agents 0.0.0-d7d2876 → 0.0.0-db0351e
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/README.md +2 -6
- package/dist/ai-chat-agent.d.ts +49 -3
- package/dist/ai-chat-agent.js +129 -69
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +18 -3
- 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-VCSB47AK.js +116 -0
- package/dist/chunk-VCSB47AK.js.map +1 -0
- package/dist/chunk-VNSFDJYL.js +783 -0
- package/dist/chunk-VNSFDJYL.js.map +1 -0
- package/dist/chunk-Y67CHZBI.js +464 -0
- package/dist/chunk-Y67CHZBI.js.map +1 -0
- package/dist/client.d.ts +15 -1
- package/dist/client.js +6 -133
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +122 -13
- package/dist/index.js +6 -4
- 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 +85 -5
- package/dist/react.js +48 -29
- package/dist/react.js.map +1 -1
- package/dist/schedule.js +0 -2
- package/dist/schedule.js.map +1 -1
- package/dist/serializable.d.ts +32 -0
- package/dist/serializable.js +1 -0
- package/dist/serializable.js.map +1 -0
- package/package.json +41 -5
- package/src/index.ts +486 -124
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-X6BBKLSC.js +0 -568
- package/dist/chunk-X6BBKLSC.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → mcp/client.js.map} +0 -0
package/src/index.ts
CHANGED
|
@@ -11,9 +11,25 @@ import {
|
|
|
11
11
|
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
|
+
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";
|
|
15
31
|
|
|
16
|
-
|
|
32
|
+
export type { Connection, WSMessage, ConnectionContext } from "partyserver";
|
|
17
33
|
|
|
18
34
|
/**
|
|
19
35
|
* RPC request message from client
|
|
@@ -97,7 +113,6 @@ export type CallableMetadata = {
|
|
|
97
113
|
streaming?: boolean;
|
|
98
114
|
};
|
|
99
115
|
|
|
100
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
101
116
|
const callableMetadata = new Map<Function, CallableMetadata>();
|
|
102
117
|
|
|
103
118
|
/**
|
|
@@ -117,11 +132,6 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
|
|
|
117
132
|
};
|
|
118
133
|
}
|
|
119
134
|
|
|
120
|
-
/**
|
|
121
|
-
* A class for creating workflow entry points that can be used with Cloudflare Workers
|
|
122
|
-
*/
|
|
123
|
-
export class WorkflowEntrypoint extends CFWorkflowEntrypoint {}
|
|
124
|
-
|
|
125
135
|
/**
|
|
126
136
|
* Represents a scheduled task within an Agent
|
|
127
137
|
* @template T Type of the payload data
|
|
@@ -163,18 +173,92 @@ function getNextCronTime(cron: string) {
|
|
|
163
173
|
return interval.getNextDate();
|
|
164
174
|
}
|
|
165
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
|
+
|
|
166
215
|
const STATE_ROW_ID = "cf_state_row_id";
|
|
167
216
|
const STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
168
217
|
|
|
169
218
|
const DEFAULT_STATE = {} as unknown;
|
|
170
219
|
|
|
220
|
+
const agentContext = new AsyncLocalStorage<{
|
|
221
|
+
agent: Agent<unknown>;
|
|
222
|
+
connection: Connection | undefined;
|
|
223
|
+
request: Request | undefined;
|
|
224
|
+
}>();
|
|
225
|
+
|
|
226
|
+
export function getCurrentAgent<
|
|
227
|
+
T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
|
|
228
|
+
>(): {
|
|
229
|
+
agent: T | undefined;
|
|
230
|
+
connection: Connection | undefined;
|
|
231
|
+
request: Request<unknown, CfProperties<unknown>> | undefined;
|
|
232
|
+
} {
|
|
233
|
+
const store = agentContext.getStore() as
|
|
234
|
+
| {
|
|
235
|
+
agent: T;
|
|
236
|
+
connection: Connection | undefined;
|
|
237
|
+
request: Request<unknown, CfProperties<unknown>> | undefined;
|
|
238
|
+
}
|
|
239
|
+
| undefined;
|
|
240
|
+
if (!store) {
|
|
241
|
+
return {
|
|
242
|
+
agent: undefined,
|
|
243
|
+
connection: undefined,
|
|
244
|
+
request: undefined,
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
return store;
|
|
248
|
+
}
|
|
249
|
+
|
|
171
250
|
/**
|
|
172
251
|
* Base class for creating Agent implementations
|
|
173
252
|
* @template Env Environment type containing bindings
|
|
174
253
|
* @template State State type to store within the Agent
|
|
175
254
|
*/
|
|
176
255
|
export class Agent<Env, State = unknown> extends Server<Env> {
|
|
177
|
-
|
|
256
|
+
private _state = DEFAULT_STATE as State;
|
|
257
|
+
|
|
258
|
+
private _ParentClass: typeof Agent<Env, State> =
|
|
259
|
+
Object.getPrototypeOf(this).constructor;
|
|
260
|
+
|
|
261
|
+
mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
178
262
|
|
|
179
263
|
/**
|
|
180
264
|
* Initial state for the Agent
|
|
@@ -186,9 +270,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
186
270
|
* Current state of the Agent
|
|
187
271
|
*/
|
|
188
272
|
get state(): State {
|
|
189
|
-
if (this
|
|
273
|
+
if (this._state !== DEFAULT_STATE) {
|
|
190
274
|
// state was previously set, and populated internal state
|
|
191
|
-
return this
|
|
275
|
+
return this._state;
|
|
192
276
|
}
|
|
193
277
|
// looks like this is the first time the state is being accessed
|
|
194
278
|
// check if the state was set in a previous life
|
|
@@ -208,8 +292,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
208
292
|
) {
|
|
209
293
|
const state = result[0]?.state as string; // could be null?
|
|
210
294
|
|
|
211
|
-
this
|
|
212
|
-
return this
|
|
295
|
+
this._state = JSON.parse(state);
|
|
296
|
+
return this._state;
|
|
213
297
|
}
|
|
214
298
|
|
|
215
299
|
// ok, this is the first time the state is being accessed
|
|
@@ -270,7 +354,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
270
354
|
`;
|
|
271
355
|
|
|
272
356
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
273
|
-
return this
|
|
357
|
+
return this._tryCatch(async () => {
|
|
274
358
|
// Create alarms table if it doesn't exist
|
|
275
359
|
this.sql`
|
|
276
360
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
@@ -290,96 +374,196 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
290
374
|
});
|
|
291
375
|
});
|
|
292
376
|
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
return this.#tryCatch(() => _onMessage(connection, message));
|
|
305
|
-
}
|
|
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
|
+
`;
|
|
306
388
|
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
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
|
+
}
|
|
311
411
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
412
|
+
return this._tryCatch(() => _onRequest(request));
|
|
413
|
+
}
|
|
414
|
+
);
|
|
415
|
+
};
|
|
315
416
|
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
417
|
+
const _onMessage = this.onMessage.bind(this);
|
|
418
|
+
this.onMessage = async (connection: Connection, message: WSMessage) => {
|
|
419
|
+
return agentContext.run(
|
|
420
|
+
{ agent: this, connection, request: undefined },
|
|
421
|
+
async () => {
|
|
422
|
+
if (typeof message !== "string") {
|
|
423
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
320
424
|
}
|
|
321
425
|
|
|
322
|
-
|
|
323
|
-
|
|
426
|
+
let parsed: unknown;
|
|
427
|
+
try {
|
|
428
|
+
parsed = JSON.parse(message);
|
|
429
|
+
} catch (e) {
|
|
430
|
+
// silently fail and let the onMessage handler handle it
|
|
431
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
324
432
|
}
|
|
325
433
|
|
|
326
|
-
|
|
327
|
-
|
|
434
|
+
if (isStateUpdateMessage(parsed)) {
|
|
435
|
+
this._setStateInternal(parsed.state as State, connection);
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
328
438
|
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
439
|
+
if (isRPCRequest(parsed)) {
|
|
440
|
+
try {
|
|
441
|
+
const { id, method, args } = parsed;
|
|
442
|
+
|
|
443
|
+
// Check if method exists and is callable
|
|
444
|
+
const methodFn = this[method as keyof this];
|
|
445
|
+
if (typeof methodFn !== "function") {
|
|
446
|
+
throw new Error(`Method ${method} does not exist`);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
if (!this._isCallable(method)) {
|
|
450
|
+
throw new Error(`Method ${method} is not callable`);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const metadata = callableMetadata.get(methodFn as Function);
|
|
454
|
+
|
|
455
|
+
// For streaming methods, pass a StreamingResponse object
|
|
456
|
+
if (metadata?.streaming) {
|
|
457
|
+
const stream = new StreamingResponse(connection, id);
|
|
458
|
+
await methodFn.apply(this, [stream, ...args]);
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// For regular methods, execute and send response
|
|
463
|
+
const result = await methodFn.apply(this, args);
|
|
464
|
+
const response: RPCResponse = {
|
|
465
|
+
type: "rpc",
|
|
466
|
+
id,
|
|
467
|
+
success: true,
|
|
468
|
+
result,
|
|
469
|
+
done: true,
|
|
470
|
+
};
|
|
471
|
+
connection.send(JSON.stringify(response));
|
|
472
|
+
} catch (e) {
|
|
473
|
+
// Send error response
|
|
474
|
+
const response: RPCResponse = {
|
|
475
|
+
type: "rpc",
|
|
476
|
+
id: parsed.id,
|
|
477
|
+
success: false,
|
|
478
|
+
error:
|
|
479
|
+
e instanceof Error ? e.message : "Unknown error occurred",
|
|
480
|
+
};
|
|
481
|
+
connection.send(JSON.stringify(response));
|
|
482
|
+
console.error("RPC error:", e);
|
|
483
|
+
}
|
|
333
484
|
return;
|
|
334
485
|
}
|
|
335
486
|
|
|
336
|
-
|
|
337
|
-
const result = await methodFn.apply(this, args);
|
|
338
|
-
const response: RPCResponse = {
|
|
339
|
-
type: "rpc",
|
|
340
|
-
id,
|
|
341
|
-
success: true,
|
|
342
|
-
result,
|
|
343
|
-
done: true,
|
|
344
|
-
};
|
|
345
|
-
connection.send(JSON.stringify(response));
|
|
346
|
-
} catch (e) {
|
|
347
|
-
// Send error response
|
|
348
|
-
const response: RPCResponse = {
|
|
349
|
-
type: "rpc",
|
|
350
|
-
id: parsed.id,
|
|
351
|
-
success: false,
|
|
352
|
-
error: e instanceof Error ? e.message : "Unknown error occurred",
|
|
353
|
-
};
|
|
354
|
-
connection.send(JSON.stringify(response));
|
|
355
|
-
console.error("RPC error:", e);
|
|
487
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
356
488
|
}
|
|
357
|
-
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
return this.#tryCatch(() => _onMessage(connection, message));
|
|
489
|
+
);
|
|
361
490
|
};
|
|
362
491
|
|
|
363
492
|
const _onConnect = this.onConnect.bind(this);
|
|
364
493
|
this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
|
|
365
494
|
// TODO: This is a hack to ensure the state is sent after the connection is established
|
|
366
495
|
// must fix this
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
496
|
+
return agentContext.run(
|
|
497
|
+
{ agent: this, connection, request: ctx.request },
|
|
498
|
+
async () => {
|
|
499
|
+
setTimeout(() => {
|
|
500
|
+
if (this.state) {
|
|
501
|
+
connection.send(
|
|
502
|
+
JSON.stringify({
|
|
503
|
+
type: "cf_agent_state",
|
|
504
|
+
state: this.state,
|
|
505
|
+
})
|
|
506
|
+
);
|
|
507
|
+
}
|
|
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));
|
|
517
|
+
}, 20);
|
|
518
|
+
}
|
|
519
|
+
);
|
|
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(
|
|
370
550
|
JSON.stringify({
|
|
371
|
-
type: "
|
|
372
|
-
|
|
551
|
+
type: "cf_agent_mcp_servers",
|
|
552
|
+
mcp: this.getMcpServers(),
|
|
373
553
|
})
|
|
374
554
|
);
|
|
555
|
+
|
|
556
|
+
await this._tryCatch(() => _onStart());
|
|
375
557
|
}
|
|
376
|
-
|
|
377
|
-
}, 20);
|
|
558
|
+
);
|
|
378
559
|
};
|
|
379
560
|
}
|
|
380
561
|
|
|
381
|
-
|
|
382
|
-
|
|
562
|
+
private _setStateInternal(
|
|
563
|
+
state: State,
|
|
564
|
+
source: Connection | "server" = "server"
|
|
565
|
+
) {
|
|
566
|
+
this._state = state;
|
|
383
567
|
this.sql`
|
|
384
568
|
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
385
569
|
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
@@ -395,7 +579,15 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
395
579
|
}),
|
|
396
580
|
source !== "server" ? [source.id] : []
|
|
397
581
|
);
|
|
398
|
-
return this
|
|
582
|
+
return this._tryCatch(() => {
|
|
583
|
+
const { connection, request } = agentContext.getStore() || {};
|
|
584
|
+
return agentContext.run(
|
|
585
|
+
{ agent: this, connection, request },
|
|
586
|
+
async () => {
|
|
587
|
+
return this.onStateUpdate(state, source);
|
|
588
|
+
}
|
|
589
|
+
);
|
|
590
|
+
});
|
|
399
591
|
}
|
|
400
592
|
|
|
401
593
|
/**
|
|
@@ -403,7 +595,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
403
595
|
* @param state New state to set
|
|
404
596
|
*/
|
|
405
597
|
setState(state: State) {
|
|
406
|
-
this
|
|
598
|
+
this._setStateInternal(state, "server");
|
|
407
599
|
}
|
|
408
600
|
|
|
409
601
|
/**
|
|
@@ -420,10 +612,15 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
420
612
|
* @param email Email message to process
|
|
421
613
|
*/
|
|
422
614
|
onEmail(email: ForwardableEmailMessage) {
|
|
423
|
-
|
|
615
|
+
return agentContext.run(
|
|
616
|
+
{ agent: this, connection: undefined, request: undefined },
|
|
617
|
+
async () => {
|
|
618
|
+
console.error("onEmail not implemented");
|
|
619
|
+
}
|
|
620
|
+
);
|
|
424
621
|
}
|
|
425
622
|
|
|
426
|
-
async
|
|
623
|
+
private async _tryCatch<T>(fn: () => T | Promise<T>) {
|
|
427
624
|
try {
|
|
428
625
|
return await fn();
|
|
429
626
|
} catch (e) {
|
|
@@ -497,7 +694,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
497
694
|
)}, 'scheduled', ${timestamp})
|
|
498
695
|
`;
|
|
499
696
|
|
|
500
|
-
await this
|
|
697
|
+
await this._scheduleNextAlarm();
|
|
501
698
|
|
|
502
699
|
return {
|
|
503
700
|
id,
|
|
@@ -518,7 +715,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
518
715
|
)}, 'delayed', ${when}, ${timestamp})
|
|
519
716
|
`;
|
|
520
717
|
|
|
521
|
-
await this
|
|
718
|
+
await this._scheduleNextAlarm();
|
|
522
719
|
|
|
523
720
|
return {
|
|
524
721
|
id,
|
|
@@ -540,7 +737,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
540
737
|
)}, 'cron', ${when}, ${timestamp})
|
|
541
738
|
`;
|
|
542
739
|
|
|
543
|
-
await this
|
|
740
|
+
await this._scheduleNextAlarm();
|
|
544
741
|
|
|
545
742
|
return {
|
|
546
743
|
id,
|
|
@@ -580,7 +777,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
580
777
|
*/
|
|
581
778
|
getSchedules<T = string>(
|
|
582
779
|
criteria: {
|
|
583
|
-
description?: string;
|
|
584
780
|
id?: string;
|
|
585
781
|
type?: "scheduled" | "delayed" | "cron";
|
|
586
782
|
timeRange?: { start?: Date; end?: Date };
|
|
@@ -594,11 +790,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
594
790
|
params.push(criteria.id);
|
|
595
791
|
}
|
|
596
792
|
|
|
597
|
-
if (criteria.description) {
|
|
598
|
-
query += " AND description = ?";
|
|
599
|
-
params.push(criteria.description);
|
|
600
|
-
}
|
|
601
|
-
|
|
602
793
|
if (criteria.type) {
|
|
603
794
|
query += " AND type = ?";
|
|
604
795
|
params.push(criteria.type);
|
|
@@ -633,11 +824,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
633
824
|
async cancelSchedule(id: string): Promise<boolean> {
|
|
634
825
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
635
826
|
|
|
636
|
-
await this
|
|
827
|
+
await this._scheduleNextAlarm();
|
|
637
828
|
return true;
|
|
638
829
|
}
|
|
639
830
|
|
|
640
|
-
async
|
|
831
|
+
private async _scheduleNextAlarm() {
|
|
641
832
|
// Find the next schedule that needs to be executed
|
|
642
833
|
const result = this.sql`
|
|
643
834
|
SELECT time FROM cf_agents_schedules
|
|
@@ -654,10 +845,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
654
845
|
}
|
|
655
846
|
|
|
656
847
|
/**
|
|
657
|
-
* Method called when an alarm fires
|
|
658
|
-
* 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/}
|
|
659
854
|
*/
|
|
660
|
-
async
|
|
855
|
+
public readonly alarm = async () => {
|
|
661
856
|
const now = Math.floor(Date.now() / 1000);
|
|
662
857
|
|
|
663
858
|
// Get all schedules that should be executed now
|
|
@@ -671,16 +866,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
671
866
|
console.error(`callback ${row.callback} not found`);
|
|
672
867
|
continue;
|
|
673
868
|
}
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
869
|
+
await agentContext.run(
|
|
870
|
+
{ agent: this, connection: undefined, request: undefined },
|
|
871
|
+
async () => {
|
|
872
|
+
try {
|
|
873
|
+
await (
|
|
874
|
+
callback as (
|
|
875
|
+
payload: unknown,
|
|
876
|
+
schedule: Schedule<unknown>
|
|
877
|
+
) => Promise<void>
|
|
878
|
+
).bind(this)(JSON.parse(row.payload as string), row);
|
|
879
|
+
} catch (e) {
|
|
880
|
+
console.error(`error executing callback "${row.callback}"`, e);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
);
|
|
684
884
|
if (row.type === "cron") {
|
|
685
885
|
// Update next execution time for cron schedules
|
|
686
886
|
const nextExecutionTime = getNextCronTime(row.cron);
|
|
@@ -698,8 +898,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
698
898
|
}
|
|
699
899
|
|
|
700
900
|
// Schedule the next alarm
|
|
701
|
-
await this
|
|
702
|
-
}
|
|
901
|
+
await this._scheduleNextAlarm();
|
|
902
|
+
};
|
|
703
903
|
|
|
704
904
|
/**
|
|
705
905
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -708,6 +908,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
708
908
|
// drop all tables
|
|
709
909
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
710
910
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
911
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
711
912
|
|
|
712
913
|
// delete all alarms
|
|
713
914
|
await this.ctx.storage.deleteAlarm();
|
|
@@ -718,10 +919,171 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
718
919
|
* Get all methods marked as callable on this Agent
|
|
719
920
|
* @returns A map of method names to their metadata
|
|
720
921
|
*/
|
|
721
|
-
|
|
722
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
922
|
+
private _isCallable(method: string): boolean {
|
|
723
923
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
724
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
|
+
}
|
|
725
1087
|
}
|
|
726
1088
|
|
|
727
1089
|
/**
|
|
@@ -825,7 +1187,7 @@ export async function routeAgentEmail<Env>(
|
|
|
825
1187
|
* @param options Options for Agent creation
|
|
826
1188
|
* @returns Promise resolving to an Agent instance stub
|
|
827
1189
|
*/
|
|
828
|
-
export function getAgentByName<Env, T extends Agent<Env>>(
|
|
1190
|
+
export async function getAgentByName<Env, T extends Agent<Env>>(
|
|
829
1191
|
namespace: AgentNamespace<T>,
|
|
830
1192
|
name: string,
|
|
831
1193
|
options?: {
|
|
@@ -840,13 +1202,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
|
|
|
840
1202
|
* A wrapper for streaming responses in callable methods
|
|
841
1203
|
*/
|
|
842
1204
|
export class StreamingResponse {
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
1205
|
+
private _connection: Connection;
|
|
1206
|
+
private _id: string;
|
|
1207
|
+
private _closed = false;
|
|
846
1208
|
|
|
847
1209
|
constructor(connection: Connection, id: string) {
|
|
848
|
-
this
|
|
849
|
-
this
|
|
1210
|
+
this._connection = connection;
|
|
1211
|
+
this._id = id;
|
|
850
1212
|
}
|
|
851
1213
|
|
|
852
1214
|
/**
|
|
@@ -854,17 +1216,17 @@ export class StreamingResponse {
|
|
|
854
1216
|
* @param chunk The data to send
|
|
855
1217
|
*/
|
|
856
1218
|
send(chunk: unknown) {
|
|
857
|
-
if (this
|
|
1219
|
+
if (this._closed) {
|
|
858
1220
|
throw new Error("StreamingResponse is already closed");
|
|
859
1221
|
}
|
|
860
1222
|
const response: RPCResponse = {
|
|
861
1223
|
type: "rpc",
|
|
862
|
-
id: this
|
|
1224
|
+
id: this._id,
|
|
863
1225
|
success: true,
|
|
864
1226
|
result: chunk,
|
|
865
1227
|
done: false,
|
|
866
1228
|
};
|
|
867
|
-
this
|
|
1229
|
+
this._connection.send(JSON.stringify(response));
|
|
868
1230
|
}
|
|
869
1231
|
|
|
870
1232
|
/**
|
|
@@ -872,17 +1234,17 @@ export class StreamingResponse {
|
|
|
872
1234
|
* @param finalChunk Optional final chunk of data to send
|
|
873
1235
|
*/
|
|
874
1236
|
end(finalChunk?: unknown) {
|
|
875
|
-
if (this
|
|
1237
|
+
if (this._closed) {
|
|
876
1238
|
throw new Error("StreamingResponse is already closed");
|
|
877
1239
|
}
|
|
878
|
-
this
|
|
1240
|
+
this._closed = true;
|
|
879
1241
|
const response: RPCResponse = {
|
|
880
1242
|
type: "rpc",
|
|
881
|
-
id: this
|
|
1243
|
+
id: this._id,
|
|
882
1244
|
success: true,
|
|
883
1245
|
result: finalChunk,
|
|
884
1246
|
done: true,
|
|
885
1247
|
};
|
|
886
|
-
this
|
|
1248
|
+
this._connection.send(JSON.stringify(response));
|
|
887
1249
|
}
|
|
888
1250
|
}
|