agents 0.0.0-ee727ca → 0.0.0-eeb70e2
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 -66
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +13 -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-OYJXQRRH.js +465 -0
- package/dist/chunk-OYJXQRRH.js.map +1 -0
- package/dist/chunk-P3RZJ72N.js +783 -0
- package/dist/chunk-P3RZJ72N.js.map +1 -0
- package/dist/chunk-VCSB47AK.js +116 -0
- package/dist/chunk-VCSB47AK.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 +782 -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 +490 -126
- 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
|
@@ -1,19 +1,32 @@
|
|
|
1
1
|
import {
|
|
2
2
|
Server,
|
|
3
|
-
routePartykitRequest,
|
|
4
|
-
type PartyServerOptions,
|
|
5
3
|
getServerByName,
|
|
4
|
+
routePartykitRequest,
|
|
6
5
|
type Connection,
|
|
7
6
|
type ConnectionContext,
|
|
7
|
+
type PartyServerOptions,
|
|
8
8
|
type WSMessage,
|
|
9
9
|
} from "partyserver";
|
|
10
10
|
|
|
11
11
|
import { parseCronExpression } from "cron-schedule";
|
|
12
12
|
import { nanoid } from "nanoid";
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
import type {
|
|
15
|
+
Prompt,
|
|
16
|
+
Resource,
|
|
17
|
+
ServerCapabilities,
|
|
18
|
+
Tool,
|
|
19
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
20
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
21
|
+
import { MCPClientManager } from "./mcp/client";
|
|
22
|
+
import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
|
|
15
23
|
|
|
16
|
-
import {
|
|
24
|
+
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
25
|
+
import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
26
|
+
|
|
27
|
+
import { camelCaseToKebabCase } from "./client";
|
|
28
|
+
|
|
29
|
+
export type { Connection, ConnectionContext, WSMessage } from "partyserver";
|
|
17
30
|
|
|
18
31
|
/**
|
|
19
32
|
* RPC request message from client
|
|
@@ -97,7 +110,6 @@ export type CallableMetadata = {
|
|
|
97
110
|
streaming?: boolean;
|
|
98
111
|
};
|
|
99
112
|
|
|
100
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
101
113
|
const callableMetadata = new Map<Function, CallableMetadata>();
|
|
102
114
|
|
|
103
115
|
/**
|
|
@@ -117,11 +129,6 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
|
|
|
117
129
|
};
|
|
118
130
|
}
|
|
119
131
|
|
|
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
132
|
/**
|
|
126
133
|
* Represents a scheduled task within an Agent
|
|
127
134
|
* @template T Type of the payload data
|
|
@@ -163,18 +170,95 @@ function getNextCronTime(cron: string) {
|
|
|
163
170
|
return interval.getNextDate();
|
|
164
171
|
}
|
|
165
172
|
|
|
173
|
+
/**
|
|
174
|
+
* MCP Server state update message from server -> Client
|
|
175
|
+
*/
|
|
176
|
+
export type MCPServerMessage = {
|
|
177
|
+
type: "cf_agent_mcp_servers";
|
|
178
|
+
mcp: MCPServersState;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
export type MCPServersState = {
|
|
182
|
+
servers: {
|
|
183
|
+
[id: string]: MCPServer;
|
|
184
|
+
};
|
|
185
|
+
tools: Tool[];
|
|
186
|
+
prompts: Prompt[];
|
|
187
|
+
resources: Resource[];
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
export type MCPServer = {
|
|
191
|
+
name: string;
|
|
192
|
+
server_url: string;
|
|
193
|
+
auth_url: string | null;
|
|
194
|
+
// This state is specifically about the temporary process of getting a token (if needed).
|
|
195
|
+
// Scope outside of that can't be relied upon because when the DO sleeps, there's no way
|
|
196
|
+
// to communicate a change to a non-ready state.
|
|
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,198 @@ 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 not currently in the oauth flow using our saved auth information
|
|
532
|
+
await Promise.allSettled(
|
|
533
|
+
servers
|
|
534
|
+
.filter((server) => server.auth_url === null)
|
|
535
|
+
.map((server) => {
|
|
536
|
+
return this._connectToMcpServerInternal(
|
|
537
|
+
server.name,
|
|
538
|
+
server.server_url,
|
|
539
|
+
server.callback_url,
|
|
540
|
+
server.server_options
|
|
541
|
+
? JSON.parse(server.server_options)
|
|
542
|
+
: undefined,
|
|
543
|
+
{
|
|
544
|
+
id: server.id,
|
|
545
|
+
oauthClientId: server.client_id ?? undefined,
|
|
546
|
+
}
|
|
547
|
+
);
|
|
548
|
+
})
|
|
549
|
+
);
|
|
550
|
+
|
|
551
|
+
this.broadcast(
|
|
370
552
|
JSON.stringify({
|
|
371
|
-
type: "
|
|
372
|
-
|
|
553
|
+
type: "cf_agent_mcp_servers",
|
|
554
|
+
mcp: this.getMcpServers(),
|
|
373
555
|
})
|
|
374
556
|
);
|
|
557
|
+
|
|
558
|
+
await this._tryCatch(() => _onStart());
|
|
375
559
|
}
|
|
376
|
-
|
|
377
|
-
}, 20);
|
|
560
|
+
);
|
|
378
561
|
};
|
|
379
562
|
}
|
|
380
563
|
|
|
381
|
-
|
|
382
|
-
|
|
564
|
+
private _setStateInternal(
|
|
565
|
+
state: State,
|
|
566
|
+
source: Connection | "server" = "server"
|
|
567
|
+
) {
|
|
568
|
+
this._state = state;
|
|
383
569
|
this.sql`
|
|
384
570
|
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
385
571
|
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
@@ -395,7 +581,15 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
395
581
|
}),
|
|
396
582
|
source !== "server" ? [source.id] : []
|
|
397
583
|
);
|
|
398
|
-
return this
|
|
584
|
+
return this._tryCatch(() => {
|
|
585
|
+
const { connection, request } = agentContext.getStore() || {};
|
|
586
|
+
return agentContext.run(
|
|
587
|
+
{ agent: this, connection, request },
|
|
588
|
+
async () => {
|
|
589
|
+
return this.onStateUpdate(state, source);
|
|
590
|
+
}
|
|
591
|
+
);
|
|
592
|
+
});
|
|
399
593
|
}
|
|
400
594
|
|
|
401
595
|
/**
|
|
@@ -403,7 +597,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
403
597
|
* @param state New state to set
|
|
404
598
|
*/
|
|
405
599
|
setState(state: State) {
|
|
406
|
-
this
|
|
600
|
+
this._setStateInternal(state, "server");
|
|
407
601
|
}
|
|
408
602
|
|
|
409
603
|
/**
|
|
@@ -420,10 +614,15 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
420
614
|
* @param email Email message to process
|
|
421
615
|
*/
|
|
422
616
|
onEmail(email: ForwardableEmailMessage) {
|
|
423
|
-
|
|
617
|
+
return agentContext.run(
|
|
618
|
+
{ agent: this, connection: undefined, request: undefined },
|
|
619
|
+
async () => {
|
|
620
|
+
console.error("onEmail not implemented");
|
|
621
|
+
}
|
|
622
|
+
);
|
|
424
623
|
}
|
|
425
624
|
|
|
426
|
-
async
|
|
625
|
+
private async _tryCatch<T>(fn: () => T | Promise<T>) {
|
|
427
626
|
try {
|
|
428
627
|
return await fn();
|
|
429
628
|
} catch (e) {
|
|
@@ -497,7 +696,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
497
696
|
)}, 'scheduled', ${timestamp})
|
|
498
697
|
`;
|
|
499
698
|
|
|
500
|
-
await this
|
|
699
|
+
await this._scheduleNextAlarm();
|
|
501
700
|
|
|
502
701
|
return {
|
|
503
702
|
id,
|
|
@@ -518,7 +717,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
518
717
|
)}, 'delayed', ${when}, ${timestamp})
|
|
519
718
|
`;
|
|
520
719
|
|
|
521
|
-
await this
|
|
720
|
+
await this._scheduleNextAlarm();
|
|
522
721
|
|
|
523
722
|
return {
|
|
524
723
|
id,
|
|
@@ -540,7 +739,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
540
739
|
)}, 'cron', ${when}, ${timestamp})
|
|
541
740
|
`;
|
|
542
741
|
|
|
543
|
-
await this
|
|
742
|
+
await this._scheduleNextAlarm();
|
|
544
743
|
|
|
545
744
|
return {
|
|
546
745
|
id,
|
|
@@ -580,7 +779,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
580
779
|
*/
|
|
581
780
|
getSchedules<T = string>(
|
|
582
781
|
criteria: {
|
|
583
|
-
description?: string;
|
|
584
782
|
id?: string;
|
|
585
783
|
type?: "scheduled" | "delayed" | "cron";
|
|
586
784
|
timeRange?: { start?: Date; end?: Date };
|
|
@@ -594,11 +792,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
594
792
|
params.push(criteria.id);
|
|
595
793
|
}
|
|
596
794
|
|
|
597
|
-
if (criteria.description) {
|
|
598
|
-
query += " AND description = ?";
|
|
599
|
-
params.push(criteria.description);
|
|
600
|
-
}
|
|
601
|
-
|
|
602
795
|
if (criteria.type) {
|
|
603
796
|
query += " AND type = ?";
|
|
604
797
|
params.push(criteria.type);
|
|
@@ -633,11 +826,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
633
826
|
async cancelSchedule(id: string): Promise<boolean> {
|
|
634
827
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
635
828
|
|
|
636
|
-
await this
|
|
829
|
+
await this._scheduleNextAlarm();
|
|
637
830
|
return true;
|
|
638
831
|
}
|
|
639
832
|
|
|
640
|
-
async
|
|
833
|
+
private async _scheduleNextAlarm() {
|
|
641
834
|
// Find the next schedule that needs to be executed
|
|
642
835
|
const result = this.sql`
|
|
643
836
|
SELECT time FROM cf_agents_schedules
|
|
@@ -654,10 +847,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
654
847
|
}
|
|
655
848
|
|
|
656
849
|
/**
|
|
657
|
-
* Method called when an alarm fires
|
|
658
|
-
* Executes any scheduled tasks that are due
|
|
850
|
+
* Method called when an alarm fires.
|
|
851
|
+
* Executes any scheduled tasks that are due.
|
|
852
|
+
*
|
|
853
|
+
* @remarks
|
|
854
|
+
* To schedule a task, please use the `this.schedule` method instead.
|
|
855
|
+
* See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
|
|
659
856
|
*/
|
|
660
|
-
async
|
|
857
|
+
public readonly alarm = async () => {
|
|
661
858
|
const now = Math.floor(Date.now() / 1000);
|
|
662
859
|
|
|
663
860
|
// Get all schedules that should be executed now
|
|
@@ -671,16 +868,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
671
868
|
console.error(`callback ${row.callback} not found`);
|
|
672
869
|
continue;
|
|
673
870
|
}
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
871
|
+
await agentContext.run(
|
|
872
|
+
{ agent: this, connection: undefined, request: undefined },
|
|
873
|
+
async () => {
|
|
874
|
+
try {
|
|
875
|
+
await (
|
|
876
|
+
callback as (
|
|
877
|
+
payload: unknown,
|
|
878
|
+
schedule: Schedule<unknown>
|
|
879
|
+
) => Promise<void>
|
|
880
|
+
).bind(this)(JSON.parse(row.payload as string), row);
|
|
881
|
+
} catch (e) {
|
|
882
|
+
console.error(`error executing callback "${row.callback}"`, e);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
);
|
|
684
886
|
if (row.type === "cron") {
|
|
685
887
|
// Update next execution time for cron schedules
|
|
686
888
|
const nextExecutionTime = getNextCronTime(row.cron);
|
|
@@ -698,8 +900,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
698
900
|
}
|
|
699
901
|
|
|
700
902
|
// Schedule the next alarm
|
|
701
|
-
await this
|
|
702
|
-
}
|
|
903
|
+
await this._scheduleNextAlarm();
|
|
904
|
+
};
|
|
703
905
|
|
|
704
906
|
/**
|
|
705
907
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -708,6 +910,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
708
910
|
// drop all tables
|
|
709
911
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
710
912
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
913
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
711
914
|
|
|
712
915
|
// delete all alarms
|
|
713
916
|
await this.ctx.storage.deleteAlarm();
|
|
@@ -718,10 +921,171 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
718
921
|
* Get all methods marked as callable on this Agent
|
|
719
922
|
* @returns A map of method names to their metadata
|
|
720
923
|
*/
|
|
721
|
-
|
|
722
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
924
|
+
private _isCallable(method: string): boolean {
|
|
723
925
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
724
926
|
}
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* Connect to a new MCP Server
|
|
930
|
+
*
|
|
931
|
+
* @param url MCP Server SSE URL
|
|
932
|
+
* @param callbackHost Base host for the agent, used for the redirect URI.
|
|
933
|
+
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
934
|
+
* @param options MCP client and transport (header) options
|
|
935
|
+
* @returns authUrl
|
|
936
|
+
*/
|
|
937
|
+
async addMcpServer(
|
|
938
|
+
serverName: string,
|
|
939
|
+
url: string,
|
|
940
|
+
callbackHost: string,
|
|
941
|
+
agentsPrefix = "agents",
|
|
942
|
+
options?: {
|
|
943
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
944
|
+
transport?: {
|
|
945
|
+
headers: HeadersInit;
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
949
|
+
const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
950
|
+
|
|
951
|
+
const result = await this._connectToMcpServerInternal(
|
|
952
|
+
serverName,
|
|
953
|
+
url,
|
|
954
|
+
callbackUrl,
|
|
955
|
+
options
|
|
956
|
+
);
|
|
957
|
+
|
|
958
|
+
this.broadcast(
|
|
959
|
+
JSON.stringify({
|
|
960
|
+
type: "cf_agent_mcp_servers",
|
|
961
|
+
mcp: this.getMcpServers(),
|
|
962
|
+
})
|
|
963
|
+
);
|
|
964
|
+
|
|
965
|
+
return result;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
async _connectToMcpServerInternal(
|
|
969
|
+
serverName: string,
|
|
970
|
+
url: string,
|
|
971
|
+
callbackUrl: string,
|
|
972
|
+
// it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
|
|
973
|
+
options?: {
|
|
974
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
975
|
+
/**
|
|
976
|
+
* We don't expose the normal set of transport options because:
|
|
977
|
+
* 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
|
|
978
|
+
* 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
|
|
979
|
+
*
|
|
980
|
+
* 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).
|
|
981
|
+
*/
|
|
982
|
+
transport?: {
|
|
983
|
+
headers?: HeadersInit;
|
|
984
|
+
};
|
|
985
|
+
},
|
|
986
|
+
reconnect?: {
|
|
987
|
+
id: string;
|
|
988
|
+
oauthClientId?: string;
|
|
989
|
+
}
|
|
990
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
991
|
+
const authProvider = new DurableObjectOAuthClientProvider(
|
|
992
|
+
this.ctx.storage,
|
|
993
|
+
this.name,
|
|
994
|
+
callbackUrl
|
|
995
|
+
);
|
|
996
|
+
|
|
997
|
+
if (reconnect) {
|
|
998
|
+
authProvider.serverId = reconnect.id;
|
|
999
|
+
if (reconnect.oauthClientId) {
|
|
1000
|
+
authProvider.clientId = reconnect.oauthClientId;
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
// allows passing through transport headers if necessary
|
|
1005
|
+
// this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
|
|
1006
|
+
let headerTransportOpts: SSEClientTransportOptions = {};
|
|
1007
|
+
if (options?.transport?.headers) {
|
|
1008
|
+
headerTransportOpts = {
|
|
1009
|
+
eventSourceInit: {
|
|
1010
|
+
fetch: (url, init) =>
|
|
1011
|
+
fetch(url, {
|
|
1012
|
+
...init,
|
|
1013
|
+
headers: options?.transport?.headers,
|
|
1014
|
+
}),
|
|
1015
|
+
},
|
|
1016
|
+
requestInit: {
|
|
1017
|
+
headers: options?.transport?.headers,
|
|
1018
|
+
},
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
const { id, authUrl, clientId } = await this.mcp.connect(url, {
|
|
1023
|
+
reconnect,
|
|
1024
|
+
transport: {
|
|
1025
|
+
...headerTransportOpts,
|
|
1026
|
+
authProvider,
|
|
1027
|
+
},
|
|
1028
|
+
client: options?.client,
|
|
1029
|
+
});
|
|
1030
|
+
|
|
1031
|
+
this.sql`
|
|
1032
|
+
INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
1033
|
+
VALUES (
|
|
1034
|
+
${id},
|
|
1035
|
+
${serverName},
|
|
1036
|
+
${url},
|
|
1037
|
+
${clientId ?? null},
|
|
1038
|
+
${authUrl ?? null},
|
|
1039
|
+
${callbackUrl},
|
|
1040
|
+
${options ? JSON.stringify(options) : null}
|
|
1041
|
+
);
|
|
1042
|
+
`;
|
|
1043
|
+
|
|
1044
|
+
return {
|
|
1045
|
+
id,
|
|
1046
|
+
authUrl,
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
async removeMcpServer(id: string) {
|
|
1051
|
+
this.mcp.closeConnection(id);
|
|
1052
|
+
this.sql`
|
|
1053
|
+
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
1054
|
+
`;
|
|
1055
|
+
this.broadcast(
|
|
1056
|
+
JSON.stringify({
|
|
1057
|
+
type: "cf_agent_mcp_servers",
|
|
1058
|
+
mcp: this.getMcpServers(),
|
|
1059
|
+
})
|
|
1060
|
+
);
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
getMcpServers(): MCPServersState {
|
|
1064
|
+
const mcpState: MCPServersState = {
|
|
1065
|
+
servers: {},
|
|
1066
|
+
tools: this.mcp.listTools(),
|
|
1067
|
+
prompts: this.mcp.listPrompts(),
|
|
1068
|
+
resources: this.mcp.listResources(),
|
|
1069
|
+
};
|
|
1070
|
+
|
|
1071
|
+
const servers = this.sql<MCPServerRow>`
|
|
1072
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
1073
|
+
`;
|
|
1074
|
+
|
|
1075
|
+
for (const server of servers) {
|
|
1076
|
+
mcpState.servers[server.id] = {
|
|
1077
|
+
name: server.name,
|
|
1078
|
+
server_url: server.server_url,
|
|
1079
|
+
auth_url: server.auth_url,
|
|
1080
|
+
state: this.mcp.mcpConnections[server.id].connectionState,
|
|
1081
|
+
instructions: this.mcp.mcpConnections[server.id].instructions ?? null,
|
|
1082
|
+
capabilities:
|
|
1083
|
+
this.mcp.mcpConnections[server.id].serverCapabilities ?? null,
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
return mcpState;
|
|
1088
|
+
}
|
|
725
1089
|
}
|
|
726
1090
|
|
|
727
1091
|
/**
|
|
@@ -825,7 +1189,7 @@ export async function routeAgentEmail<Env>(
|
|
|
825
1189
|
* @param options Options for Agent creation
|
|
826
1190
|
* @returns Promise resolving to an Agent instance stub
|
|
827
1191
|
*/
|
|
828
|
-
export function getAgentByName<Env, T extends Agent<Env>>(
|
|
1192
|
+
export async function getAgentByName<Env, T extends Agent<Env>>(
|
|
829
1193
|
namespace: AgentNamespace<T>,
|
|
830
1194
|
name: string,
|
|
831
1195
|
options?: {
|
|
@@ -840,13 +1204,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
|
|
|
840
1204
|
* A wrapper for streaming responses in callable methods
|
|
841
1205
|
*/
|
|
842
1206
|
export class StreamingResponse {
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
1207
|
+
private _connection: Connection;
|
|
1208
|
+
private _id: string;
|
|
1209
|
+
private _closed = false;
|
|
846
1210
|
|
|
847
1211
|
constructor(connection: Connection, id: string) {
|
|
848
|
-
this
|
|
849
|
-
this
|
|
1212
|
+
this._connection = connection;
|
|
1213
|
+
this._id = id;
|
|
850
1214
|
}
|
|
851
1215
|
|
|
852
1216
|
/**
|
|
@@ -854,17 +1218,17 @@ export class StreamingResponse {
|
|
|
854
1218
|
* @param chunk The data to send
|
|
855
1219
|
*/
|
|
856
1220
|
send(chunk: unknown) {
|
|
857
|
-
if (this
|
|
1221
|
+
if (this._closed) {
|
|
858
1222
|
throw new Error("StreamingResponse is already closed");
|
|
859
1223
|
}
|
|
860
1224
|
const response: RPCResponse = {
|
|
861
1225
|
type: "rpc",
|
|
862
|
-
id: this
|
|
1226
|
+
id: this._id,
|
|
863
1227
|
success: true,
|
|
864
1228
|
result: chunk,
|
|
865
1229
|
done: false,
|
|
866
1230
|
};
|
|
867
|
-
this
|
|
1231
|
+
this._connection.send(JSON.stringify(response));
|
|
868
1232
|
}
|
|
869
1233
|
|
|
870
1234
|
/**
|
|
@@ -872,17 +1236,17 @@ export class StreamingResponse {
|
|
|
872
1236
|
* @param finalChunk Optional final chunk of data to send
|
|
873
1237
|
*/
|
|
874
1238
|
end(finalChunk?: unknown) {
|
|
875
|
-
if (this
|
|
1239
|
+
if (this._closed) {
|
|
876
1240
|
throw new Error("StreamingResponse is already closed");
|
|
877
1241
|
}
|
|
878
|
-
this
|
|
1242
|
+
this._closed = true;
|
|
879
1243
|
const response: RPCResponse = {
|
|
880
1244
|
type: "rpc",
|
|
881
|
-
id: this
|
|
1245
|
+
id: this._id,
|
|
882
1246
|
success: true,
|
|
883
1247
|
result: finalChunk,
|
|
884
1248
|
done: true,
|
|
885
1249
|
};
|
|
886
|
-
this
|
|
1250
|
+
this._connection.send(JSON.stringify(response));
|
|
887
1251
|
}
|
|
888
1252
|
}
|