agents 0.0.0-843745d → 0.0.0-85b0bb0
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 -6
- 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 +29 -29
- package/dist/ai-react.js.map +1 -1
- package/dist/{chunk-AV3OMRR4.js → chunk-4CIGD73X.js} +358 -164
- package/dist/chunk-4CIGD73X.js.map +1 -0
- package/dist/chunk-767EASBA.js +106 -0
- package/dist/chunk-767EASBA.js.map +1 -0
- package/dist/{chunk-YZNSS675.js → chunk-E3LCYPCB.js} +71 -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/client.d.ts +15 -1
- package/dist/client.js +6 -126
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +117 -18
- package/dist/index.js +8 -7
- package/dist/mcp/client.d.ts +310 -23
- 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 +22 -11
- package/dist/mcp/index.js +172 -175
- 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 +70 -68
- package/src/index.ts +427 -88
- package/dist/chunk-AV3OMRR4.js.map +0 -1
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-YZNSS675.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,29 +169,95 @@ 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
|
|
|
165
217
|
const DEFAULT_STATE = {} as unknown;
|
|
166
218
|
|
|
167
|
-
|
|
219
|
+
const agentContext = new AsyncLocalStorage<{
|
|
168
220
|
agent: Agent<unknown>;
|
|
169
221
|
connection: Connection | undefined;
|
|
170
222
|
request: Request | undefined;
|
|
171
223
|
}>();
|
|
172
224
|
|
|
225
|
+
export function getCurrentAgent<
|
|
226
|
+
T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
|
|
227
|
+
>(): {
|
|
228
|
+
agent: T | undefined;
|
|
229
|
+
connection: Connection | undefined;
|
|
230
|
+
request: Request<unknown, CfProperties<unknown>> | undefined;
|
|
231
|
+
} {
|
|
232
|
+
const store = agentContext.getStore() as
|
|
233
|
+
| {
|
|
234
|
+
agent: T;
|
|
235
|
+
connection: Connection | undefined;
|
|
236
|
+
request: Request<unknown, CfProperties<unknown>> | undefined;
|
|
237
|
+
}
|
|
238
|
+
| undefined;
|
|
239
|
+
if (!store) {
|
|
240
|
+
return {
|
|
241
|
+
agent: undefined,
|
|
242
|
+
connection: undefined,
|
|
243
|
+
request: undefined,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
return store;
|
|
247
|
+
}
|
|
248
|
+
|
|
173
249
|
/**
|
|
174
250
|
* Base class for creating Agent implementations
|
|
175
251
|
* @template Env Environment type containing bindings
|
|
176
252
|
* @template State State type to store within the Agent
|
|
177
253
|
*/
|
|
178
254
|
export class Agent<Env, State = unknown> extends Server<Env> {
|
|
179
|
-
|
|
255
|
+
private _state = DEFAULT_STATE as State;
|
|
180
256
|
|
|
181
|
-
|
|
257
|
+
private _ParentClass: typeof Agent<Env, State> =
|
|
182
258
|
Object.getPrototypeOf(this).constructor;
|
|
183
259
|
|
|
184
|
-
mcp: MCPClientManager = new MCPClientManager(this
|
|
260
|
+
mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
185
261
|
|
|
186
262
|
/**
|
|
187
263
|
* Initial state for the Agent
|
|
@@ -193,9 +269,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
193
269
|
* Current state of the Agent
|
|
194
270
|
*/
|
|
195
271
|
get state(): State {
|
|
196
|
-
if (this
|
|
272
|
+
if (this._state !== DEFAULT_STATE) {
|
|
197
273
|
// state was previously set, and populated internal state
|
|
198
|
-
return this
|
|
274
|
+
return this._state;
|
|
199
275
|
}
|
|
200
276
|
// looks like this is the first time the state is being accessed
|
|
201
277
|
// check if the state was set in a previous life
|
|
@@ -215,8 +291,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
215
291
|
) {
|
|
216
292
|
const state = result[0]?.state as string; // could be null?
|
|
217
293
|
|
|
218
|
-
this
|
|
219
|
-
return this
|
|
294
|
+
this._state = JSON.parse(state);
|
|
295
|
+
return this._state;
|
|
220
296
|
}
|
|
221
297
|
|
|
222
298
|
// ok, this is the first time the state is being accessed
|
|
@@ -277,7 +353,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
277
353
|
`;
|
|
278
354
|
|
|
279
355
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
280
|
-
return this
|
|
356
|
+
return this._tryCatch(async () => {
|
|
281
357
|
// Create alarms table if it doesn't exist
|
|
282
358
|
this.sql`
|
|
283
359
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
@@ -297,25 +373,65 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
297
373
|
});
|
|
298
374
|
});
|
|
299
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
|
+
|
|
300
416
|
const _onMessage = this.onMessage.bind(this);
|
|
301
417
|
this.onMessage = async (connection: Connection, message: WSMessage) => {
|
|
302
|
-
return
|
|
418
|
+
return agentContext.run(
|
|
303
419
|
{ agent: this, connection, request: undefined },
|
|
304
420
|
async () => {
|
|
305
421
|
if (typeof message !== "string") {
|
|
306
|
-
return this
|
|
422
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
307
423
|
}
|
|
308
424
|
|
|
309
425
|
let parsed: unknown;
|
|
310
426
|
try {
|
|
311
427
|
parsed = JSON.parse(message);
|
|
312
|
-
} catch (
|
|
428
|
+
} catch (_e) {
|
|
313
429
|
// silently fail and let the onMessage handler handle it
|
|
314
|
-
return this
|
|
430
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
315
431
|
}
|
|
316
432
|
|
|
317
433
|
if (isStateUpdateMessage(parsed)) {
|
|
318
|
-
this
|
|
434
|
+
this._setStateInternal(parsed.state as State, connection);
|
|
319
435
|
return;
|
|
320
436
|
}
|
|
321
437
|
|
|
@@ -329,11 +445,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
329
445
|
throw new Error(`Method ${method} does not exist`);
|
|
330
446
|
}
|
|
331
447
|
|
|
332
|
-
if (!this
|
|
448
|
+
if (!this._isCallable(method)) {
|
|
333
449
|
throw new Error(`Method ${method} is not callable`);
|
|
334
450
|
}
|
|
335
451
|
|
|
336
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
337
452
|
const metadata = callableMetadata.get(methodFn as Function);
|
|
338
453
|
|
|
339
454
|
// For streaming methods, pass a StreamingResponse object
|
|
@@ -346,21 +461,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
346
461
|
// For regular methods, execute and send response
|
|
347
462
|
const result = await methodFn.apply(this, args);
|
|
348
463
|
const response: RPCResponse = {
|
|
349
|
-
|
|
464
|
+
done: true,
|
|
350
465
|
id,
|
|
351
|
-
success: true,
|
|
352
466
|
result,
|
|
353
|
-
|
|
467
|
+
success: true,
|
|
468
|
+
type: "rpc",
|
|
354
469
|
};
|
|
355
470
|
connection.send(JSON.stringify(response));
|
|
356
471
|
} catch (e) {
|
|
357
472
|
// Send error response
|
|
358
473
|
const response: RPCResponse = {
|
|
359
|
-
type: "rpc",
|
|
360
|
-
id: parsed.id,
|
|
361
|
-
success: false,
|
|
362
474
|
error:
|
|
363
475
|
e instanceof Error ? e.message : "Unknown error occurred",
|
|
476
|
+
id: parsed.id,
|
|
477
|
+
success: false,
|
|
478
|
+
type: "rpc",
|
|
364
479
|
};
|
|
365
480
|
connection.send(JSON.stringify(response));
|
|
366
481
|
console.error("RPC error:", e);
|
|
@@ -368,7 +483,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
368
483
|
return;
|
|
369
484
|
}
|
|
370
485
|
|
|
371
|
-
return this
|
|
486
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
372
487
|
}
|
|
373
488
|
);
|
|
374
489
|
};
|
|
@@ -377,27 +492,76 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
377
492
|
this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
|
|
378
493
|
// TODO: This is a hack to ensure the state is sent after the connection is established
|
|
379
494
|
// must fix this
|
|
380
|
-
return
|
|
495
|
+
return agentContext.run(
|
|
381
496
|
{ agent: this, connection, request: ctx.request },
|
|
382
497
|
async () => {
|
|
383
498
|
setTimeout(() => {
|
|
384
499
|
if (this.state) {
|
|
385
500
|
connection.send(
|
|
386
501
|
JSON.stringify({
|
|
387
|
-
type: "cf_agent_state",
|
|
388
502
|
state: this.state,
|
|
503
|
+
type: "cf_agent_state",
|
|
389
504
|
})
|
|
390
505
|
);
|
|
391
506
|
}
|
|
392
|
-
|
|
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));
|
|
393
516
|
}, 20);
|
|
394
517
|
}
|
|
395
518
|
);
|
|
396
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
|
+
Promise.allSettled(
|
|
532
|
+
servers.map((server) => {
|
|
533
|
+
return this._connectToMcpServerInternal(
|
|
534
|
+
server.name,
|
|
535
|
+
server.server_url,
|
|
536
|
+
server.callback_url,
|
|
537
|
+
server.server_options
|
|
538
|
+
? JSON.parse(server.server_options)
|
|
539
|
+
: undefined,
|
|
540
|
+
{
|
|
541
|
+
id: server.id,
|
|
542
|
+
oauthClientId: server.client_id ?? undefined,
|
|
543
|
+
}
|
|
544
|
+
);
|
|
545
|
+
})
|
|
546
|
+
).then((_results) => {
|
|
547
|
+
this.broadcast(
|
|
548
|
+
JSON.stringify({
|
|
549
|
+
mcp: this.getMcpServers(),
|
|
550
|
+
type: "cf_agent_mcp_servers",
|
|
551
|
+
})
|
|
552
|
+
);
|
|
553
|
+
});
|
|
554
|
+
await this._tryCatch(() => _onStart());
|
|
555
|
+
}
|
|
556
|
+
);
|
|
557
|
+
};
|
|
397
558
|
}
|
|
398
559
|
|
|
399
|
-
|
|
400
|
-
|
|
560
|
+
private _setStateInternal(
|
|
561
|
+
state: State,
|
|
562
|
+
source: Connection | "server" = "server"
|
|
563
|
+
) {
|
|
564
|
+
this._state = state;
|
|
401
565
|
this.sql`
|
|
402
566
|
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
403
567
|
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
@@ -408,14 +572,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
408
572
|
`;
|
|
409
573
|
this.broadcast(
|
|
410
574
|
JSON.stringify({
|
|
411
|
-
type: "cf_agent_state",
|
|
412
575
|
state: state,
|
|
576
|
+
type: "cf_agent_state",
|
|
413
577
|
}),
|
|
414
578
|
source !== "server" ? [source.id] : []
|
|
415
579
|
);
|
|
416
|
-
return this
|
|
417
|
-
const { connection, request } =
|
|
418
|
-
return
|
|
580
|
+
return this._tryCatch(() => {
|
|
581
|
+
const { connection, request } = agentContext.getStore() || {};
|
|
582
|
+
return agentContext.run(
|
|
419
583
|
{ agent: this, connection, request },
|
|
420
584
|
async () => {
|
|
421
585
|
return this.onStateUpdate(state, source);
|
|
@@ -429,7 +593,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
429
593
|
* @param state New state to set
|
|
430
594
|
*/
|
|
431
595
|
setState(state: State) {
|
|
432
|
-
this
|
|
596
|
+
this._setStateInternal(state, "server");
|
|
433
597
|
}
|
|
434
598
|
|
|
435
599
|
/**
|
|
@@ -437,6 +601,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
437
601
|
* @param state Updated state
|
|
438
602
|
* @param source Source of the state update ("server" or a client connection)
|
|
439
603
|
*/
|
|
604
|
+
// biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
|
|
440
605
|
onStateUpdate(state: State | undefined, source: Connection | "server") {
|
|
441
606
|
// override this to handle state updates
|
|
442
607
|
}
|
|
@@ -445,8 +610,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
445
610
|
* Called when the Agent receives an email
|
|
446
611
|
* @param email Email message to process
|
|
447
612
|
*/
|
|
613
|
+
// biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
|
|
448
614
|
onEmail(email: ForwardableEmailMessage) {
|
|
449
|
-
return
|
|
615
|
+
return agentContext.run(
|
|
450
616
|
{ agent: this, connection: undefined, request: undefined },
|
|
451
617
|
async () => {
|
|
452
618
|
console.error("onEmail not implemented");
|
|
@@ -454,7 +620,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
454
620
|
);
|
|
455
621
|
}
|
|
456
622
|
|
|
457
|
-
async
|
|
623
|
+
private async _tryCatch<T>(fn: () => T | Promise<T>) {
|
|
458
624
|
try {
|
|
459
625
|
return await fn();
|
|
460
626
|
} catch (e) {
|
|
@@ -528,11 +694,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
528
694
|
)}, 'scheduled', ${timestamp})
|
|
529
695
|
`;
|
|
530
696
|
|
|
531
|
-
await this
|
|
697
|
+
await this._scheduleNextAlarm();
|
|
532
698
|
|
|
533
699
|
return {
|
|
534
|
-
id,
|
|
535
700
|
callback: callback,
|
|
701
|
+
id,
|
|
536
702
|
payload: payload as T,
|
|
537
703
|
time: timestamp,
|
|
538
704
|
type: "scheduled",
|
|
@@ -549,13 +715,13 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
549
715
|
)}, 'delayed', ${when}, ${timestamp})
|
|
550
716
|
`;
|
|
551
717
|
|
|
552
|
-
await this
|
|
718
|
+
await this._scheduleNextAlarm();
|
|
553
719
|
|
|
554
720
|
return {
|
|
555
|
-
id,
|
|
556
721
|
callback: callback,
|
|
557
|
-
payload: payload as T,
|
|
558
722
|
delayInSeconds: when,
|
|
723
|
+
id,
|
|
724
|
+
payload: payload as T,
|
|
559
725
|
time: timestamp,
|
|
560
726
|
type: "delayed",
|
|
561
727
|
};
|
|
@@ -571,13 +737,13 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
571
737
|
)}, 'cron', ${when}, ${timestamp})
|
|
572
738
|
`;
|
|
573
739
|
|
|
574
|
-
await this
|
|
740
|
+
await this._scheduleNextAlarm();
|
|
575
741
|
|
|
576
742
|
return {
|
|
577
|
-
id,
|
|
578
743
|
callback: callback,
|
|
579
|
-
payload: payload as T,
|
|
580
744
|
cron: when,
|
|
745
|
+
id,
|
|
746
|
+
payload: payload as T,
|
|
581
747
|
time: timestamp,
|
|
582
748
|
type: "cron",
|
|
583
749
|
};
|
|
@@ -658,11 +824,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
658
824
|
async cancelSchedule(id: string): Promise<boolean> {
|
|
659
825
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
660
826
|
|
|
661
|
-
await this
|
|
827
|
+
await this._scheduleNextAlarm();
|
|
662
828
|
return true;
|
|
663
829
|
}
|
|
664
830
|
|
|
665
|
-
async
|
|
831
|
+
private async _scheduleNextAlarm() {
|
|
666
832
|
// Find the next schedule that needs to be executed
|
|
667
833
|
const result = this.sql`
|
|
668
834
|
SELECT time FROM cf_agents_schedules
|
|
@@ -679,10 +845,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
679
845
|
}
|
|
680
846
|
|
|
681
847
|
/**
|
|
682
|
-
* Method called when an alarm fires
|
|
683
|
-
* 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/}
|
|
684
854
|
*/
|
|
685
|
-
async
|
|
855
|
+
public readonly alarm = async () => {
|
|
686
856
|
const now = Math.floor(Date.now() / 1000);
|
|
687
857
|
|
|
688
858
|
// Get all schedules that should be executed now
|
|
@@ -696,7 +866,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
696
866
|
console.error(`callback ${row.callback} not found`);
|
|
697
867
|
continue;
|
|
698
868
|
}
|
|
699
|
-
await
|
|
869
|
+
await agentContext.run(
|
|
700
870
|
{ agent: this, connection: undefined, request: undefined },
|
|
701
871
|
async () => {
|
|
702
872
|
try {
|
|
@@ -728,8 +898,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
728
898
|
}
|
|
729
899
|
|
|
730
900
|
// Schedule the next alarm
|
|
731
|
-
await this
|
|
732
|
-
}
|
|
901
|
+
await this._scheduleNextAlarm();
|
|
902
|
+
};
|
|
733
903
|
|
|
734
904
|
/**
|
|
735
905
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -738,20 +908,189 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
738
908
|
// drop all tables
|
|
739
909
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
740
910
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
911
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
741
912
|
|
|
742
913
|
// delete all alarms
|
|
743
914
|
await this.ctx.storage.deleteAlarm();
|
|
744
915
|
await this.ctx.storage.deleteAll();
|
|
916
|
+
this.ctx.abort("destroyed"); // enforce that the agent is evicted
|
|
745
917
|
}
|
|
746
918
|
|
|
747
919
|
/**
|
|
748
920
|
* Get all methods marked as callable on this Agent
|
|
749
921
|
* @returns A map of method names to their metadata
|
|
750
922
|
*/
|
|
751
|
-
|
|
752
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
923
|
+
private _isCallable(method: string): boolean {
|
|
753
924
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
754
925
|
}
|
|
926
|
+
|
|
927
|
+
/**
|
|
928
|
+
* Connect to a new MCP Server
|
|
929
|
+
*
|
|
930
|
+
* @param url MCP Server SSE URL
|
|
931
|
+
* @param callbackHost Base host for the agent, used for the redirect URI.
|
|
932
|
+
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
933
|
+
* @param options MCP client and transport (header) options
|
|
934
|
+
* @returns authUrl
|
|
935
|
+
*/
|
|
936
|
+
async addMcpServer(
|
|
937
|
+
serverName: string,
|
|
938
|
+
url: string,
|
|
939
|
+
callbackHost: string,
|
|
940
|
+
agentsPrefix = "agents",
|
|
941
|
+
options?: {
|
|
942
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
943
|
+
transport?: {
|
|
944
|
+
headers: HeadersInit;
|
|
945
|
+
};
|
|
946
|
+
}
|
|
947
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
948
|
+
const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
949
|
+
|
|
950
|
+
const result = await this._connectToMcpServerInternal(
|
|
951
|
+
serverName,
|
|
952
|
+
url,
|
|
953
|
+
callbackUrl,
|
|
954
|
+
options
|
|
955
|
+
);
|
|
956
|
+
this.sql`
|
|
957
|
+
INSERT
|
|
958
|
+
OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
959
|
+
VALUES (
|
|
960
|
+
${result.id},
|
|
961
|
+
${serverName},
|
|
962
|
+
${url},
|
|
963
|
+
${result.clientId ?? null},
|
|
964
|
+
${result.authUrl ?? null},
|
|
965
|
+
${callbackUrl},
|
|
966
|
+
${options ? JSON.stringify(options) : null}
|
|
967
|
+
);
|
|
968
|
+
`;
|
|
969
|
+
|
|
970
|
+
this.broadcast(
|
|
971
|
+
JSON.stringify({
|
|
972
|
+
mcp: this.getMcpServers(),
|
|
973
|
+
type: "cf_agent_mcp_servers",
|
|
974
|
+
})
|
|
975
|
+
);
|
|
976
|
+
|
|
977
|
+
return result;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
async _connectToMcpServerInternal(
|
|
981
|
+
_serverName: string,
|
|
982
|
+
url: string,
|
|
983
|
+
callbackUrl: string,
|
|
984
|
+
// it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
|
|
985
|
+
options?: {
|
|
986
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
987
|
+
/**
|
|
988
|
+
* We don't expose the normal set of transport options because:
|
|
989
|
+
* 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
|
|
990
|
+
* 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
|
|
991
|
+
*
|
|
992
|
+
* 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).
|
|
993
|
+
*/
|
|
994
|
+
transport?: {
|
|
995
|
+
headers?: HeadersInit;
|
|
996
|
+
};
|
|
997
|
+
},
|
|
998
|
+
reconnect?: {
|
|
999
|
+
id: string;
|
|
1000
|
+
oauthClientId?: string;
|
|
1001
|
+
}
|
|
1002
|
+
): Promise<{
|
|
1003
|
+
id: string;
|
|
1004
|
+
authUrl: string | undefined;
|
|
1005
|
+
clientId: string | undefined;
|
|
1006
|
+
}> {
|
|
1007
|
+
const authProvider = new DurableObjectOAuthClientProvider(
|
|
1008
|
+
this.ctx.storage,
|
|
1009
|
+
this.name,
|
|
1010
|
+
callbackUrl
|
|
1011
|
+
);
|
|
1012
|
+
|
|
1013
|
+
if (reconnect) {
|
|
1014
|
+
authProvider.serverId = reconnect.id;
|
|
1015
|
+
if (reconnect.oauthClientId) {
|
|
1016
|
+
authProvider.clientId = reconnect.oauthClientId;
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
// allows passing through transport headers if necessary
|
|
1021
|
+
// this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
|
|
1022
|
+
let headerTransportOpts: SSEClientTransportOptions = {};
|
|
1023
|
+
if (options?.transport?.headers) {
|
|
1024
|
+
headerTransportOpts = {
|
|
1025
|
+
eventSourceInit: {
|
|
1026
|
+
fetch: (url, init) =>
|
|
1027
|
+
fetch(url, {
|
|
1028
|
+
...init,
|
|
1029
|
+
headers: options?.transport?.headers,
|
|
1030
|
+
}),
|
|
1031
|
+
},
|
|
1032
|
+
requestInit: {
|
|
1033
|
+
headers: options?.transport?.headers,
|
|
1034
|
+
},
|
|
1035
|
+
};
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
const { id, authUrl, clientId } = await this.mcp.connect(url, {
|
|
1039
|
+
client: options?.client,
|
|
1040
|
+
reconnect,
|
|
1041
|
+
transport: {
|
|
1042
|
+
...headerTransportOpts,
|
|
1043
|
+
authProvider,
|
|
1044
|
+
},
|
|
1045
|
+
});
|
|
1046
|
+
|
|
1047
|
+
return {
|
|
1048
|
+
authUrl,
|
|
1049
|
+
clientId,
|
|
1050
|
+
id,
|
|
1051
|
+
};
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
async removeMcpServer(id: string) {
|
|
1055
|
+
this.mcp.closeConnection(id);
|
|
1056
|
+
this.sql`
|
|
1057
|
+
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
1058
|
+
`;
|
|
1059
|
+
this.broadcast(
|
|
1060
|
+
JSON.stringify({
|
|
1061
|
+
mcp: this.getMcpServers(),
|
|
1062
|
+
type: "cf_agent_mcp_servers",
|
|
1063
|
+
})
|
|
1064
|
+
);
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
getMcpServers(): MCPServersState {
|
|
1068
|
+
const mcpState: MCPServersState = {
|
|
1069
|
+
prompts: this.mcp.listPrompts(),
|
|
1070
|
+
resources: this.mcp.listResources(),
|
|
1071
|
+
servers: {},
|
|
1072
|
+
tools: this.mcp.listTools(),
|
|
1073
|
+
};
|
|
1074
|
+
|
|
1075
|
+
const servers = this.sql<MCPServerRow>`
|
|
1076
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
1077
|
+
`;
|
|
1078
|
+
|
|
1079
|
+
for (const server of servers) {
|
|
1080
|
+
const serverConn = this.mcp.mcpConnections[server.id];
|
|
1081
|
+
mcpState.servers[server.id] = {
|
|
1082
|
+
auth_url: server.auth_url,
|
|
1083
|
+
capabilities: serverConn?.serverCapabilities ?? null,
|
|
1084
|
+
instructions: serverConn?.instructions ?? null,
|
|
1085
|
+
name: server.name,
|
|
1086
|
+
server_url: server.server_url,
|
|
1087
|
+
// mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
|
|
1088
|
+
state: serverConn?.connectionState ?? "authenticating",
|
|
1089
|
+
};
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
return mcpState;
|
|
1093
|
+
}
|
|
755
1094
|
}
|
|
756
1095
|
|
|
757
1096
|
/**
|
|
@@ -791,9 +1130,9 @@ export async function routeAgentRequest<Env>(
|
|
|
791
1130
|
const corsHeaders =
|
|
792
1131
|
options?.cors === true
|
|
793
1132
|
? {
|
|
794
|
-
"Access-Control-Allow-Origin": "*",
|
|
795
|
-
"Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
|
|
796
1133
|
"Access-Control-Allow-Credentials": "true",
|
|
1134
|
+
"Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
|
|
1135
|
+
"Access-Control-Allow-Origin": "*",
|
|
797
1136
|
"Access-Control-Max-Age": "86400",
|
|
798
1137
|
}
|
|
799
1138
|
: options?.cors;
|
|
@@ -841,9 +1180,9 @@ export async function routeAgentRequest<Env>(
|
|
|
841
1180
|
* @param options Routing options
|
|
842
1181
|
*/
|
|
843
1182
|
export async function routeAgentEmail<Env>(
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
1183
|
+
_email: ForwardableEmailMessage,
|
|
1184
|
+
_env: Env,
|
|
1185
|
+
_options?: AgentOptions<Env>
|
|
847
1186
|
): Promise<void> {}
|
|
848
1187
|
|
|
849
1188
|
/**
|
|
@@ -855,7 +1194,7 @@ export async function routeAgentEmail<Env>(
|
|
|
855
1194
|
* @param options Options for Agent creation
|
|
856
1195
|
* @returns Promise resolving to an Agent instance stub
|
|
857
1196
|
*/
|
|
858
|
-
export function getAgentByName<Env, T extends Agent<Env>>(
|
|
1197
|
+
export async function getAgentByName<Env, T extends Agent<Env>>(
|
|
859
1198
|
namespace: AgentNamespace<T>,
|
|
860
1199
|
name: string,
|
|
861
1200
|
options?: {
|
|
@@ -870,13 +1209,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
|
|
|
870
1209
|
* A wrapper for streaming responses in callable methods
|
|
871
1210
|
*/
|
|
872
1211
|
export class StreamingResponse {
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
1212
|
+
private _connection: Connection;
|
|
1213
|
+
private _id: string;
|
|
1214
|
+
private _closed = false;
|
|
876
1215
|
|
|
877
1216
|
constructor(connection: Connection, id: string) {
|
|
878
|
-
this
|
|
879
|
-
this
|
|
1217
|
+
this._connection = connection;
|
|
1218
|
+
this._id = id;
|
|
880
1219
|
}
|
|
881
1220
|
|
|
882
1221
|
/**
|
|
@@ -884,17 +1223,17 @@ export class StreamingResponse {
|
|
|
884
1223
|
* @param chunk The data to send
|
|
885
1224
|
*/
|
|
886
1225
|
send(chunk: unknown) {
|
|
887
|
-
if (this
|
|
1226
|
+
if (this._closed) {
|
|
888
1227
|
throw new Error("StreamingResponse is already closed");
|
|
889
1228
|
}
|
|
890
1229
|
const response: RPCResponse = {
|
|
891
|
-
type: "rpc",
|
|
892
|
-
id: this.#id,
|
|
893
|
-
success: true,
|
|
894
|
-
result: chunk,
|
|
895
1230
|
done: false,
|
|
1231
|
+
id: this._id,
|
|
1232
|
+
result: chunk,
|
|
1233
|
+
success: true,
|
|
1234
|
+
type: "rpc",
|
|
896
1235
|
};
|
|
897
|
-
this
|
|
1236
|
+
this._connection.send(JSON.stringify(response));
|
|
898
1237
|
}
|
|
899
1238
|
|
|
900
1239
|
/**
|
|
@@ -902,17 +1241,17 @@ export class StreamingResponse {
|
|
|
902
1241
|
* @param finalChunk Optional final chunk of data to send
|
|
903
1242
|
*/
|
|
904
1243
|
end(finalChunk?: unknown) {
|
|
905
|
-
if (this
|
|
1244
|
+
if (this._closed) {
|
|
906
1245
|
throw new Error("StreamingResponse is already closed");
|
|
907
1246
|
}
|
|
908
|
-
this
|
|
1247
|
+
this._closed = true;
|
|
909
1248
|
const response: RPCResponse = {
|
|
910
|
-
type: "rpc",
|
|
911
|
-
id: this.#id,
|
|
912
|
-
success: true,
|
|
913
|
-
result: finalChunk,
|
|
914
1249
|
done: true,
|
|
1250
|
+
id: this._id,
|
|
1251
|
+
result: finalChunk,
|
|
1252
|
+
success: true,
|
|
1253
|
+
type: "rpc",
|
|
915
1254
|
};
|
|
916
|
-
this
|
|
1255
|
+
this._connection.send(JSON.stringify(response));
|
|
917
1256
|
}
|
|
918
1257
|
}
|