agents 0.2.14 → 0.2.15

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/src/index.ts DELETED
@@ -1,2167 +0,0 @@
1
- import type { env } from "cloudflare:workers";
2
- import { AsyncLocalStorage } from "node:async_hooks";
3
- import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
- import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
5
-
6
- import type {
7
- Prompt,
8
- Resource,
9
- ServerCapabilities,
10
- Tool
11
- } from "@modelcontextprotocol/sdk/types.js";
12
- import { parseCronExpression } from "cron-schedule";
13
- import { nanoid } from "nanoid";
14
- import { EmailMessage } from "cloudflare:email";
15
- import {
16
- type Connection,
17
- type ConnectionContext,
18
- type PartyServerOptions,
19
- Server,
20
- type WSMessage,
21
- getServerByName,
22
- routePartykitRequest
23
- } from "partyserver";
24
- import { camelCaseToKebabCase } from "./client";
25
- import { MCPClientManager, type MCPClientOAuthResult } from "./mcp/client";
26
- import type { MCPConnectionState } from "./mcp/client-connection";
27
- import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
28
- import type { TransportType } from "./mcp/types";
29
- import { genericObservability, type Observability } from "./observability";
30
- import { DisposableStore } from "./core/events";
31
- import { MessageType } from "./ai-types";
32
-
33
- export type { Connection, ConnectionContext, WSMessage } from "partyserver";
34
-
35
- /**
36
- * RPC request message from client
37
- */
38
- export type RPCRequest = {
39
- type: "rpc";
40
- id: string;
41
- method: string;
42
- args: unknown[];
43
- };
44
-
45
- /**
46
- * State update message from client
47
- */
48
- export type StateUpdateMessage = {
49
- type: MessageType.CF_AGENT_STATE;
50
- state: unknown;
51
- };
52
-
53
- /**
54
- * RPC response message to client
55
- */
56
- export type RPCResponse = {
57
- type: MessageType.RPC;
58
- id: string;
59
- } & (
60
- | {
61
- success: true;
62
- result: unknown;
63
- done?: false;
64
- }
65
- | {
66
- success: true;
67
- result: unknown;
68
- done: true;
69
- }
70
- | {
71
- success: false;
72
- error: string;
73
- }
74
- );
75
-
76
- /**
77
- * Type guard for RPC request messages
78
- */
79
- function isRPCRequest(msg: unknown): msg is RPCRequest {
80
- return (
81
- typeof msg === "object" &&
82
- msg !== null &&
83
- "type" in msg &&
84
- msg.type === MessageType.RPC &&
85
- "id" in msg &&
86
- typeof msg.id === "string" &&
87
- "method" in msg &&
88
- typeof msg.method === "string" &&
89
- "args" in msg &&
90
- Array.isArray((msg as RPCRequest).args)
91
- );
92
- }
93
-
94
- /**
95
- * Type guard for state update messages
96
- */
97
- function isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {
98
- return (
99
- typeof msg === "object" &&
100
- msg !== null &&
101
- "type" in msg &&
102
- msg.type === MessageType.CF_AGENT_STATE &&
103
- "state" in msg
104
- );
105
- }
106
-
107
- /**
108
- * Metadata for a callable method
109
- */
110
- export type CallableMetadata = {
111
- /** Optional description of what the method does */
112
- description?: string;
113
- /** Whether the method supports streaming responses */
114
- streaming?: boolean;
115
- };
116
-
117
- const callableMetadata = new Map<Function, CallableMetadata>();
118
-
119
- /**
120
- * Decorator that marks a method as callable by clients
121
- * @param metadata Optional metadata about the callable method
122
- */
123
- export function callable(metadata: CallableMetadata = {}) {
124
- return function callableDecorator<This, Args extends unknown[], Return>(
125
- target: (this: This, ...args: Args) => Return,
126
- // biome-ignore lint/correctness/noUnusedFunctionParameters: later
127
- context: ClassMethodDecoratorContext
128
- ) {
129
- if (!callableMetadata.has(target)) {
130
- callableMetadata.set(target, metadata);
131
- }
132
-
133
- return target;
134
- };
135
- }
136
-
137
- let didWarnAboutUnstableCallable = false;
138
-
139
- /**
140
- * Decorator that marks a method as callable by clients
141
- * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
142
- * @param metadata Optional metadata about the callable method
143
- */
144
- export const unstable_callable = (metadata: CallableMetadata = {}) => {
145
- if (!didWarnAboutUnstableCallable) {
146
- didWarnAboutUnstableCallable = true;
147
- console.warn(
148
- "unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version."
149
- );
150
- }
151
- callable(metadata);
152
- };
153
-
154
- export type QueueItem<T = string> = {
155
- id: string;
156
- payload: T;
157
- callback: keyof Agent<unknown>;
158
- created_at: number;
159
- };
160
-
161
- /**
162
- * Represents a scheduled task within an Agent
163
- * @template T Type of the payload data
164
- */
165
- export type Schedule<T = string> = {
166
- /** Unique identifier for the schedule */
167
- id: string;
168
- /** Name of the method to be called */
169
- callback: string;
170
- /** Data to be passed to the callback */
171
- payload: T;
172
- } & (
173
- | {
174
- /** Type of schedule for one-time execution at a specific time */
175
- type: "scheduled";
176
- /** Timestamp when the task should execute */
177
- time: number;
178
- }
179
- | {
180
- /** Type of schedule for delayed execution */
181
- type: "delayed";
182
- /** Timestamp when the task should execute */
183
- time: number;
184
- /** Number of seconds to delay execution */
185
- delayInSeconds: number;
186
- }
187
- | {
188
- /** Type of schedule for recurring execution based on cron expression */
189
- type: "cron";
190
- /** Timestamp for the next execution */
191
- time: number;
192
- /** Cron expression defining the schedule */
193
- cron: string;
194
- }
195
- );
196
-
197
- function getNextCronTime(cron: string) {
198
- const interval = parseCronExpression(cron);
199
- return interval.getNextDate();
200
- }
201
-
202
- export type { TransportType } from "./mcp/types";
203
-
204
- /**
205
- * MCP Server state update message from server -> Client
206
- */
207
- export type MCPServerMessage = {
208
- type: MessageType.CF_AGENT_MCP_SERVERS;
209
- mcp: MCPServersState;
210
- };
211
-
212
- export type MCPServersState = {
213
- servers: {
214
- [id: string]: MCPServer;
215
- };
216
- tools: Tool[];
217
- prompts: Prompt[];
218
- resources: Resource[];
219
- };
220
-
221
- export type MCPServer = {
222
- name: string;
223
- server_url: string;
224
- auth_url: string | null;
225
- // This state is specifically about the temporary process of getting a token (if needed).
226
- // Scope outside of that can't be relied upon because when the DO sleeps, there's no way
227
- // to communicate a change to a non-ready state.
228
- state: MCPConnectionState;
229
- instructions: string | null;
230
- capabilities: ServerCapabilities | null;
231
- };
232
-
233
- /**
234
- * MCP Server data stored in DO SQL for resuming MCP Server connections
235
- */
236
- type MCPServerRow = {
237
- id: string;
238
- name: string;
239
- server_url: string;
240
- client_id: string | null;
241
- auth_url: string | null;
242
- callback_url: string;
243
- server_options: string;
244
- };
245
-
246
- const STATE_ROW_ID = "cf_state_row_id";
247
- const STATE_WAS_CHANGED = "cf_state_was_changed";
248
-
249
- const DEFAULT_STATE = {} as unknown;
250
-
251
- const agentContext = new AsyncLocalStorage<{
252
- agent: Agent<unknown, unknown>;
253
- connection: Connection | undefined;
254
- request: Request | undefined;
255
- email: AgentEmail | undefined;
256
- }>();
257
-
258
- export function getCurrentAgent<
259
- T extends Agent<unknown, unknown> = Agent<unknown, unknown>
260
- >(): {
261
- agent: T | undefined;
262
- connection: Connection | undefined;
263
- request: Request | undefined;
264
- email: AgentEmail | undefined;
265
- } {
266
- const store = agentContext.getStore() as
267
- | {
268
- agent: T;
269
- connection: Connection | undefined;
270
- request: Request | undefined;
271
- email: AgentEmail | undefined;
272
- }
273
- | undefined;
274
- if (!store) {
275
- return {
276
- agent: undefined,
277
- connection: undefined,
278
- request: undefined,
279
- email: undefined
280
- };
281
- }
282
- return store;
283
- }
284
-
285
- /**
286
- * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
287
- * @param agent The agent instance
288
- * @param method The method to wrap
289
- * @returns A wrapped method that runs within the agent context
290
- */
291
-
292
- // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
293
- function withAgentContext<T extends (...args: any[]) => any>(
294
- method: T
295
- ): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {
296
- return function (...args: Parameters<T>): ReturnType<T> {
297
- const { connection, request, email, agent } = getCurrentAgent();
298
-
299
- if (agent === this) {
300
- // already wrapped, so we can just call the method
301
- return method.apply(this, args);
302
- }
303
- // not wrapped, so we need to wrap it
304
- return agentContext.run({ agent: this, connection, request, email }, () => {
305
- return method.apply(this, args);
306
- });
307
- };
308
- }
309
-
310
- /**
311
- * Base class for creating Agent implementations
312
- * @template Env Environment type containing bindings
313
- * @template State State type to store within the Agent
314
- */
315
- export class Agent<
316
- Env = typeof env,
317
- State = unknown,
318
- Props extends Record<string, unknown> = Record<string, unknown>
319
- > extends Server<Env, Props> {
320
- private _state = DEFAULT_STATE as State;
321
- private _disposables = new DisposableStore();
322
-
323
- private _ParentClass: typeof Agent<Env, State> =
324
- Object.getPrototypeOf(this).constructor;
325
-
326
- readonly mcp: MCPClientManager = new MCPClientManager(
327
- this._ParentClass.name,
328
- "0.0.1"
329
- );
330
-
331
- /**
332
- * Initial state for the Agent
333
- * Override to provide default state values
334
- */
335
- initialState: State = DEFAULT_STATE as State;
336
-
337
- /**
338
- * Current state of the Agent
339
- */
340
- get state(): State {
341
- if (this._state !== DEFAULT_STATE) {
342
- // state was previously set, and populated internal state
343
- return this._state;
344
- }
345
- // looks like this is the first time the state is being accessed
346
- // check if the state was set in a previous life
347
- const wasChanged = this.sql<{ state: "true" | undefined }>`
348
- SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
349
- `;
350
-
351
- // ok, let's pick up the actual state from the db
352
- const result = this.sql<{ state: State | undefined }>`
353
- SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
354
- `;
355
-
356
- if (
357
- wasChanged[0]?.state === "true" ||
358
- // we do this check for people who updated their code before we shipped wasChanged
359
- result[0]?.state
360
- ) {
361
- const state = result[0]?.state as string; // could be null?
362
-
363
- this._state = JSON.parse(state);
364
- return this._state;
365
- }
366
-
367
- // ok, this is the first time the state is being accessed
368
- // and the state was not set in a previous life
369
- // so we need to set the initial state (if provided)
370
- if (this.initialState === DEFAULT_STATE) {
371
- // no initial state provided, so we return undefined
372
- return undefined as State;
373
- }
374
- // initial state provided, so we set the state,
375
- // update db and return the initial state
376
- this.setState(this.initialState);
377
- return this.initialState;
378
- }
379
-
380
- /**
381
- * Agent configuration options
382
- */
383
- static options = {
384
- /** Whether the Agent should hibernate when inactive */
385
- hibernate: true // default to hibernate
386
- };
387
-
388
- /**
389
- * The observability implementation to use for the Agent
390
- */
391
- observability?: Observability = genericObservability;
392
-
393
- /**
394
- * Execute SQL queries against the Agent's database
395
- * @template T Type of the returned rows
396
- * @param strings SQL query template strings
397
- * @param values Values to be inserted into the query
398
- * @returns Array of query results
399
- */
400
- sql<T = Record<string, string | number | boolean | null>>(
401
- strings: TemplateStringsArray,
402
- ...values: (string | number | boolean | null)[]
403
- ) {
404
- let query = "";
405
- try {
406
- // Construct the SQL query with placeholders
407
- query = strings.reduce(
408
- (acc, str, i) => acc + str + (i < values.length ? "?" : ""),
409
- ""
410
- );
411
-
412
- // Execute the SQL query with the provided values
413
- return [...this.ctx.storage.sql.exec(query, ...values)] as T[];
414
- } catch (e) {
415
- console.error(`failed to execute sql query: ${query}`, e);
416
- throw this.onError(e);
417
- }
418
- }
419
- constructor(ctx: AgentContext, env: Env) {
420
- super(ctx, env);
421
-
422
- if (!wrappedClasses.has(this.constructor)) {
423
- // Auto-wrap custom methods with agent context
424
- this._autoWrapCustomMethods();
425
- wrappedClasses.add(this.constructor);
426
- }
427
-
428
- // Broadcast server state after background connects (for OAuth servers)
429
- this._disposables.add(
430
- this.mcp.onConnected(async () => {
431
- this.broadcastMcpServers();
432
- })
433
- );
434
-
435
- // Emit MCP observability events
436
- this._disposables.add(
437
- this.mcp.onObservabilityEvent((event) => {
438
- this.observability?.emit(event);
439
- })
440
- );
441
-
442
- this.sql`
443
- CREATE TABLE IF NOT EXISTS cf_agents_state (
444
- id TEXT PRIMARY KEY NOT NULL,
445
- state TEXT
446
- )
447
- `;
448
-
449
- this.sql`
450
- CREATE TABLE IF NOT EXISTS cf_agents_queues (
451
- id TEXT PRIMARY KEY NOT NULL,
452
- payload TEXT,
453
- callback TEXT,
454
- created_at INTEGER DEFAULT (unixepoch())
455
- )
456
- `;
457
-
458
- void this.ctx.blockConcurrencyWhile(async () => {
459
- return this._tryCatch(async () => {
460
- // Create alarms table if it doesn't exist
461
- this.sql`
462
- CREATE TABLE IF NOT EXISTS cf_agents_schedules (
463
- id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
464
- callback TEXT,
465
- payload TEXT,
466
- type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
467
- time INTEGER,
468
- delayInSeconds INTEGER,
469
- cron TEXT,
470
- created_at INTEGER DEFAULT (unixepoch())
471
- )
472
- `;
473
-
474
- // execute any pending alarms and schedule the next alarm
475
- await this.alarm();
476
- });
477
- });
478
-
479
- this.sql`
480
- CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
481
- id TEXT PRIMARY KEY NOT NULL,
482
- name TEXT NOT NULL,
483
- server_url TEXT NOT NULL,
484
- callback_url TEXT NOT NULL,
485
- client_id TEXT,
486
- auth_url TEXT,
487
- server_options TEXT
488
- )
489
- `;
490
-
491
- const _onRequest = this.onRequest.bind(this);
492
- this.onRequest = (request: Request) => {
493
- return agentContext.run(
494
- { agent: this, connection: undefined, request, email: undefined },
495
- async () => {
496
- // Check if this is an OAuth callback and restore state if needed
497
- const callbackResult =
498
- await this._handlePotentialOAuthCallback(request);
499
- if (callbackResult) {
500
- return callbackResult;
501
- }
502
-
503
- return this._tryCatch(() => _onRequest(request));
504
- }
505
- );
506
- };
507
-
508
- const _onMessage = this.onMessage.bind(this);
509
- this.onMessage = async (connection: Connection, message: WSMessage) => {
510
- return agentContext.run(
511
- { agent: this, connection, request: undefined, email: undefined },
512
- async () => {
513
- if (typeof message !== "string") {
514
- return this._tryCatch(() => _onMessage(connection, message));
515
- }
516
-
517
- let parsed: unknown;
518
- try {
519
- parsed = JSON.parse(message);
520
- } catch (_e) {
521
- // silently fail and let the onMessage handler handle it
522
- return this._tryCatch(() => _onMessage(connection, message));
523
- }
524
-
525
- if (isStateUpdateMessage(parsed)) {
526
- this._setStateInternal(parsed.state as State, connection);
527
- return;
528
- }
529
-
530
- if (isRPCRequest(parsed)) {
531
- try {
532
- const { id, method, args } = parsed;
533
-
534
- // Check if method exists and is callable
535
- const methodFn = this[method as keyof this];
536
- if (typeof methodFn !== "function") {
537
- throw new Error(`Method ${method} does not exist`);
538
- }
539
-
540
- if (!this._isCallable(method)) {
541
- throw new Error(`Method ${method} is not callable`);
542
- }
543
-
544
- const metadata = callableMetadata.get(methodFn as Function);
545
-
546
- // For streaming methods, pass a StreamingResponse object
547
- if (metadata?.streaming) {
548
- const stream = new StreamingResponse(connection, id);
549
- await methodFn.apply(this, [stream, ...args]);
550
- return;
551
- }
552
-
553
- // For regular methods, execute and send response
554
- const result = await methodFn.apply(this, args);
555
-
556
- this.observability?.emit(
557
- {
558
- displayMessage: `RPC call to ${method}`,
559
- id: nanoid(),
560
- payload: {
561
- method,
562
- streaming: metadata?.streaming
563
- },
564
- timestamp: Date.now(),
565
- type: "rpc"
566
- },
567
- this.ctx
568
- );
569
-
570
- const response: RPCResponse = {
571
- done: true,
572
- id,
573
- result,
574
- success: true,
575
- type: MessageType.RPC
576
- };
577
- connection.send(JSON.stringify(response));
578
- } catch (e) {
579
- // Send error response
580
- const response: RPCResponse = {
581
- error:
582
- e instanceof Error ? e.message : "Unknown error occurred",
583
- id: parsed.id,
584
- success: false,
585
- type: MessageType.RPC
586
- };
587
- connection.send(JSON.stringify(response));
588
- console.error("RPC error:", e);
589
- }
590
- return;
591
- }
592
-
593
- return this._tryCatch(() => _onMessage(connection, message));
594
- }
595
- );
596
- };
597
-
598
- const _onConnect = this.onConnect.bind(this);
599
- this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
600
- // TODO: This is a hack to ensure the state is sent after the connection is established
601
- // must fix this
602
- return agentContext.run(
603
- { agent: this, connection, request: ctx.request, email: undefined },
604
- () => {
605
- if (this.state) {
606
- connection.send(
607
- JSON.stringify({
608
- state: this.state,
609
- type: MessageType.CF_AGENT_STATE
610
- })
611
- );
612
- }
613
-
614
- connection.send(
615
- JSON.stringify({
616
- mcp: this.getMcpServers(),
617
- type: MessageType.CF_AGENT_MCP_SERVERS
618
- })
619
- );
620
-
621
- this.observability?.emit(
622
- {
623
- displayMessage: "Connection established",
624
- id: nanoid(),
625
- payload: {
626
- connectionId: connection.id
627
- },
628
- timestamp: Date.now(),
629
- type: "connect"
630
- },
631
- this.ctx
632
- );
633
- return this._tryCatch(() => _onConnect(connection, ctx));
634
- }
635
- );
636
- };
637
-
638
- const _onStart = this.onStart.bind(this);
639
- this.onStart = async (props?: Props) => {
640
- return agentContext.run(
641
- {
642
- agent: this,
643
- connection: undefined,
644
- request: undefined,
645
- email: undefined
646
- },
647
- async () => {
648
- await this._tryCatch(() => {
649
- const servers = this.sql<MCPServerRow>`
650
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
651
- `;
652
-
653
- this.broadcastMcpServers();
654
-
655
- // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
656
- if (servers && Array.isArray(servers) && servers.length > 0) {
657
- // Restore callback URLs for OAuth-enabled servers
658
- servers.forEach((server) => {
659
- if (server.callback_url) {
660
- // Register the full redirect URL including serverId to avoid ambiguous matches
661
- this.mcp.registerCallbackUrl(
662
- `${server.callback_url}/${server.id}`
663
- );
664
- }
665
- });
666
-
667
- servers.forEach((server) => {
668
- this._connectToMcpServerInternal(
669
- server.name,
670
- server.server_url,
671
- server.callback_url,
672
- server.server_options
673
- ? JSON.parse(server.server_options)
674
- : undefined,
675
- {
676
- id: server.id,
677
- oauthClientId: server.client_id ?? undefined
678
- }
679
- )
680
- .then(() => {
681
- // Broadcast updated MCP servers state after each server connects
682
- this.broadcastMcpServers();
683
- })
684
- .catch((error) => {
685
- console.error(
686
- `Error connecting to MCP server: ${server.name} (${server.server_url})`,
687
- error
688
- );
689
- // Still broadcast even if connection fails, so clients know about the failure
690
- this.broadcastMcpServers();
691
- });
692
- });
693
- }
694
- return _onStart(props);
695
- });
696
- }
697
- );
698
- };
699
- }
700
-
701
- private _setStateInternal(
702
- state: State,
703
- source: Connection | "server" = "server"
704
- ) {
705
- this._state = state;
706
- this.sql`
707
- INSERT OR REPLACE INTO cf_agents_state (id, state)
708
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
709
- `;
710
- this.sql`
711
- INSERT OR REPLACE INTO cf_agents_state (id, state)
712
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
713
- `;
714
- this.broadcast(
715
- JSON.stringify({
716
- state: state,
717
- type: MessageType.CF_AGENT_STATE
718
- }),
719
- source !== "server" ? [source.id] : []
720
- );
721
- return this._tryCatch(() => {
722
- const { connection, request, email } = agentContext.getStore() || {};
723
- return agentContext.run(
724
- { agent: this, connection, request, email },
725
- async () => {
726
- this.observability?.emit(
727
- {
728
- displayMessage: "State updated",
729
- id: nanoid(),
730
- payload: {},
731
- timestamp: Date.now(),
732
- type: "state:update"
733
- },
734
- this.ctx
735
- );
736
- return this.onStateUpdate(state, source);
737
- }
738
- );
739
- });
740
- }
741
-
742
- /**
743
- * Update the Agent's state
744
- * @param state New state to set
745
- */
746
- setState(state: State) {
747
- this._setStateInternal(state, "server");
748
- }
749
-
750
- /**
751
- * Called when the Agent's state is updated
752
- * @param state Updated state
753
- * @param source Source of the state update ("server" or a client connection)
754
- */
755
- // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
756
- onStateUpdate(state: State | undefined, source: Connection | "server") {
757
- // override this to handle state updates
758
- }
759
-
760
- /**
761
- * Called when the Agent receives an email via routeAgentEmail()
762
- * Override this method to handle incoming emails
763
- * @param email Email message to process
764
- */
765
- async _onEmail(email: AgentEmail) {
766
- // nb: we use this roundabout way of getting to onEmail
767
- // because of https://github.com/cloudflare/workerd/issues/4499
768
- return agentContext.run(
769
- { agent: this, connection: undefined, request: undefined, email: email },
770
- async () => {
771
- if ("onEmail" in this && typeof this.onEmail === "function") {
772
- return this._tryCatch(() =>
773
- (this.onEmail as (email: AgentEmail) => Promise<void>)(email)
774
- );
775
- } else {
776
- console.log("Received email from:", email.from, "to:", email.to);
777
- console.log("Subject:", email.headers.get("subject"));
778
- console.log(
779
- "Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
780
- );
781
- }
782
- }
783
- );
784
- }
785
-
786
- /**
787
- * Reply to an email
788
- * @param email The email to reply to
789
- * @param options Options for the reply
790
- * @returns void
791
- */
792
- async replyToEmail(
793
- email: AgentEmail,
794
- options: {
795
- fromName: string;
796
- subject?: string | undefined;
797
- body: string;
798
- contentType?: string;
799
- headers?: Record<string, string>;
800
- }
801
- ): Promise<void> {
802
- return this._tryCatch(async () => {
803
- const agentName = camelCaseToKebabCase(this._ParentClass.name);
804
- const agentId = this.name;
805
-
806
- const { createMimeMessage } = await import("mimetext");
807
- const msg = createMimeMessage();
808
- msg.setSender({ addr: email.to, name: options.fromName });
809
- msg.setRecipient(email.from);
810
- msg.setSubject(
811
- options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
812
- );
813
- msg.addMessage({
814
- contentType: options.contentType || "text/plain",
815
- data: options.body
816
- });
817
-
818
- const domain = email.from.split("@")[1];
819
- const messageId = `<${agentId}@${domain}>`;
820
- msg.setHeader("In-Reply-To", email.headers.get("Message-ID")!);
821
- msg.setHeader("Message-ID", messageId);
822
- msg.setHeader("X-Agent-Name", agentName);
823
- msg.setHeader("X-Agent-ID", agentId);
824
-
825
- if (options.headers) {
826
- for (const [key, value] of Object.entries(options.headers)) {
827
- msg.setHeader(key, value);
828
- }
829
- }
830
- await email.reply({
831
- from: email.to,
832
- raw: msg.asRaw(),
833
- to: email.from
834
- });
835
- });
836
- }
837
-
838
- private async _tryCatch<T>(fn: () => T | Promise<T>) {
839
- try {
840
- return await fn();
841
- } catch (e) {
842
- throw this.onError(e);
843
- }
844
- }
845
-
846
- /**
847
- * Automatically wrap custom methods with agent context
848
- * This ensures getCurrentAgent() works in all custom methods without decorators
849
- */
850
- private _autoWrapCustomMethods() {
851
- // Collect all methods from base prototypes (Agent and Server)
852
- const basePrototypes = [Agent.prototype, Server.prototype];
853
- const baseMethods = new Set<string>();
854
- for (const baseProto of basePrototypes) {
855
- let proto = baseProto;
856
- while (proto && proto !== Object.prototype) {
857
- const methodNames = Object.getOwnPropertyNames(proto);
858
- for (const methodName of methodNames) {
859
- baseMethods.add(methodName);
860
- }
861
- proto = Object.getPrototypeOf(proto);
862
- }
863
- }
864
- // Get all methods from the current instance's prototype chain
865
- let proto = Object.getPrototypeOf(this);
866
- let depth = 0;
867
- while (proto && proto !== Object.prototype && depth < 10) {
868
- const methodNames = Object.getOwnPropertyNames(proto);
869
- for (const methodName of methodNames) {
870
- const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
871
-
872
- // Skip if it's a private method, a base method, a getter, or not a function,
873
- if (
874
- baseMethods.has(methodName) ||
875
- methodName.startsWith("_") ||
876
- !descriptor ||
877
- !!descriptor.get ||
878
- typeof descriptor.value !== "function"
879
- ) {
880
- continue;
881
- }
882
-
883
- // Now, methodName is confirmed to be a custom method/function
884
- // Wrap the custom method with context
885
- const wrappedFunction = withAgentContext(
886
- // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
887
- this[methodName as keyof this] as (...args: any[]) => any
888
- // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
889
- ) as any;
890
-
891
- // if the method is callable, copy the metadata from the original method
892
- if (this._isCallable(methodName)) {
893
- callableMetadata.set(
894
- wrappedFunction,
895
- callableMetadata.get(this[methodName as keyof this] as Function)!
896
- );
897
- }
898
-
899
- // set the wrapped function on the prototype
900
- this.constructor.prototype[methodName as keyof this] = wrappedFunction;
901
- }
902
-
903
- proto = Object.getPrototypeOf(proto);
904
- depth++;
905
- }
906
- }
907
-
908
- override onError(
909
- connection: Connection,
910
- error: unknown
911
- ): void | Promise<void>;
912
- override onError(error: unknown): void | Promise<void>;
913
- override onError(connectionOrError: Connection | unknown, error?: unknown) {
914
- let theError: unknown;
915
- if (connectionOrError && error) {
916
- theError = error;
917
- // this is a websocket connection error
918
- console.error(
919
- "Error on websocket connection:",
920
- (connectionOrError as Connection).id,
921
- theError
922
- );
923
- console.error(
924
- "Override onError(connection, error) to handle websocket connection errors"
925
- );
926
- } else {
927
- theError = connectionOrError;
928
- // this is a server error
929
- console.error("Error on server:", theError);
930
- console.error("Override onError(error) to handle server errors");
931
- }
932
- throw theError;
933
- }
934
-
935
- /**
936
- * Render content (not implemented in base class)
937
- */
938
- render() {
939
- throw new Error("Not implemented");
940
- }
941
-
942
- /**
943
- * Queue a task to be executed in the future
944
- * @param payload Payload to pass to the callback
945
- * @param callback Name of the method to call
946
- * @returns The ID of the queued task
947
- */
948
- async queue<T = unknown>(callback: keyof this, payload: T): Promise<string> {
949
- const id = nanoid(9);
950
- if (typeof callback !== "string") {
951
- throw new Error("Callback must be a string");
952
- }
953
-
954
- if (typeof this[callback] !== "function") {
955
- throw new Error(`this.${callback} is not a function`);
956
- }
957
-
958
- this.sql`
959
- INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
960
- VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
961
- `;
962
-
963
- void this._flushQueue().catch((e) => {
964
- console.error("Error flushing queue:", e);
965
- });
966
-
967
- return id;
968
- }
969
-
970
- private _flushingQueue = false;
971
-
972
- private async _flushQueue() {
973
- if (this._flushingQueue) {
974
- return;
975
- }
976
- this._flushingQueue = true;
977
- while (true) {
978
- const result = this.sql<QueueItem<string>>`
979
- SELECT * FROM cf_agents_queues
980
- ORDER BY created_at ASC
981
- `;
982
-
983
- if (!result || result.length === 0) {
984
- break;
985
- }
986
-
987
- for (const row of result || []) {
988
- const callback = this[row.callback as keyof Agent<Env>];
989
- if (!callback) {
990
- console.error(`callback ${row.callback} not found`);
991
- continue;
992
- }
993
- const { connection, request, email } = agentContext.getStore() || {};
994
- await agentContext.run(
995
- {
996
- agent: this,
997
- connection,
998
- request,
999
- email
1000
- },
1001
- async () => {
1002
- // TODO: add retries and backoff
1003
- await (
1004
- callback as (
1005
- payload: unknown,
1006
- queueItem: QueueItem<string>
1007
- ) => Promise<void>
1008
- ).bind(this)(JSON.parse(row.payload as string), row);
1009
- await this.dequeue(row.id);
1010
- }
1011
- );
1012
- }
1013
- }
1014
- this._flushingQueue = false;
1015
- }
1016
-
1017
- /**
1018
- * Dequeue a task by ID
1019
- * @param id ID of the task to dequeue
1020
- */
1021
- async dequeue(id: string) {
1022
- this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
1023
- }
1024
-
1025
- /**
1026
- * Dequeue all tasks
1027
- */
1028
- async dequeueAll() {
1029
- this.sql`DELETE FROM cf_agents_queues`;
1030
- }
1031
-
1032
- /**
1033
- * Dequeue all tasks by callback
1034
- * @param callback Name of the callback to dequeue
1035
- */
1036
- async dequeueAllByCallback(callback: string) {
1037
- this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
1038
- }
1039
-
1040
- /**
1041
- * Get a queued task by ID
1042
- * @param id ID of the task to get
1043
- * @returns The task or undefined if not found
1044
- */
1045
- async getQueue(id: string): Promise<QueueItem<string> | undefined> {
1046
- const result = this.sql<QueueItem<string>>`
1047
- SELECT * FROM cf_agents_queues WHERE id = ${id}
1048
- `;
1049
- return result
1050
- ? { ...result[0], payload: JSON.parse(result[0].payload) }
1051
- : undefined;
1052
- }
1053
-
1054
- /**
1055
- * Get all queues by key and value
1056
- * @param key Key to filter by
1057
- * @param value Value to filter by
1058
- * @returns Array of matching QueueItem objects
1059
- */
1060
- async getQueues(key: string, value: string): Promise<QueueItem<string>[]> {
1061
- const result = this.sql<QueueItem<string>>`
1062
- SELECT * FROM cf_agents_queues
1063
- `;
1064
- return result.filter((row) => JSON.parse(row.payload)[key] === value);
1065
- }
1066
-
1067
- /**
1068
- * Schedule a task to be executed in the future
1069
- * @template T Type of the payload data
1070
- * @param when When to execute the task (Date, seconds delay, or cron expression)
1071
- * @param callback Name of the method to call
1072
- * @param payload Data to pass to the callback
1073
- * @returns Schedule object representing the scheduled task
1074
- */
1075
- async schedule<T = string>(
1076
- when: Date | string | number,
1077
- callback: keyof this,
1078
- payload?: T
1079
- ): Promise<Schedule<T>> {
1080
- const id = nanoid(9);
1081
-
1082
- const emitScheduleCreate = (schedule: Schedule<T>) =>
1083
- this.observability?.emit(
1084
- {
1085
- displayMessage: `Schedule ${schedule.id} created`,
1086
- id: nanoid(),
1087
- payload: {
1088
- callback: callback as string,
1089
- id: id
1090
- },
1091
- timestamp: Date.now(),
1092
- type: "schedule:create"
1093
- },
1094
- this.ctx
1095
- );
1096
-
1097
- if (typeof callback !== "string") {
1098
- throw new Error("Callback must be a string");
1099
- }
1100
-
1101
- if (typeof this[callback] !== "function") {
1102
- throw new Error(`this.${callback} is not a function`);
1103
- }
1104
-
1105
- if (when instanceof Date) {
1106
- const timestamp = Math.floor(when.getTime() / 1000);
1107
- this.sql`
1108
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
1109
- VALUES (${id}, ${callback}, ${JSON.stringify(
1110
- payload
1111
- )}, 'scheduled', ${timestamp})
1112
- `;
1113
-
1114
- await this._scheduleNextAlarm();
1115
-
1116
- const schedule: Schedule<T> = {
1117
- callback: callback,
1118
- id,
1119
- payload: payload as T,
1120
- time: timestamp,
1121
- type: "scheduled"
1122
- };
1123
-
1124
- emitScheduleCreate(schedule);
1125
-
1126
- return schedule;
1127
- }
1128
- if (typeof when === "number") {
1129
- const time = new Date(Date.now() + when * 1000);
1130
- const timestamp = Math.floor(time.getTime() / 1000);
1131
-
1132
- this.sql`
1133
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
1134
- VALUES (${id}, ${callback}, ${JSON.stringify(
1135
- payload
1136
- )}, 'delayed', ${when}, ${timestamp})
1137
- `;
1138
-
1139
- await this._scheduleNextAlarm();
1140
-
1141
- const schedule: Schedule<T> = {
1142
- callback: callback,
1143
- delayInSeconds: when,
1144
- id,
1145
- payload: payload as T,
1146
- time: timestamp,
1147
- type: "delayed"
1148
- };
1149
-
1150
- emitScheduleCreate(schedule);
1151
-
1152
- return schedule;
1153
- }
1154
- if (typeof when === "string") {
1155
- const nextExecutionTime = getNextCronTime(when);
1156
- const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1157
-
1158
- this.sql`
1159
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
1160
- VALUES (${id}, ${callback}, ${JSON.stringify(
1161
- payload
1162
- )}, 'cron', ${when}, ${timestamp})
1163
- `;
1164
-
1165
- await this._scheduleNextAlarm();
1166
-
1167
- const schedule: Schedule<T> = {
1168
- callback: callback,
1169
- cron: when,
1170
- id,
1171
- payload: payload as T,
1172
- time: timestamp,
1173
- type: "cron"
1174
- };
1175
-
1176
- emitScheduleCreate(schedule);
1177
-
1178
- return schedule;
1179
- }
1180
- throw new Error("Invalid schedule type");
1181
- }
1182
-
1183
- /**
1184
- * Get a scheduled task by ID
1185
- * @template T Type of the payload data
1186
- * @param id ID of the scheduled task
1187
- * @returns The Schedule object or undefined if not found
1188
- */
1189
- async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {
1190
- const result = this.sql<Schedule<string>>`
1191
- SELECT * FROM cf_agents_schedules WHERE id = ${id}
1192
- `;
1193
- if (!result) {
1194
- console.error(`schedule ${id} not found`);
1195
- return undefined;
1196
- }
1197
-
1198
- return { ...result[0], payload: JSON.parse(result[0].payload) as T };
1199
- }
1200
-
1201
- /**
1202
- * Get scheduled tasks matching the given criteria
1203
- * @template T Type of the payload data
1204
- * @param criteria Criteria to filter schedules
1205
- * @returns Array of matching Schedule objects
1206
- */
1207
- getSchedules<T = string>(
1208
- criteria: {
1209
- id?: string;
1210
- type?: "scheduled" | "delayed" | "cron";
1211
- timeRange?: { start?: Date; end?: Date };
1212
- } = {}
1213
- ): Schedule<T>[] {
1214
- let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
1215
- const params = [];
1216
-
1217
- if (criteria.id) {
1218
- query += " AND id = ?";
1219
- params.push(criteria.id);
1220
- }
1221
-
1222
- if (criteria.type) {
1223
- query += " AND type = ?";
1224
- params.push(criteria.type);
1225
- }
1226
-
1227
- if (criteria.timeRange) {
1228
- query += " AND time >= ? AND time <= ?";
1229
- const start = criteria.timeRange.start || new Date(0);
1230
- const end = criteria.timeRange.end || new Date(999999999999999);
1231
- params.push(
1232
- Math.floor(start.getTime() / 1000),
1233
- Math.floor(end.getTime() / 1000)
1234
- );
1235
- }
1236
-
1237
- const result = this.ctx.storage.sql
1238
- .exec(query, ...params)
1239
- .toArray()
1240
- .map((row) => ({
1241
- ...row,
1242
- payload: JSON.parse(row.payload as string) as T
1243
- })) as Schedule<T>[];
1244
-
1245
- return result;
1246
- }
1247
-
1248
- /**
1249
- * Cancel a scheduled task
1250
- * @param id ID of the task to cancel
1251
- * @returns true if the task was cancelled, false otherwise
1252
- */
1253
- async cancelSchedule(id: string): Promise<boolean> {
1254
- const schedule = await this.getSchedule(id);
1255
- if (schedule) {
1256
- this.observability?.emit(
1257
- {
1258
- displayMessage: `Schedule ${id} cancelled`,
1259
- id: nanoid(),
1260
- payload: {
1261
- callback: schedule.callback,
1262
- id: schedule.id
1263
- },
1264
- timestamp: Date.now(),
1265
- type: "schedule:cancel"
1266
- },
1267
- this.ctx
1268
- );
1269
- }
1270
- this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
1271
-
1272
- await this._scheduleNextAlarm();
1273
- return true;
1274
- }
1275
-
1276
- private async _scheduleNextAlarm() {
1277
- // Find the next schedule that needs to be executed
1278
- const result = this.sql`
1279
- SELECT time FROM cf_agents_schedules
1280
- WHERE time > ${Math.floor(Date.now() / 1000)}
1281
- ORDER BY time ASC
1282
- LIMIT 1
1283
- `;
1284
- if (!result) return;
1285
-
1286
- if (result.length > 0 && "time" in result[0]) {
1287
- const nextTime = (result[0].time as number) * 1000;
1288
- await this.ctx.storage.setAlarm(nextTime);
1289
- }
1290
- }
1291
-
1292
- /**
1293
- * Method called when an alarm fires.
1294
- * Executes any scheduled tasks that are due.
1295
- *
1296
- * @remarks
1297
- * To schedule a task, please use the `this.schedule` method instead.
1298
- * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
1299
- */
1300
- public readonly alarm = async () => {
1301
- const now = Math.floor(Date.now() / 1000);
1302
-
1303
- // Get all schedules that should be executed now
1304
- const result = this.sql<Schedule<string>>`
1305
- SELECT * FROM cf_agents_schedules WHERE time <= ${now}
1306
- `;
1307
-
1308
- if (result && Array.isArray(result)) {
1309
- for (const row of result) {
1310
- const callback = this[row.callback as keyof Agent<Env>];
1311
- if (!callback) {
1312
- console.error(`callback ${row.callback} not found`);
1313
- continue;
1314
- }
1315
- await agentContext.run(
1316
- {
1317
- agent: this,
1318
- connection: undefined,
1319
- request: undefined,
1320
- email: undefined
1321
- },
1322
- async () => {
1323
- try {
1324
- this.observability?.emit(
1325
- {
1326
- displayMessage: `Schedule ${row.id} executed`,
1327
- id: nanoid(),
1328
- payload: {
1329
- callback: row.callback,
1330
- id: row.id
1331
- },
1332
- timestamp: Date.now(),
1333
- type: "schedule:execute"
1334
- },
1335
- this.ctx
1336
- );
1337
-
1338
- await (
1339
- callback as (
1340
- payload: unknown,
1341
- schedule: Schedule<unknown>
1342
- ) => Promise<void>
1343
- ).bind(this)(JSON.parse(row.payload as string), row);
1344
- } catch (e) {
1345
- console.error(`error executing callback "${row.callback}"`, e);
1346
- }
1347
- }
1348
- );
1349
- if (row.type === "cron") {
1350
- // Update next execution time for cron schedules
1351
- const nextExecutionTime = getNextCronTime(row.cron);
1352
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1353
-
1354
- this.sql`
1355
- UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
1356
- `;
1357
- } else {
1358
- // Delete one-time schedules after execution
1359
- this.sql`
1360
- DELETE FROM cf_agents_schedules WHERE id = ${row.id}
1361
- `;
1362
- }
1363
- }
1364
- }
1365
-
1366
- // Schedule the next alarm
1367
- await this._scheduleNextAlarm();
1368
- };
1369
-
1370
- /**
1371
- * Destroy the Agent, removing all state and scheduled tasks
1372
- */
1373
- async destroy() {
1374
- // drop all tables
1375
- this.sql`DROP TABLE IF EXISTS cf_agents_state`;
1376
- this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
1377
- this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
1378
- this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
1379
-
1380
- // delete all alarms
1381
- await this.ctx.storage.deleteAlarm();
1382
- await this.ctx.storage.deleteAll();
1383
- this._disposables.dispose();
1384
- await this.mcp.dispose?.();
1385
- this.ctx.abort("destroyed"); // enforce that the agent is evicted
1386
-
1387
- this.observability?.emit(
1388
- {
1389
- displayMessage: "Agent destroyed",
1390
- id: nanoid(),
1391
- payload: {},
1392
- timestamp: Date.now(),
1393
- type: "destroy"
1394
- },
1395
- this.ctx
1396
- );
1397
- }
1398
-
1399
- /**
1400
- * Get all methods marked as callable on this Agent
1401
- * @returns A map of method names to their metadata
1402
- */
1403
- private _isCallable(method: string): boolean {
1404
- return callableMetadata.has(this[method as keyof this] as Function);
1405
- }
1406
-
1407
- /**
1408
- * Connect to a new MCP Server
1409
- *
1410
- * @param serverName Name of the MCP server
1411
- * @param url MCP Server SSE URL
1412
- * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
1413
- * @param agentsPrefix agents routing prefix if not using `agents`
1414
- * @param options MCP client and transport options
1415
- * @returns authUrl
1416
- */
1417
- async addMcpServer(
1418
- serverName: string,
1419
- url: string,
1420
- callbackHost?: string,
1421
- agentsPrefix = "agents",
1422
- options?: {
1423
- client?: ConstructorParameters<typeof Client>[1];
1424
- transport?: {
1425
- headers?: HeadersInit;
1426
- type?: TransportType;
1427
- };
1428
- }
1429
- ): Promise<{ id: string; authUrl: string | undefined }> {
1430
- // If callbackHost is not provided, derive it from the current request
1431
- let resolvedCallbackHost = callbackHost;
1432
- if (!resolvedCallbackHost) {
1433
- const { request } = getCurrentAgent();
1434
- if (!request) {
1435
- throw new Error(
1436
- "callbackHost is required when not called within a request context"
1437
- );
1438
- }
1439
-
1440
- // Extract the origin from the request
1441
- const requestUrl = new URL(request.url);
1442
- resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
1443
- }
1444
-
1445
- const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
1446
-
1447
- // Generate a serverId upfront
1448
- const serverId = nanoid(8);
1449
-
1450
- // Persist to database BEFORE starting OAuth flow to survive DO hibernation
1451
- this.sql`
1452
- INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1453
- VALUES (
1454
- ${serverId},
1455
- ${serverName},
1456
- ${url},
1457
- ${null},
1458
- ${null},
1459
- ${callbackUrl},
1460
- ${options ? JSON.stringify(options) : null}
1461
- );
1462
- `;
1463
-
1464
- // _connectToMcpServerInternal will call mcp.connect which registers the callback URL
1465
- const result = await this._connectToMcpServerInternal(
1466
- serverName,
1467
- url,
1468
- callbackUrl,
1469
- options,
1470
- { id: serverId }
1471
- );
1472
-
1473
- // Update database with OAuth client info if auth is required
1474
- if (result.clientId || result.authUrl) {
1475
- this.sql`
1476
- UPDATE cf_agents_mcp_servers
1477
- SET client_id = ${result.clientId ?? null}, auth_url = ${result.authUrl ?? null}
1478
- WHERE id = ${serverId}
1479
- `;
1480
- }
1481
-
1482
- this.broadcastMcpServers();
1483
-
1484
- return result;
1485
- }
1486
-
1487
- /**
1488
- * Handle potential OAuth callback requests after DO hibernation.
1489
- * Detects OAuth callbacks, restores state from database, and processes the callback.
1490
- * Returns a Response if this was an OAuth callback, otherwise returns undefined.
1491
- */
1492
- private async _handlePotentialOAuthCallback(
1493
- request: Request
1494
- ): Promise<Response | undefined> {
1495
- // Quick check: must be GET with callback pattern and code parameter
1496
- if (request.method !== "GET") {
1497
- return undefined;
1498
- }
1499
-
1500
- const url = new URL(request.url);
1501
- const hasCallbackPattern =
1502
- url.pathname.includes("/callback/") && url.searchParams.has("code");
1503
-
1504
- if (!hasCallbackPattern) {
1505
- return undefined;
1506
- }
1507
-
1508
- // Extract serverId from callback URL
1509
- const pathParts = url.pathname.split("/");
1510
- const callbackIndex = pathParts.indexOf("callback");
1511
- const serverId = callbackIndex !== -1 ? pathParts[callbackIndex + 1] : null;
1512
-
1513
- if (!serverId) {
1514
- return new Response("Invalid callback URL: missing serverId", {
1515
- status: 400
1516
- });
1517
- }
1518
-
1519
- // Check if callback is already registered AND connection exists (not hibernated)
1520
- if (
1521
- this.mcp.isCallbackRequest(request) &&
1522
- this.mcp.mcpConnections[serverId]
1523
- ) {
1524
- // State already restored, handle normally
1525
- return this._processOAuthCallback(request);
1526
- }
1527
-
1528
- // Need to restore from database after hibernation
1529
- try {
1530
- const server = this.sql<MCPServerRow>`
1531
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options
1532
- FROM cf_agents_mcp_servers
1533
- WHERE id = ${serverId}
1534
- `.find((s) => s.id === serverId);
1535
-
1536
- if (!server) {
1537
- return new Response(
1538
- `OAuth callback failed: Server ${serverId} not found in database`,
1539
- { status: 404 }
1540
- );
1541
- }
1542
-
1543
- // Register callback URL (restores it after hibernation)
1544
- if (!server.callback_url) {
1545
- return new Response(
1546
- `OAuth callback failed: No callback URL stored for server ${serverId}`,
1547
- { status: 500 }
1548
- );
1549
- }
1550
-
1551
- this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);
1552
-
1553
- // Restore connection if not in memory
1554
- if (!this.mcp.mcpConnections[serverId]) {
1555
- let parsedOptions:
1556
- | {
1557
- client?: ConstructorParameters<typeof Client>[1];
1558
- transport?: {
1559
- headers?: HeadersInit;
1560
- type?: TransportType;
1561
- };
1562
- }
1563
- | undefined;
1564
- try {
1565
- parsedOptions = server.server_options
1566
- ? JSON.parse(server.server_options)
1567
- : undefined;
1568
- } catch {
1569
- return new Response(
1570
- `OAuth callback failed: Invalid server options in database for ${serverId}`,
1571
- { status: 500 }
1572
- );
1573
- }
1574
-
1575
- await this._connectToMcpServerInternal(
1576
- server.name,
1577
- server.server_url,
1578
- server.callback_url,
1579
- parsedOptions,
1580
- {
1581
- id: server.id,
1582
- oauthClientId: server.client_id ?? undefined
1583
- }
1584
- );
1585
- }
1586
-
1587
- // Now process the OAuth callback
1588
- return this._processOAuthCallback(request);
1589
- } catch (error) {
1590
- const errorMsg = error instanceof Error ? error.message : "Unknown error";
1591
- console.error(`Failed to restore MCP state for ${serverId}:`, error);
1592
- return new Response(
1593
- `OAuth callback failed during state restoration: ${errorMsg}`,
1594
- { status: 500 }
1595
- );
1596
- }
1597
- }
1598
-
1599
- /**
1600
- * Process an OAuth callback request (assumes state is already restored)
1601
- */
1602
- private async _processOAuthCallback(request: Request): Promise<Response> {
1603
- const result = await this.mcp.handleCallbackRequest(request);
1604
- this.broadcastMcpServers();
1605
-
1606
- if (result.authSuccess) {
1607
- // Start background connection if auth was successful
1608
- this.mcp
1609
- .establishConnection(result.serverId)
1610
- .catch((error) => {
1611
- console.error("Background connection failed:", error);
1612
- })
1613
- .finally(() => {
1614
- // Broadcast after background connection resolves (success/failure)
1615
- this.broadcastMcpServers();
1616
- });
1617
- }
1618
-
1619
- // Handle OAuth callback response using MCPClientManager configuration
1620
- return this.handleOAuthCallbackResponse(result, request);
1621
- }
1622
-
1623
- private async _connectToMcpServerInternal(
1624
- _serverName: string,
1625
- url: string,
1626
- callbackUrl: string,
1627
- // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
1628
- options?: {
1629
- client?: ConstructorParameters<typeof Client>[1];
1630
- /**
1631
- * We don't expose the normal set of transport options because:
1632
- * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
1633
- * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
1634
- *
1635
- * 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).
1636
- */
1637
- transport?: {
1638
- headers?: HeadersInit;
1639
- type?: TransportType;
1640
- };
1641
- },
1642
- reconnect?: {
1643
- id: string;
1644
- oauthClientId?: string;
1645
- }
1646
- ): Promise<{
1647
- id: string;
1648
- authUrl: string | undefined;
1649
- clientId: string | undefined;
1650
- }> {
1651
- const authProvider = new DurableObjectOAuthClientProvider(
1652
- this.ctx.storage,
1653
- this.name,
1654
- callbackUrl
1655
- );
1656
-
1657
- if (reconnect) {
1658
- authProvider.serverId = reconnect.id;
1659
- if (reconnect.oauthClientId) {
1660
- authProvider.clientId = reconnect.oauthClientId;
1661
- }
1662
- }
1663
-
1664
- // Use the transport type specified in options, or default to "auto"
1665
- const transportType: TransportType = options?.transport?.type ?? "auto";
1666
-
1667
- // allows passing through transport headers if necessary
1668
- // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
1669
- let headerTransportOpts: SSEClientTransportOptions = {};
1670
- if (options?.transport?.headers) {
1671
- headerTransportOpts = {
1672
- eventSourceInit: {
1673
- fetch: (url, init) =>
1674
- fetch(url, {
1675
- ...init,
1676
- headers: options?.transport?.headers
1677
- })
1678
- },
1679
- requestInit: {
1680
- headers: options?.transport?.headers
1681
- }
1682
- };
1683
- }
1684
-
1685
- const { id, authUrl, clientId } = await this.mcp.connect(url, {
1686
- client: options?.client,
1687
- reconnect,
1688
- transport: {
1689
- ...headerTransportOpts,
1690
- authProvider,
1691
- type: transportType
1692
- }
1693
- });
1694
-
1695
- return {
1696
- authUrl,
1697
- clientId,
1698
- id
1699
- };
1700
- }
1701
-
1702
- async removeMcpServer(id: string) {
1703
- this.mcp.closeConnection(id);
1704
- this.mcp.unregisterCallbackUrl(id);
1705
- this.sql`
1706
- DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1707
- `;
1708
- this.broadcastMcpServers();
1709
- }
1710
-
1711
- getMcpServers(): MCPServersState {
1712
- const mcpState: MCPServersState = {
1713
- prompts: this.mcp.listPrompts(),
1714
- resources: this.mcp.listResources(),
1715
- servers: {},
1716
- tools: this.mcp.listTools()
1717
- };
1718
-
1719
- const servers = this.sql<MCPServerRow>`
1720
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1721
- `;
1722
-
1723
- if (servers && Array.isArray(servers) && servers.length > 0) {
1724
- for (const server of servers) {
1725
- const serverConn = this.mcp.mcpConnections[server.id];
1726
- mcpState.servers[server.id] = {
1727
- auth_url: server.auth_url,
1728
- capabilities: serverConn?.serverCapabilities ?? null,
1729
- instructions: serverConn?.instructions ?? null,
1730
- name: server.name,
1731
- server_url: server.server_url,
1732
- // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1733
- state: serverConn?.connectionState ?? "authenticating"
1734
- };
1735
- }
1736
- }
1737
-
1738
- return mcpState;
1739
- }
1740
-
1741
- private broadcastMcpServers() {
1742
- this.broadcast(
1743
- JSON.stringify({
1744
- mcp: this.getMcpServers(),
1745
- type: MessageType.CF_AGENT_MCP_SERVERS
1746
- })
1747
- );
1748
- }
1749
-
1750
- /**
1751
- * Handle OAuth callback response using MCPClientManager configuration
1752
- * @param result OAuth callback result
1753
- * @param request The original request (needed for base URL)
1754
- * @returns Response for the OAuth callback
1755
- */
1756
- private handleOAuthCallbackResponse(
1757
- result: MCPClientOAuthResult,
1758
- request: Request
1759
- ): Response {
1760
- const config = this.mcp.getOAuthCallbackConfig();
1761
-
1762
- // Use custom handler if configured
1763
- if (config?.customHandler) {
1764
- return config.customHandler(result);
1765
- }
1766
-
1767
- // Use redirect URLs if configured
1768
- if (config?.successRedirect && result.authSuccess) {
1769
- return Response.redirect(config.successRedirect);
1770
- }
1771
-
1772
- if (config?.errorRedirect && !result.authSuccess) {
1773
- return Response.redirect(
1774
- `${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`
1775
- );
1776
- }
1777
-
1778
- // Default behavior - redirect to base URL
1779
- const baseUrl = new URL(request.url).origin;
1780
- return Response.redirect(baseUrl);
1781
- }
1782
- }
1783
-
1784
- // A set of classes that have been wrapped with agent context
1785
- const wrappedClasses = new Set<typeof Agent.prototype.constructor>();
1786
-
1787
- /**
1788
- * Namespace for creating Agent instances
1789
- * @template Agentic Type of the Agent class
1790
- */
1791
- export type AgentNamespace<Agentic extends Agent<unknown>> =
1792
- DurableObjectNamespace<Agentic>;
1793
-
1794
- /**
1795
- * Agent's durable context
1796
- */
1797
- export type AgentContext = DurableObjectState;
1798
-
1799
- /**
1800
- * Configuration options for Agent routing
1801
- */
1802
- export type AgentOptions<Env> = PartyServerOptions<Env> & {
1803
- /**
1804
- * Whether to enable CORS for the Agent
1805
- */
1806
- cors?: boolean | HeadersInit | undefined;
1807
- };
1808
-
1809
- /**
1810
- * Route a request to the appropriate Agent
1811
- * @param request Request to route
1812
- * @param env Environment containing Agent bindings
1813
- * @param options Routing options
1814
- * @returns Response from the Agent or undefined if no route matched
1815
- */
1816
- export async function routeAgentRequest<Env>(
1817
- request: Request,
1818
- env: Env,
1819
- options?: AgentOptions<Env>
1820
- ) {
1821
- const corsHeaders =
1822
- options?.cors === true
1823
- ? {
1824
- "Access-Control-Allow-Credentials": "true",
1825
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1826
- "Access-Control-Allow-Origin": "*",
1827
- "Access-Control-Max-Age": "86400"
1828
- }
1829
- : options?.cors;
1830
-
1831
- if (request.method === "OPTIONS") {
1832
- if (corsHeaders) {
1833
- return new Response(null, {
1834
- headers: corsHeaders
1835
- });
1836
- }
1837
- console.warn(
1838
- "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
1839
- );
1840
- }
1841
-
1842
- let response = await routePartykitRequest(
1843
- request,
1844
- env as Record<string, unknown>,
1845
- {
1846
- prefix: "agents",
1847
- ...(options as PartyServerOptions<Record<string, unknown>>)
1848
- }
1849
- );
1850
-
1851
- if (
1852
- response &&
1853
- corsHeaders &&
1854
- request.headers.get("upgrade")?.toLowerCase() !== "websocket" &&
1855
- request.headers.get("Upgrade")?.toLowerCase() !== "websocket"
1856
- ) {
1857
- response = new Response(response.body, {
1858
- headers: {
1859
- ...response.headers,
1860
- ...corsHeaders
1861
- }
1862
- });
1863
- }
1864
- return response;
1865
- }
1866
-
1867
- export type EmailResolver<Env> = (
1868
- email: ForwardableEmailMessage,
1869
- env: Env
1870
- ) => Promise<{
1871
- agentName: string;
1872
- agentId: string;
1873
- } | null>;
1874
-
1875
- /**
1876
- * Create a resolver that uses the message-id header to determine the agent to route the email to
1877
- * @returns A function that resolves the agent to route the email to
1878
- */
1879
- export function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {
1880
- return async (email: ForwardableEmailMessage, _env: Env) => {
1881
- const messageId = email.headers.get("message-id");
1882
- if (messageId) {
1883
- const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1884
- if (messageIdMatch) {
1885
- const [, agentId, domain] = messageIdMatch;
1886
- const agentName = domain.split(".")[0];
1887
- return { agentName, agentId };
1888
- }
1889
- }
1890
-
1891
- const references = email.headers.get("references");
1892
- if (references) {
1893
- const referencesMatch = references.match(
1894
- /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1895
- );
1896
- if (referencesMatch) {
1897
- const [, base64Id, domain] = referencesMatch;
1898
- const agentId = Buffer.from(base64Id, "base64").toString("hex");
1899
- const agentName = domain.split(".")[0];
1900
- return { agentName, agentId };
1901
- }
1902
- }
1903
-
1904
- const agentName = email.headers.get("x-agent-name");
1905
- const agentId = email.headers.get("x-agent-id");
1906
- if (agentName && agentId) {
1907
- return { agentName, agentId };
1908
- }
1909
-
1910
- return null;
1911
- };
1912
- }
1913
-
1914
- /**
1915
- * Create a resolver that uses the email address to determine the agent to route the email to
1916
- * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
1917
- * @returns A function that resolves the agent to route the email to
1918
- */
1919
- export function createAddressBasedEmailResolver<Env>(
1920
- defaultAgentName: string
1921
- ): EmailResolver<Env> {
1922
- return async (email: ForwardableEmailMessage, _env: Env) => {
1923
- const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1924
- if (!emailMatch) {
1925
- return null;
1926
- }
1927
-
1928
- const [, localPart, subAddress] = emailMatch;
1929
-
1930
- if (subAddress) {
1931
- return {
1932
- agentName: localPart,
1933
- agentId: subAddress
1934
- };
1935
- }
1936
-
1937
- // Option 2: Use defaultAgentName namespace, localPart as agentId
1938
- // Common for catch-all email routing to a single EmailAgent namespace
1939
- return {
1940
- agentName: defaultAgentName,
1941
- agentId: localPart
1942
- };
1943
- };
1944
- }
1945
-
1946
- /**
1947
- * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
1948
- * @param agentName The name of the agent to route the email to
1949
- * @param agentId The id of the agent to route the email to
1950
- * @returns A function that resolves the agent to route the email to
1951
- */
1952
- export function createCatchAllEmailResolver<Env>(
1953
- agentName: string,
1954
- agentId: string
1955
- ): EmailResolver<Env> {
1956
- return async () => ({ agentName, agentId });
1957
- }
1958
-
1959
- export type EmailRoutingOptions<Env> = AgentOptions<Env> & {
1960
- resolver: EmailResolver<Env>;
1961
- };
1962
-
1963
- // Cache the agent namespace map for email routing
1964
- // This maps both kebab-case and original names to namespaces
1965
- const agentMapCache = new WeakMap<
1966
- Record<string, unknown>,
1967
- Record<string, unknown>
1968
- >();
1969
-
1970
- /**
1971
- * Route an email to the appropriate Agent
1972
- * @param email The email to route
1973
- * @param env The environment containing the Agent bindings
1974
- * @param options The options for routing the email
1975
- * @returns A promise that resolves when the email has been routed
1976
- */
1977
- export async function routeAgentEmail<Env>(
1978
- email: ForwardableEmailMessage,
1979
- env: Env,
1980
- options: EmailRoutingOptions<Env>
1981
- ): Promise<void> {
1982
- const routingInfo = await options.resolver(email, env);
1983
-
1984
- if (!routingInfo) {
1985
- console.warn("No routing information found for email, dropping message");
1986
- return;
1987
- }
1988
-
1989
- // Build a map that includes both original names and kebab-case versions
1990
- if (!agentMapCache.has(env as Record<string, unknown>)) {
1991
- const map: Record<string, unknown> = {};
1992
- for (const [key, value] of Object.entries(env as Record<string, unknown>)) {
1993
- if (
1994
- value &&
1995
- typeof value === "object" &&
1996
- "idFromName" in value &&
1997
- typeof value.idFromName === "function"
1998
- ) {
1999
- // Add both the original name and kebab-case version
2000
- map[key] = value;
2001
- map[camelCaseToKebabCase(key)] = value;
2002
- }
2003
- }
2004
- agentMapCache.set(env as Record<string, unknown>, map);
2005
- }
2006
-
2007
- const agentMap = agentMapCache.get(env as Record<string, unknown>)!;
2008
- const namespace = agentMap[routingInfo.agentName];
2009
-
2010
- if (!namespace) {
2011
- // Provide helpful error message listing available agents
2012
- const availableAgents = Object.keys(agentMap)
2013
- .filter((key) => !key.includes("-")) // Show only original names, not kebab-case duplicates
2014
- .join(", ");
2015
- throw new Error(
2016
- `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
2017
- );
2018
- }
2019
-
2020
- const agent = await getAgentByName(
2021
- namespace as unknown as AgentNamespace<Agent<Env>>,
2022
- routingInfo.agentId
2023
- );
2024
-
2025
- // let's make a serialisable version of the email
2026
- const serialisableEmail: AgentEmail = {
2027
- getRaw: async () => {
2028
- const reader = email.raw.getReader();
2029
- const chunks: Uint8Array[] = [];
2030
-
2031
- let done = false;
2032
- while (!done) {
2033
- const { value, done: readerDone } = await reader.read();
2034
- done = readerDone;
2035
- if (value) {
2036
- chunks.push(value);
2037
- }
2038
- }
2039
-
2040
- const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
2041
- const combined = new Uint8Array(totalLength);
2042
- let offset = 0;
2043
- for (const chunk of chunks) {
2044
- combined.set(chunk, offset);
2045
- offset += chunk.length;
2046
- }
2047
-
2048
- return combined;
2049
- },
2050
- headers: email.headers,
2051
- rawSize: email.rawSize,
2052
- setReject: (reason: string) => {
2053
- email.setReject(reason);
2054
- },
2055
- forward: (rcptTo: string, headers?: Headers) => {
2056
- return email.forward(rcptTo, headers);
2057
- },
2058
- reply: (options: { from: string; to: string; raw: string }) => {
2059
- return email.reply(
2060
- new EmailMessage(options.from, options.to, options.raw)
2061
- );
2062
- },
2063
- from: email.from,
2064
- to: email.to
2065
- };
2066
-
2067
- await agent._onEmail(serialisableEmail);
2068
- }
2069
-
2070
- export type AgentEmail = {
2071
- from: string;
2072
- to: string;
2073
- getRaw: () => Promise<Uint8Array>;
2074
- headers: Headers;
2075
- rawSize: number;
2076
- setReject: (reason: string) => void;
2077
- forward: (rcptTo: string, headers?: Headers) => Promise<void>;
2078
- reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
2079
- };
2080
-
2081
- export type EmailSendOptions = {
2082
- to: string;
2083
- subject: string;
2084
- body: string;
2085
- contentType?: string;
2086
- headers?: Record<string, string>;
2087
- includeRoutingHeaders?: boolean;
2088
- agentName?: string;
2089
- agentId?: string;
2090
- domain?: string;
2091
- };
2092
-
2093
- /**
2094
- * Get or create an Agent by name
2095
- * @template Env Environment type containing bindings
2096
- * @template T Type of the Agent class
2097
- * @param namespace Agent namespace
2098
- * @param name Name of the Agent instance
2099
- * @param options Options for Agent creation
2100
- * @returns Promise resolving to an Agent instance stub
2101
- */
2102
- export async function getAgentByName<
2103
- Env,
2104
- T extends Agent<Env>,
2105
- Props extends Record<string, unknown> = Record<string, unknown>
2106
- >(
2107
- namespace: AgentNamespace<T>,
2108
- name: string,
2109
- options?: {
2110
- jurisdiction?: DurableObjectJurisdiction;
2111
- locationHint?: DurableObjectLocationHint;
2112
- props?: Props;
2113
- }
2114
- ) {
2115
- return getServerByName<Env, T>(namespace, name, options);
2116
- }
2117
-
2118
- /**
2119
- * A wrapper for streaming responses in callable methods
2120
- */
2121
- export class StreamingResponse {
2122
- private _connection: Connection;
2123
- private _id: string;
2124
- private _closed = false;
2125
-
2126
- constructor(connection: Connection, id: string) {
2127
- this._connection = connection;
2128
- this._id = id;
2129
- }
2130
-
2131
- /**
2132
- * Send a chunk of data to the client
2133
- * @param chunk The data to send
2134
- */
2135
- send(chunk: unknown) {
2136
- if (this._closed) {
2137
- throw new Error("StreamingResponse is already closed");
2138
- }
2139
- const response: RPCResponse = {
2140
- done: false,
2141
- id: this._id,
2142
- result: chunk,
2143
- success: true,
2144
- type: MessageType.RPC
2145
- };
2146
- this._connection.send(JSON.stringify(response));
2147
- }
2148
-
2149
- /**
2150
- * End the stream and send the final chunk (if any)
2151
- * @param finalChunk Optional final chunk of data to send
2152
- */
2153
- end(finalChunk?: unknown) {
2154
- if (this._closed) {
2155
- throw new Error("StreamingResponse is already closed");
2156
- }
2157
- this._closed = true;
2158
- const response: RPCResponse = {
2159
- done: true,
2160
- id: this._id,
2161
- result: finalChunk,
2162
- success: true,
2163
- type: MessageType.RPC
2164
- };
2165
- this._connection.send(JSON.stringify(response));
2166
- }
2167
- }