agents 0.0.0-b342dcf → 0.0.0-b4ebb44
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 +31 -5
- package/dist/ai-chat-agent.js +119 -115
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +17 -4
- package/dist/ai-react.js +28 -29
- package/dist/ai-react.js.map +1 -1
- package/dist/chunk-767EASBA.js +106 -0
- package/dist/chunk-767EASBA.js.map +1 -0
- package/dist/{chunk-WNICV3OI.js → chunk-E3LCYPCB.js} +70 -37
- package/dist/chunk-E3LCYPCB.js.map +1 -0
- package/dist/chunk-NKZZ66QY.js +116 -0
- package/dist/chunk-NKZZ66QY.js.map +1 -0
- package/dist/{chunk-UAKVEVG5.js → chunk-ZRRXJUAA.js} +344 -162
- package/dist/chunk-ZRRXJUAA.js.map +1 -0
- package/dist/client.d.ts +15 -1
- package/dist/client.js +6 -126
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +110 -13
- package/dist/index.js +4 -3
- package/dist/mcp/client.d.ts +31 -16
- 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 +20 -10
- package/dist/mcp/index.js +148 -173
- package/dist/mcp/index.js.map +1 -1
- package/dist/react.d.ts +85 -5
- package/dist/react.js +20 -8
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +2 -2
- package/dist/schedule.js +4 -6
- package/dist/schedule.js.map +1 -1
- package/dist/serializable.d.ts +32 -0
- package/dist/serializable.js +1 -0
- package/package.json +71 -68
- package/src/index.ts +400 -85
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-UAKVEVG5.js.map +0 -1
- package/dist/chunk-WNICV3OI.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → serializable.js.map} +0 -0
package/src/index.ts
CHANGED
|
@@ -1,20 +1,30 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
3
|
+
import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
4
|
+
|
|
5
|
+
import type {
|
|
6
|
+
Prompt,
|
|
7
|
+
Resource,
|
|
8
|
+
ServerCapabilities,
|
|
9
|
+
Tool,
|
|
10
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
11
|
+
import { parseCronExpression } from "cron-schedule";
|
|
12
|
+
import { nanoid } from "nanoid";
|
|
1
13
|
import {
|
|
2
|
-
Server,
|
|
3
|
-
routePartykitRequest,
|
|
4
|
-
type PartyServerOptions,
|
|
5
|
-
getServerByName,
|
|
6
14
|
type Connection,
|
|
7
15
|
type ConnectionContext,
|
|
16
|
+
getServerByName,
|
|
17
|
+
type PartyServerOptions,
|
|
18
|
+
routePartykitRequest,
|
|
19
|
+
Server,
|
|
8
20
|
type WSMessage,
|
|
9
21
|
} from "partyserver";
|
|
10
|
-
|
|
11
|
-
import { parseCronExpression } from "cron-schedule";
|
|
12
|
-
import { nanoid } from "nanoid";
|
|
13
|
-
|
|
14
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
22
|
+
import { camelCaseToKebabCase } from "./client";
|
|
15
23
|
import { MCPClientManager } from "./mcp/client";
|
|
24
|
+
// import type { MCPClientConnection } from "./mcp/client-connection";
|
|
25
|
+
import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
|
|
16
26
|
|
|
17
|
-
export type { Connection,
|
|
27
|
+
export type { Connection, ConnectionContext, WSMessage } from "partyserver";
|
|
18
28
|
|
|
19
29
|
/**
|
|
20
30
|
* RPC request message from client
|
|
@@ -98,7 +108,6 @@ export type CallableMetadata = {
|
|
|
98
108
|
streaming?: boolean;
|
|
99
109
|
};
|
|
100
110
|
|
|
101
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
102
111
|
const callableMetadata = new Map<Function, CallableMetadata>();
|
|
103
112
|
|
|
104
113
|
/**
|
|
@@ -108,6 +117,7 @@ const callableMetadata = new Map<Function, CallableMetadata>();
|
|
|
108
117
|
export function unstable_callable(metadata: CallableMetadata = {}) {
|
|
109
118
|
return function callableDecorator<This, Args extends unknown[], Return>(
|
|
110
119
|
target: (this: This, ...args: Args) => Return,
|
|
120
|
+
// biome-ignore lint/correctness/noUnusedFunctionParameters: later
|
|
111
121
|
context: ClassMethodDecoratorContext
|
|
112
122
|
) {
|
|
113
123
|
if (!callableMetadata.has(target)) {
|
|
@@ -159,6 +169,48 @@ function getNextCronTime(cron: string) {
|
|
|
159
169
|
return interval.getNextDate();
|
|
160
170
|
}
|
|
161
171
|
|
|
172
|
+
/**
|
|
173
|
+
* MCP Server state update message from server -> Client
|
|
174
|
+
*/
|
|
175
|
+
export type MCPServerMessage = {
|
|
176
|
+
type: "cf_agent_mcp_servers";
|
|
177
|
+
mcp: MCPServersState;
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
export type MCPServersState = {
|
|
181
|
+
servers: {
|
|
182
|
+
[id: string]: MCPServer;
|
|
183
|
+
};
|
|
184
|
+
tools: Tool[];
|
|
185
|
+
prompts: Prompt[];
|
|
186
|
+
resources: Resource[];
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
export type MCPServer = {
|
|
190
|
+
name: string;
|
|
191
|
+
server_url: string;
|
|
192
|
+
auth_url: string | null;
|
|
193
|
+
// This state is specifically about the temporary process of getting a token (if needed).
|
|
194
|
+
// Scope outside of that can't be relied upon because when the DO sleeps, there's no way
|
|
195
|
+
// to communicate a change to a non-ready state.
|
|
196
|
+
state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
|
|
197
|
+
instructions: string | null;
|
|
198
|
+
capabilities: ServerCapabilities | null;
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* MCP Server data stored in DO SQL for resuming MCP Server connections
|
|
203
|
+
*/
|
|
204
|
+
type MCPServerRow = {
|
|
205
|
+
id: string;
|
|
206
|
+
name: string;
|
|
207
|
+
server_url: string;
|
|
208
|
+
client_id: string | null;
|
|
209
|
+
auth_url: string | null;
|
|
210
|
+
callback_url: string;
|
|
211
|
+
server_options: string;
|
|
212
|
+
};
|
|
213
|
+
|
|
162
214
|
const STATE_ROW_ID = "cf_state_row_id";
|
|
163
215
|
const STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
164
216
|
|
|
@@ -173,7 +225,7 @@ const agentContext = new AsyncLocalStorage<{
|
|
|
173
225
|
export function getCurrentAgent<
|
|
174
226
|
T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
|
|
175
227
|
>(): {
|
|
176
|
-
agent: T;
|
|
228
|
+
agent: T | undefined;
|
|
177
229
|
connection: Connection | undefined;
|
|
178
230
|
request: Request<unknown, CfProperties<unknown>> | undefined;
|
|
179
231
|
} {
|
|
@@ -185,9 +237,11 @@ export function getCurrentAgent<
|
|
|
185
237
|
}
|
|
186
238
|
| undefined;
|
|
187
239
|
if (!store) {
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
240
|
+
return {
|
|
241
|
+
agent: undefined,
|
|
242
|
+
connection: undefined,
|
|
243
|
+
request: undefined,
|
|
244
|
+
};
|
|
191
245
|
}
|
|
192
246
|
return store;
|
|
193
247
|
}
|
|
@@ -198,12 +252,12 @@ export function getCurrentAgent<
|
|
|
198
252
|
* @template State State type to store within the Agent
|
|
199
253
|
*/
|
|
200
254
|
export class Agent<Env, State = unknown> extends Server<Env> {
|
|
201
|
-
|
|
255
|
+
private _state = DEFAULT_STATE as State;
|
|
202
256
|
|
|
203
|
-
|
|
257
|
+
private _ParentClass: typeof Agent<Env, State> =
|
|
204
258
|
Object.getPrototypeOf(this).constructor;
|
|
205
259
|
|
|
206
|
-
mcp: MCPClientManager = new MCPClientManager(this
|
|
260
|
+
mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
207
261
|
|
|
208
262
|
/**
|
|
209
263
|
* Initial state for the Agent
|
|
@@ -215,9 +269,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
215
269
|
* Current state of the Agent
|
|
216
270
|
*/
|
|
217
271
|
get state(): State {
|
|
218
|
-
if (this
|
|
272
|
+
if (this._state !== DEFAULT_STATE) {
|
|
219
273
|
// state was previously set, and populated internal state
|
|
220
|
-
return this
|
|
274
|
+
return this._state;
|
|
221
275
|
}
|
|
222
276
|
// looks like this is the first time the state is being accessed
|
|
223
277
|
// check if the state was set in a previous life
|
|
@@ -237,8 +291,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
237
291
|
) {
|
|
238
292
|
const state = result[0]?.state as string; // could be null?
|
|
239
293
|
|
|
240
|
-
this
|
|
241
|
-
return this
|
|
294
|
+
this._state = JSON.parse(state);
|
|
295
|
+
return this._state;
|
|
242
296
|
}
|
|
243
297
|
|
|
244
298
|
// ok, this is the first time the state is being accessed
|
|
@@ -299,7 +353,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
299
353
|
`;
|
|
300
354
|
|
|
301
355
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
302
|
-
return this
|
|
356
|
+
return this._tryCatch(async () => {
|
|
303
357
|
// Create alarms table if it doesn't exist
|
|
304
358
|
this.sql`
|
|
305
359
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
@@ -319,25 +373,65 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
319
373
|
});
|
|
320
374
|
});
|
|
321
375
|
|
|
376
|
+
this.sql`
|
|
377
|
+
CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
|
|
378
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
379
|
+
name TEXT NOT NULL,
|
|
380
|
+
server_url TEXT NOT NULL,
|
|
381
|
+
callback_url TEXT NOT NULL,
|
|
382
|
+
client_id TEXT,
|
|
383
|
+
auth_url TEXT,
|
|
384
|
+
server_options TEXT
|
|
385
|
+
)
|
|
386
|
+
`;
|
|
387
|
+
|
|
388
|
+
const _onRequest = this.onRequest.bind(this);
|
|
389
|
+
this.onRequest = (request: Request) => {
|
|
390
|
+
return agentContext.run(
|
|
391
|
+
{ agent: this, connection: undefined, request },
|
|
392
|
+
async () => {
|
|
393
|
+
if (this.mcp.isCallbackRequest(request)) {
|
|
394
|
+
await this.mcp.handleCallbackRequest(request);
|
|
395
|
+
|
|
396
|
+
// after the MCP connection handshake, we can send updated mcp state
|
|
397
|
+
this.broadcast(
|
|
398
|
+
JSON.stringify({
|
|
399
|
+
mcp: this.getMcpServers(),
|
|
400
|
+
type: "cf_agent_mcp_servers",
|
|
401
|
+
})
|
|
402
|
+
);
|
|
403
|
+
|
|
404
|
+
// We probably should let the user configure this response/redirect, but this is fine for now.
|
|
405
|
+
return new Response("<script>window.close();</script>", {
|
|
406
|
+
headers: { "content-type": "text/html" },
|
|
407
|
+
status: 200,
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
return this._tryCatch(() => _onRequest(request));
|
|
412
|
+
}
|
|
413
|
+
);
|
|
414
|
+
};
|
|
415
|
+
|
|
322
416
|
const _onMessage = this.onMessage.bind(this);
|
|
323
417
|
this.onMessage = async (connection: Connection, message: WSMessage) => {
|
|
324
418
|
return agentContext.run(
|
|
325
419
|
{ agent: this, connection, request: undefined },
|
|
326
420
|
async () => {
|
|
327
421
|
if (typeof message !== "string") {
|
|
328
|
-
return this
|
|
422
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
329
423
|
}
|
|
330
424
|
|
|
331
425
|
let parsed: unknown;
|
|
332
426
|
try {
|
|
333
427
|
parsed = JSON.parse(message);
|
|
334
|
-
} catch (
|
|
428
|
+
} catch (_e) {
|
|
335
429
|
// silently fail and let the onMessage handler handle it
|
|
336
|
-
return this
|
|
430
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
337
431
|
}
|
|
338
432
|
|
|
339
433
|
if (isStateUpdateMessage(parsed)) {
|
|
340
|
-
this
|
|
434
|
+
this._setStateInternal(parsed.state as State, connection);
|
|
341
435
|
return;
|
|
342
436
|
}
|
|
343
437
|
|
|
@@ -351,11 +445,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
351
445
|
throw new Error(`Method ${method} does not exist`);
|
|
352
446
|
}
|
|
353
447
|
|
|
354
|
-
if (!this
|
|
448
|
+
if (!this._isCallable(method)) {
|
|
355
449
|
throw new Error(`Method ${method} is not callable`);
|
|
356
450
|
}
|
|
357
451
|
|
|
358
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
359
452
|
const metadata = callableMetadata.get(methodFn as Function);
|
|
360
453
|
|
|
361
454
|
// For streaming methods, pass a StreamingResponse object
|
|
@@ -368,21 +461,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
368
461
|
// For regular methods, execute and send response
|
|
369
462
|
const result = await methodFn.apply(this, args);
|
|
370
463
|
const response: RPCResponse = {
|
|
371
|
-
|
|
464
|
+
done: true,
|
|
372
465
|
id,
|
|
373
|
-
success: true,
|
|
374
466
|
result,
|
|
375
|
-
|
|
467
|
+
success: true,
|
|
468
|
+
type: "rpc",
|
|
376
469
|
};
|
|
377
470
|
connection.send(JSON.stringify(response));
|
|
378
471
|
} catch (e) {
|
|
379
472
|
// Send error response
|
|
380
473
|
const response: RPCResponse = {
|
|
381
|
-
type: "rpc",
|
|
382
|
-
id: parsed.id,
|
|
383
|
-
success: false,
|
|
384
474
|
error:
|
|
385
475
|
e instanceof Error ? e.message : "Unknown error occurred",
|
|
476
|
+
id: parsed.id,
|
|
477
|
+
success: false,
|
|
478
|
+
type: "rpc",
|
|
386
479
|
};
|
|
387
480
|
connection.send(JSON.stringify(response));
|
|
388
481
|
console.error("RPC error:", e);
|
|
@@ -390,7 +483,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
390
483
|
return;
|
|
391
484
|
}
|
|
392
485
|
|
|
393
|
-
return this
|
|
486
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
394
487
|
}
|
|
395
488
|
);
|
|
396
489
|
};
|
|
@@ -406,20 +499,72 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
406
499
|
if (this.state) {
|
|
407
500
|
connection.send(
|
|
408
501
|
JSON.stringify({
|
|
409
|
-
type: "cf_agent_state",
|
|
410
502
|
state: this.state,
|
|
503
|
+
type: "cf_agent_state",
|
|
411
504
|
})
|
|
412
505
|
);
|
|
413
506
|
}
|
|
414
|
-
|
|
507
|
+
|
|
508
|
+
connection.send(
|
|
509
|
+
JSON.stringify({
|
|
510
|
+
mcp: this.getMcpServers(),
|
|
511
|
+
type: "cf_agent_mcp_servers",
|
|
512
|
+
})
|
|
513
|
+
);
|
|
514
|
+
|
|
515
|
+
return this._tryCatch(() => _onConnect(connection, ctx));
|
|
415
516
|
}, 20);
|
|
416
517
|
}
|
|
417
518
|
);
|
|
418
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 not currently in the oauth flow using our saved auth information
|
|
531
|
+
await Promise.allSettled(
|
|
532
|
+
servers
|
|
533
|
+
.filter((server) => server.auth_url === null)
|
|
534
|
+
.map((server) => {
|
|
535
|
+
return this._connectToMcpServerInternal(
|
|
536
|
+
server.name,
|
|
537
|
+
server.server_url,
|
|
538
|
+
server.callback_url,
|
|
539
|
+
server.server_options
|
|
540
|
+
? JSON.parse(server.server_options)
|
|
541
|
+
: undefined,
|
|
542
|
+
{
|
|
543
|
+
id: server.id,
|
|
544
|
+
oauthClientId: server.client_id ?? undefined,
|
|
545
|
+
}
|
|
546
|
+
);
|
|
547
|
+
})
|
|
548
|
+
);
|
|
549
|
+
|
|
550
|
+
this.broadcast(
|
|
551
|
+
JSON.stringify({
|
|
552
|
+
mcp: this.getMcpServers(),
|
|
553
|
+
type: "cf_agent_mcp_servers",
|
|
554
|
+
})
|
|
555
|
+
);
|
|
556
|
+
|
|
557
|
+
await this._tryCatch(() => _onStart());
|
|
558
|
+
}
|
|
559
|
+
);
|
|
560
|
+
};
|
|
419
561
|
}
|
|
420
562
|
|
|
421
|
-
|
|
422
|
-
|
|
563
|
+
private _setStateInternal(
|
|
564
|
+
state: State,
|
|
565
|
+
source: Connection | "server" = "server"
|
|
566
|
+
) {
|
|
567
|
+
this._state = state;
|
|
423
568
|
this.sql`
|
|
424
569
|
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
425
570
|
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
@@ -430,12 +575,12 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
430
575
|
`;
|
|
431
576
|
this.broadcast(
|
|
432
577
|
JSON.stringify({
|
|
433
|
-
type: "cf_agent_state",
|
|
434
578
|
state: state,
|
|
579
|
+
type: "cf_agent_state",
|
|
435
580
|
}),
|
|
436
581
|
source !== "server" ? [source.id] : []
|
|
437
582
|
);
|
|
438
|
-
return this
|
|
583
|
+
return this._tryCatch(() => {
|
|
439
584
|
const { connection, request } = agentContext.getStore() || {};
|
|
440
585
|
return agentContext.run(
|
|
441
586
|
{ agent: this, connection, request },
|
|
@@ -451,7 +596,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
451
596
|
* @param state New state to set
|
|
452
597
|
*/
|
|
453
598
|
setState(state: State) {
|
|
454
|
-
this
|
|
599
|
+
this._setStateInternal(state, "server");
|
|
455
600
|
}
|
|
456
601
|
|
|
457
602
|
/**
|
|
@@ -459,6 +604,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
459
604
|
* @param state Updated state
|
|
460
605
|
* @param source Source of the state update ("server" or a client connection)
|
|
461
606
|
*/
|
|
607
|
+
// biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
|
|
462
608
|
onStateUpdate(state: State | undefined, source: Connection | "server") {
|
|
463
609
|
// override this to handle state updates
|
|
464
610
|
}
|
|
@@ -467,6 +613,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
467
613
|
* Called when the Agent receives an email
|
|
468
614
|
* @param email Email message to process
|
|
469
615
|
*/
|
|
616
|
+
// biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
|
|
470
617
|
onEmail(email: ForwardableEmailMessage) {
|
|
471
618
|
return agentContext.run(
|
|
472
619
|
{ agent: this, connection: undefined, request: undefined },
|
|
@@ -476,7 +623,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
476
623
|
);
|
|
477
624
|
}
|
|
478
625
|
|
|
479
|
-
async
|
|
626
|
+
private async _tryCatch<T>(fn: () => T | Promise<T>) {
|
|
480
627
|
try {
|
|
481
628
|
return await fn();
|
|
482
629
|
} catch (e) {
|
|
@@ -550,11 +697,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
550
697
|
)}, 'scheduled', ${timestamp})
|
|
551
698
|
`;
|
|
552
699
|
|
|
553
|
-
await this
|
|
700
|
+
await this._scheduleNextAlarm();
|
|
554
701
|
|
|
555
702
|
return {
|
|
556
|
-
id,
|
|
557
703
|
callback: callback,
|
|
704
|
+
id,
|
|
558
705
|
payload: payload as T,
|
|
559
706
|
time: timestamp,
|
|
560
707
|
type: "scheduled",
|
|
@@ -571,13 +718,13 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
571
718
|
)}, 'delayed', ${when}, ${timestamp})
|
|
572
719
|
`;
|
|
573
720
|
|
|
574
|
-
await this
|
|
721
|
+
await this._scheduleNextAlarm();
|
|
575
722
|
|
|
576
723
|
return {
|
|
577
|
-
id,
|
|
578
724
|
callback: callback,
|
|
579
|
-
payload: payload as T,
|
|
580
725
|
delayInSeconds: when,
|
|
726
|
+
id,
|
|
727
|
+
payload: payload as T,
|
|
581
728
|
time: timestamp,
|
|
582
729
|
type: "delayed",
|
|
583
730
|
};
|
|
@@ -593,13 +740,13 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
593
740
|
)}, 'cron', ${when}, ${timestamp})
|
|
594
741
|
`;
|
|
595
742
|
|
|
596
|
-
await this
|
|
743
|
+
await this._scheduleNextAlarm();
|
|
597
744
|
|
|
598
745
|
return {
|
|
599
|
-
id,
|
|
600
746
|
callback: callback,
|
|
601
|
-
payload: payload as T,
|
|
602
747
|
cron: when,
|
|
748
|
+
id,
|
|
749
|
+
payload: payload as T,
|
|
603
750
|
time: timestamp,
|
|
604
751
|
type: "cron",
|
|
605
752
|
};
|
|
@@ -680,11 +827,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
680
827
|
async cancelSchedule(id: string): Promise<boolean> {
|
|
681
828
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
682
829
|
|
|
683
|
-
await this
|
|
830
|
+
await this._scheduleNextAlarm();
|
|
684
831
|
return true;
|
|
685
832
|
}
|
|
686
833
|
|
|
687
|
-
async
|
|
834
|
+
private async _scheduleNextAlarm() {
|
|
688
835
|
// Find the next schedule that needs to be executed
|
|
689
836
|
const result = this.sql`
|
|
690
837
|
SELECT time FROM cf_agents_schedules
|
|
@@ -701,10 +848,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
701
848
|
}
|
|
702
849
|
|
|
703
850
|
/**
|
|
704
|
-
* Method called when an alarm fires
|
|
705
|
-
* Executes any scheduled tasks that are due
|
|
851
|
+
* Method called when an alarm fires.
|
|
852
|
+
* Executes any scheduled tasks that are due.
|
|
853
|
+
*
|
|
854
|
+
* @remarks
|
|
855
|
+
* To schedule a task, please use the `this.schedule` method instead.
|
|
856
|
+
* See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
|
|
706
857
|
*/
|
|
707
|
-
async
|
|
858
|
+
public readonly alarm = async () => {
|
|
708
859
|
const now = Math.floor(Date.now() / 1000);
|
|
709
860
|
|
|
710
861
|
// Get all schedules that should be executed now
|
|
@@ -750,8 +901,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
750
901
|
}
|
|
751
902
|
|
|
752
903
|
// Schedule the next alarm
|
|
753
|
-
await this
|
|
754
|
-
}
|
|
904
|
+
await this._scheduleNextAlarm();
|
|
905
|
+
};
|
|
755
906
|
|
|
756
907
|
/**
|
|
757
908
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -760,20 +911,184 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
760
911
|
// drop all tables
|
|
761
912
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
762
913
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
914
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
763
915
|
|
|
764
916
|
// delete all alarms
|
|
765
917
|
await this.ctx.storage.deleteAlarm();
|
|
766
918
|
await this.ctx.storage.deleteAll();
|
|
919
|
+
this.ctx.abort("destroyed"); // enforce that the agent is evicted
|
|
767
920
|
}
|
|
768
921
|
|
|
769
922
|
/**
|
|
770
923
|
* Get all methods marked as callable on this Agent
|
|
771
924
|
* @returns A map of method names to their metadata
|
|
772
925
|
*/
|
|
773
|
-
|
|
774
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
926
|
+
private _isCallable(method: string): boolean {
|
|
775
927
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
776
928
|
}
|
|
929
|
+
|
|
930
|
+
/**
|
|
931
|
+
* Connect to a new MCP Server
|
|
932
|
+
*
|
|
933
|
+
* @param url MCP Server SSE URL
|
|
934
|
+
* @param callbackHost Base host for the agent, used for the redirect URI.
|
|
935
|
+
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
936
|
+
* @param options MCP client and transport (header) options
|
|
937
|
+
* @returns authUrl
|
|
938
|
+
*/
|
|
939
|
+
async addMcpServer(
|
|
940
|
+
serverName: string,
|
|
941
|
+
url: string,
|
|
942
|
+
callbackHost: string,
|
|
943
|
+
agentsPrefix = "agents",
|
|
944
|
+
options?: {
|
|
945
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
946
|
+
transport?: {
|
|
947
|
+
headers: HeadersInit;
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
951
|
+
const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
952
|
+
|
|
953
|
+
const result = await this._connectToMcpServerInternal(
|
|
954
|
+
serverName,
|
|
955
|
+
url,
|
|
956
|
+
callbackUrl,
|
|
957
|
+
options
|
|
958
|
+
);
|
|
959
|
+
|
|
960
|
+
this.broadcast(
|
|
961
|
+
JSON.stringify({
|
|
962
|
+
mcp: this.getMcpServers(),
|
|
963
|
+
type: "cf_agent_mcp_servers",
|
|
964
|
+
})
|
|
965
|
+
);
|
|
966
|
+
|
|
967
|
+
return result;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
async _connectToMcpServerInternal(
|
|
971
|
+
serverName: string,
|
|
972
|
+
url: string,
|
|
973
|
+
callbackUrl: string,
|
|
974
|
+
// it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
|
|
975
|
+
options?: {
|
|
976
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
977
|
+
/**
|
|
978
|
+
* We don't expose the normal set of transport options because:
|
|
979
|
+
* 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
|
|
980
|
+
* 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
|
|
981
|
+
*
|
|
982
|
+
* 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).
|
|
983
|
+
*/
|
|
984
|
+
transport?: {
|
|
985
|
+
headers?: HeadersInit;
|
|
986
|
+
};
|
|
987
|
+
},
|
|
988
|
+
reconnect?: {
|
|
989
|
+
id: string;
|
|
990
|
+
oauthClientId?: string;
|
|
991
|
+
}
|
|
992
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
993
|
+
const authProvider = new DurableObjectOAuthClientProvider(
|
|
994
|
+
this.ctx.storage,
|
|
995
|
+
this.name,
|
|
996
|
+
callbackUrl
|
|
997
|
+
);
|
|
998
|
+
|
|
999
|
+
if (reconnect) {
|
|
1000
|
+
authProvider.serverId = reconnect.id;
|
|
1001
|
+
if (reconnect.oauthClientId) {
|
|
1002
|
+
authProvider.clientId = reconnect.oauthClientId;
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
// allows passing through transport headers if necessary
|
|
1007
|
+
// this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
|
|
1008
|
+
let headerTransportOpts: SSEClientTransportOptions = {};
|
|
1009
|
+
if (options?.transport?.headers) {
|
|
1010
|
+
headerTransportOpts = {
|
|
1011
|
+
eventSourceInit: {
|
|
1012
|
+
fetch: (url, init) =>
|
|
1013
|
+
fetch(url, {
|
|
1014
|
+
...init,
|
|
1015
|
+
headers: options?.transport?.headers,
|
|
1016
|
+
}),
|
|
1017
|
+
},
|
|
1018
|
+
requestInit: {
|
|
1019
|
+
headers: options?.transport?.headers,
|
|
1020
|
+
},
|
|
1021
|
+
};
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
const { id, authUrl, clientId } = await this.mcp.connect(url, {
|
|
1025
|
+
client: options?.client,
|
|
1026
|
+
reconnect,
|
|
1027
|
+
transport: {
|
|
1028
|
+
...headerTransportOpts,
|
|
1029
|
+
authProvider,
|
|
1030
|
+
},
|
|
1031
|
+
});
|
|
1032
|
+
|
|
1033
|
+
this.sql`
|
|
1034
|
+
INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
1035
|
+
VALUES (
|
|
1036
|
+
${id},
|
|
1037
|
+
${serverName},
|
|
1038
|
+
${url},
|
|
1039
|
+
${clientId ?? null},
|
|
1040
|
+
${authUrl ?? null},
|
|
1041
|
+
${callbackUrl},
|
|
1042
|
+
${options ? JSON.stringify(options) : null}
|
|
1043
|
+
);
|
|
1044
|
+
`;
|
|
1045
|
+
|
|
1046
|
+
return {
|
|
1047
|
+
authUrl,
|
|
1048
|
+
id,
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
async removeMcpServer(id: string) {
|
|
1053
|
+
this.mcp.closeConnection(id);
|
|
1054
|
+
this.sql`
|
|
1055
|
+
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
1056
|
+
`;
|
|
1057
|
+
this.broadcast(
|
|
1058
|
+
JSON.stringify({
|
|
1059
|
+
mcp: this.getMcpServers(),
|
|
1060
|
+
type: "cf_agent_mcp_servers",
|
|
1061
|
+
})
|
|
1062
|
+
);
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
getMcpServers(): MCPServersState {
|
|
1066
|
+
const mcpState: MCPServersState = {
|
|
1067
|
+
prompts: this.mcp.listPrompts(),
|
|
1068
|
+
resources: this.mcp.listResources(),
|
|
1069
|
+
servers: {},
|
|
1070
|
+
tools: this.mcp.listTools(),
|
|
1071
|
+
};
|
|
1072
|
+
|
|
1073
|
+
const servers = this.sql<MCPServerRow>`
|
|
1074
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
1075
|
+
`;
|
|
1076
|
+
|
|
1077
|
+
for (const server of servers) {
|
|
1078
|
+
const serverConn = this.mcp.mcpConnections[server.id];
|
|
1079
|
+
mcpState.servers[server.id] = {
|
|
1080
|
+
auth_url: server.auth_url,
|
|
1081
|
+
capabilities: serverConn?.serverCapabilities ?? null,
|
|
1082
|
+
instructions: serverConn?.instructions ?? null,
|
|
1083
|
+
name: server.name,
|
|
1084
|
+
server_url: server.server_url,
|
|
1085
|
+
// mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
|
|
1086
|
+
state: serverConn?.connectionState ?? "authenticating",
|
|
1087
|
+
};
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
return mcpState;
|
|
1091
|
+
}
|
|
777
1092
|
}
|
|
778
1093
|
|
|
779
1094
|
/**
|
|
@@ -813,9 +1128,9 @@ export async function routeAgentRequest<Env>(
|
|
|
813
1128
|
const corsHeaders =
|
|
814
1129
|
options?.cors === true
|
|
815
1130
|
? {
|
|
816
|
-
"Access-Control-Allow-Origin": "*",
|
|
817
|
-
"Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
|
|
818
1131
|
"Access-Control-Allow-Credentials": "true",
|
|
1132
|
+
"Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
|
|
1133
|
+
"Access-Control-Allow-Origin": "*",
|
|
819
1134
|
"Access-Control-Max-Age": "86400",
|
|
820
1135
|
}
|
|
821
1136
|
: options?.cors;
|
|
@@ -863,9 +1178,9 @@ export async function routeAgentRequest<Env>(
|
|
|
863
1178
|
* @param options Routing options
|
|
864
1179
|
*/
|
|
865
1180
|
export async function routeAgentEmail<Env>(
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
1181
|
+
_email: ForwardableEmailMessage,
|
|
1182
|
+
_env: Env,
|
|
1183
|
+
_options?: AgentOptions<Env>
|
|
869
1184
|
): Promise<void> {}
|
|
870
1185
|
|
|
871
1186
|
/**
|
|
@@ -877,7 +1192,7 @@ export async function routeAgentEmail<Env>(
|
|
|
877
1192
|
* @param options Options for Agent creation
|
|
878
1193
|
* @returns Promise resolving to an Agent instance stub
|
|
879
1194
|
*/
|
|
880
|
-
export function getAgentByName<Env, T extends Agent<Env>>(
|
|
1195
|
+
export async function getAgentByName<Env, T extends Agent<Env>>(
|
|
881
1196
|
namespace: AgentNamespace<T>,
|
|
882
1197
|
name: string,
|
|
883
1198
|
options?: {
|
|
@@ -892,13 +1207,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
|
|
|
892
1207
|
* A wrapper for streaming responses in callable methods
|
|
893
1208
|
*/
|
|
894
1209
|
export class StreamingResponse {
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
1210
|
+
private _connection: Connection;
|
|
1211
|
+
private _id: string;
|
|
1212
|
+
private _closed = false;
|
|
898
1213
|
|
|
899
1214
|
constructor(connection: Connection, id: string) {
|
|
900
|
-
this
|
|
901
|
-
this
|
|
1215
|
+
this._connection = connection;
|
|
1216
|
+
this._id = id;
|
|
902
1217
|
}
|
|
903
1218
|
|
|
904
1219
|
/**
|
|
@@ -906,17 +1221,17 @@ export class StreamingResponse {
|
|
|
906
1221
|
* @param chunk The data to send
|
|
907
1222
|
*/
|
|
908
1223
|
send(chunk: unknown) {
|
|
909
|
-
if (this
|
|
1224
|
+
if (this._closed) {
|
|
910
1225
|
throw new Error("StreamingResponse is already closed");
|
|
911
1226
|
}
|
|
912
1227
|
const response: RPCResponse = {
|
|
913
|
-
type: "rpc",
|
|
914
|
-
id: this.#id,
|
|
915
|
-
success: true,
|
|
916
|
-
result: chunk,
|
|
917
1228
|
done: false,
|
|
1229
|
+
id: this._id,
|
|
1230
|
+
result: chunk,
|
|
1231
|
+
success: true,
|
|
1232
|
+
type: "rpc",
|
|
918
1233
|
};
|
|
919
|
-
this
|
|
1234
|
+
this._connection.send(JSON.stringify(response));
|
|
920
1235
|
}
|
|
921
1236
|
|
|
922
1237
|
/**
|
|
@@ -924,17 +1239,17 @@ export class StreamingResponse {
|
|
|
924
1239
|
* @param finalChunk Optional final chunk of data to send
|
|
925
1240
|
*/
|
|
926
1241
|
end(finalChunk?: unknown) {
|
|
927
|
-
if (this
|
|
1242
|
+
if (this._closed) {
|
|
928
1243
|
throw new Error("StreamingResponse is already closed");
|
|
929
1244
|
}
|
|
930
|
-
this
|
|
1245
|
+
this._closed = true;
|
|
931
1246
|
const response: RPCResponse = {
|
|
932
|
-
type: "rpc",
|
|
933
|
-
id: this.#id,
|
|
934
|
-
success: true,
|
|
935
|
-
result: finalChunk,
|
|
936
1247
|
done: true,
|
|
1248
|
+
id: this._id,
|
|
1249
|
+
result: finalChunk,
|
|
1250
|
+
success: true,
|
|
1251
|
+
type: "rpc",
|
|
937
1252
|
};
|
|
938
|
-
this
|
|
1253
|
+
this._connection.send(JSON.stringify(response));
|
|
939
1254
|
}
|
|
940
1255
|
}
|