agents 0.0.0-e03246e → 0.0.0-e19fea6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +255 -27
- package/dist/_esm-LV5FJ3HK.js +3922 -0
- package/dist/_esm-LV5FJ3HK.js.map +1 -0
- package/dist/ai-chat-agent.d.ts +57 -7
- package/dist/ai-chat-agent.js +578 -94
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-chat-v5-migration.d.ts +152 -0
- package/dist/ai-chat-v5-migration.js +20 -0
- package/dist/ai-react.d.ts +78 -67
- package/dist/ai-react.js +274 -114
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types.d.ts +41 -18
- package/dist/ai-types.js +7 -0
- package/dist/ccip-CMBYN64O.js +15 -0
- package/dist/ccip-CMBYN64O.js.map +1 -0
- package/dist/chunk-254F4GDT.js +1343 -0
- package/dist/chunk-254F4GDT.js.map +1 -0
- package/dist/chunk-3OT2NNEW.js +941 -0
- package/dist/chunk-3OT2NNEW.js.map +1 -0
- package/dist/chunk-5Y6BEZDY.js +276 -0
- package/dist/chunk-5Y6BEZDY.js.map +1 -0
- package/dist/chunk-BER7KXUJ.js +18 -0
- package/dist/chunk-BER7KXUJ.js.map +1 -0
- package/dist/chunk-JJBFIGUC.js +5202 -0
- package/dist/chunk-JJBFIGUC.js.map +1 -0
- package/dist/chunk-PR4QN5HX.js +43 -0
- package/dist/chunk-PR4QN5HX.js.map +1 -0
- package/dist/chunk-QEVM4BVL.js +116 -0
- package/dist/chunk-QEVM4BVL.js.map +1 -0
- package/dist/chunk-TYAY6AU6.js +159 -0
- package/dist/chunk-TYAY6AU6.js.map +1 -0
- package/dist/chunk-UJVEAURM.js +150 -0
- package/dist/chunk-UJVEAURM.js.map +1 -0
- package/dist/chunk-Z44WASMA.js +114 -0
- package/dist/chunk-Z44WASMA.js.map +1 -0
- package/dist/client-DVoPb3-C.d.ts +5120 -0
- package/dist/client.d.ts +16 -2
- package/dist/client.js +8 -126
- package/dist/client.js.map +1 -1
- package/dist/codemode/ai.d.ts +25 -0
- package/dist/codemode/ai.js +5112 -0
- package/dist/codemode/ai.js.map +1 -0
- package/dist/index.d.ts +275 -26
- package/dist/index.js +18 -8
- package/dist/mcp/client.d.ts +12 -675
- package/dist/mcp/client.js +4 -262
- package/dist/mcp/client.js.map +1 -1
- package/dist/mcp/do-oauth-client-provider.d.ts +42 -0
- package/dist/mcp/do-oauth-client-provider.js +8 -0
- package/dist/mcp/do-oauth-client-provider.js.map +1 -0
- package/dist/mcp/index.d.ts +71 -37
- package/dist/mcp/index.js +1019 -263
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/x402.d.ts +39 -0
- package/dist/mcp/x402.js +3195 -0
- package/dist/mcp/x402.js.map +1 -0
- package/dist/mcp-BH1fJeiU.d.ts +58 -0
- package/dist/observability/index.d.ts +34 -0
- package/dist/observability/index.js +12 -0
- package/dist/observability/index.js.map +1 -0
- package/dist/react.d.ts +97 -9
- package/dist/react.js +140 -28
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +81 -7
- package/dist/schedule.js +20 -7
- package/dist/schedule.js.map +1 -1
- package/dist/secp256k1-M22GZP2U.js +2193 -0
- package/dist/secp256k1-M22GZP2U.js.map +1 -0
- package/dist/serializable.d.ts +32 -0
- package/dist/serializable.js +1 -0
- package/dist/serializable.js.map +1 -0
- package/package.json +103 -50
- package/src/index.ts +1268 -156
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-YMUU7QHV.js +0 -595
- package/dist/chunk-YMUU7QHV.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → ai-chat-v5-migration.js.map} +0 -0
package/src/index.ts
CHANGED
|
@@ -1,21 +1,36 @@
|
|
|
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";
|
|
1
15
|
import {
|
|
2
|
-
Server,
|
|
3
|
-
routePartykitRequest,
|
|
4
|
-
type PartyServerOptions,
|
|
5
|
-
getServerByName,
|
|
6
16
|
type Connection,
|
|
7
17
|
type ConnectionContext,
|
|
18
|
+
type PartyServerOptions,
|
|
19
|
+
Server,
|
|
8
20
|
type WSMessage,
|
|
21
|
+
getServerByName,
|
|
22
|
+
routePartykitRequest
|
|
9
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";
|
|
10
32
|
|
|
11
|
-
|
|
12
|
-
import { nanoid } from "nanoid";
|
|
13
|
-
|
|
14
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
15
|
-
|
|
16
|
-
export type { Connection, WSMessage, ConnectionContext } from "partyserver";
|
|
17
|
-
|
|
18
|
-
import { WorkflowEntrypoint as CFWorkflowEntrypoint } from "cloudflare:workers";
|
|
33
|
+
export type { Connection, ConnectionContext, WSMessage } from "partyserver";
|
|
19
34
|
|
|
20
35
|
/**
|
|
21
36
|
* RPC request message from client
|
|
@@ -31,7 +46,7 @@ export type RPCRequest = {
|
|
|
31
46
|
* State update message from client
|
|
32
47
|
*/
|
|
33
48
|
export type StateUpdateMessage = {
|
|
34
|
-
type:
|
|
49
|
+
type: MessageType.CF_AGENT_STATE;
|
|
35
50
|
state: unknown;
|
|
36
51
|
};
|
|
37
52
|
|
|
@@ -39,7 +54,7 @@ export type StateUpdateMessage = {
|
|
|
39
54
|
* RPC response message to client
|
|
40
55
|
*/
|
|
41
56
|
export type RPCResponse = {
|
|
42
|
-
type:
|
|
57
|
+
type: MessageType.RPC;
|
|
43
58
|
id: string;
|
|
44
59
|
} & (
|
|
45
60
|
| {
|
|
@@ -66,7 +81,7 @@ function isRPCRequest(msg: unknown): msg is RPCRequest {
|
|
|
66
81
|
typeof msg === "object" &&
|
|
67
82
|
msg !== null &&
|
|
68
83
|
"type" in msg &&
|
|
69
|
-
msg.type ===
|
|
84
|
+
msg.type === MessageType.RPC &&
|
|
70
85
|
"id" in msg &&
|
|
71
86
|
typeof msg.id === "string" &&
|
|
72
87
|
"method" in msg &&
|
|
@@ -84,7 +99,7 @@ function isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {
|
|
|
84
99
|
typeof msg === "object" &&
|
|
85
100
|
msg !== null &&
|
|
86
101
|
"type" in msg &&
|
|
87
|
-
msg.type ===
|
|
102
|
+
msg.type === MessageType.CF_AGENT_STATE &&
|
|
88
103
|
"state" in msg
|
|
89
104
|
);
|
|
90
105
|
}
|
|
@@ -99,16 +114,16 @@ export type CallableMetadata = {
|
|
|
99
114
|
streaming?: boolean;
|
|
100
115
|
};
|
|
101
116
|
|
|
102
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
103
117
|
const callableMetadata = new Map<Function, CallableMetadata>();
|
|
104
118
|
|
|
105
119
|
/**
|
|
106
120
|
* Decorator that marks a method as callable by clients
|
|
107
121
|
* @param metadata Optional metadata about the callable method
|
|
108
122
|
*/
|
|
109
|
-
export function
|
|
123
|
+
export function callable(metadata: CallableMetadata = {}) {
|
|
110
124
|
return function callableDecorator<This, Args extends unknown[], Return>(
|
|
111
125
|
target: (this: This, ...args: Args) => Return,
|
|
126
|
+
// biome-ignore lint/correctness/noUnusedFunctionParameters: later
|
|
112
127
|
context: ClassMethodDecoratorContext
|
|
113
128
|
) {
|
|
114
129
|
if (!callableMetadata.has(target)) {
|
|
@@ -119,10 +134,29 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
|
|
|
119
134
|
};
|
|
120
135
|
}
|
|
121
136
|
|
|
137
|
+
let didWarnAboutUnstableCallable = false;
|
|
138
|
+
|
|
122
139
|
/**
|
|
123
|
-
*
|
|
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
|
|
124
143
|
*/
|
|
125
|
-
export
|
|
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
|
+
};
|
|
126
160
|
|
|
127
161
|
/**
|
|
128
162
|
* Represents a scheduled task within an Agent
|
|
@@ -165,24 +199,134 @@ function getNextCronTime(cron: string) {
|
|
|
165
199
|
return interval.getNextDate();
|
|
166
200
|
}
|
|
167
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
|
+
|
|
168
246
|
const STATE_ROW_ID = "cf_state_row_id";
|
|
169
247
|
const STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
170
248
|
|
|
171
249
|
const DEFAULT_STATE = {} as unknown;
|
|
172
250
|
|
|
173
|
-
|
|
174
|
-
agent: Agent<unknown>;
|
|
251
|
+
const agentContext = new AsyncLocalStorage<{
|
|
252
|
+
agent: Agent<unknown, unknown>;
|
|
175
253
|
connection: Connection | undefined;
|
|
176
254
|
request: Request | undefined;
|
|
255
|
+
email: AgentEmail | undefined;
|
|
177
256
|
}>();
|
|
178
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
|
+
|
|
179
310
|
/**
|
|
180
311
|
* Base class for creating Agent implementations
|
|
181
312
|
* @template Env Environment type containing bindings
|
|
182
313
|
* @template State State type to store within the Agent
|
|
183
314
|
*/
|
|
184
|
-
export class Agent<
|
|
185
|
-
|
|
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
|
+
);
|
|
186
330
|
|
|
187
331
|
/**
|
|
188
332
|
* Initial state for the Agent
|
|
@@ -194,9 +338,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
194
338
|
* Current state of the Agent
|
|
195
339
|
*/
|
|
196
340
|
get state(): State {
|
|
197
|
-
if (this
|
|
341
|
+
if (this._state !== DEFAULT_STATE) {
|
|
198
342
|
// state was previously set, and populated internal state
|
|
199
|
-
return this
|
|
343
|
+
return this._state;
|
|
200
344
|
}
|
|
201
345
|
// looks like this is the first time the state is being accessed
|
|
202
346
|
// check if the state was set in a previous life
|
|
@@ -216,8 +360,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
216
360
|
) {
|
|
217
361
|
const state = result[0]?.state as string; // could be null?
|
|
218
362
|
|
|
219
|
-
this
|
|
220
|
-
return this
|
|
363
|
+
this._state = JSON.parse(state);
|
|
364
|
+
return this._state;
|
|
221
365
|
}
|
|
222
366
|
|
|
223
367
|
// ok, this is the first time the state is being accessed
|
|
@@ -238,9 +382,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
238
382
|
*/
|
|
239
383
|
static options = {
|
|
240
384
|
/** Whether the Agent should hibernate when inactive */
|
|
241
|
-
hibernate: true
|
|
385
|
+
hibernate: true // default to hibernate
|
|
242
386
|
};
|
|
243
387
|
|
|
388
|
+
/**
|
|
389
|
+
* The observability implementation to use for the Agent
|
|
390
|
+
*/
|
|
391
|
+
observability?: Observability = genericObservability;
|
|
392
|
+
|
|
244
393
|
/**
|
|
245
394
|
* Execute SQL queries against the Agent's database
|
|
246
395
|
* @template T Type of the returned rows
|
|
@@ -270,6 +419,26 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
270
419
|
constructor(ctx: AgentContext, env: Env) {
|
|
271
420
|
super(ctx, env);
|
|
272
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
|
+
|
|
273
442
|
this.sql`
|
|
274
443
|
CREATE TABLE IF NOT EXISTS cf_agents_state (
|
|
275
444
|
id TEXT PRIMARY KEY NOT NULL,
|
|
@@ -277,8 +446,17 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
277
446
|
)
|
|
278
447
|
`;
|
|
279
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
|
+
|
|
280
458
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
281
|
-
return this
|
|
459
|
+
return this._tryCatch(async () => {
|
|
282
460
|
// Create alarms table if it doesn't exist
|
|
283
461
|
this.sql`
|
|
284
462
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
@@ -298,25 +476,68 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
298
476
|
});
|
|
299
477
|
});
|
|
300
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
|
+
if (this.mcp.isCallbackRequest(request)) {
|
|
497
|
+
const result = await this.mcp.handleCallbackRequest(request);
|
|
498
|
+
this.broadcastMcpServers();
|
|
499
|
+
|
|
500
|
+
if (result.authSuccess) {
|
|
501
|
+
// Start background connection if auth was successful
|
|
502
|
+
this.mcp
|
|
503
|
+
.establishConnection(result.serverId)
|
|
504
|
+
.catch((error) => {
|
|
505
|
+
console.error("Background connection failed:", error);
|
|
506
|
+
})
|
|
507
|
+
.finally(() => {
|
|
508
|
+
// Broadcast after background connection resolves (success/failure)
|
|
509
|
+
this.broadcastMcpServers();
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// Handle OAuth callback response using MCPClientManager configuration
|
|
514
|
+
return this.handleOAuthCallbackResponse(result, request);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
return this._tryCatch(() => _onRequest(request));
|
|
518
|
+
}
|
|
519
|
+
);
|
|
520
|
+
};
|
|
521
|
+
|
|
301
522
|
const _onMessage = this.onMessage.bind(this);
|
|
302
523
|
this.onMessage = async (connection: Connection, message: WSMessage) => {
|
|
303
|
-
return
|
|
304
|
-
{ agent: this, connection, request: undefined },
|
|
524
|
+
return agentContext.run(
|
|
525
|
+
{ agent: this, connection, request: undefined, email: undefined },
|
|
305
526
|
async () => {
|
|
306
527
|
if (typeof message !== "string") {
|
|
307
|
-
return this
|
|
528
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
308
529
|
}
|
|
309
530
|
|
|
310
531
|
let parsed: unknown;
|
|
311
532
|
try {
|
|
312
533
|
parsed = JSON.parse(message);
|
|
313
|
-
} catch (
|
|
534
|
+
} catch (_e) {
|
|
314
535
|
// silently fail and let the onMessage handler handle it
|
|
315
|
-
return this
|
|
536
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
316
537
|
}
|
|
317
538
|
|
|
318
539
|
if (isStateUpdateMessage(parsed)) {
|
|
319
|
-
this
|
|
540
|
+
this._setStateInternal(parsed.state as State, connection);
|
|
320
541
|
return;
|
|
321
542
|
}
|
|
322
543
|
|
|
@@ -330,11 +551,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
330
551
|
throw new Error(`Method ${method} does not exist`);
|
|
331
552
|
}
|
|
332
553
|
|
|
333
|
-
if (!this
|
|
554
|
+
if (!this._isCallable(method)) {
|
|
334
555
|
throw new Error(`Method ${method} is not callable`);
|
|
335
556
|
}
|
|
336
557
|
|
|
337
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
338
558
|
const metadata = callableMetadata.get(methodFn as Function);
|
|
339
559
|
|
|
340
560
|
// For streaming methods, pass a StreamingResponse object
|
|
@@ -346,22 +566,37 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
346
566
|
|
|
347
567
|
// For regular methods, execute and send response
|
|
348
568
|
const result = await methodFn.apply(this, args);
|
|
569
|
+
|
|
570
|
+
this.observability?.emit(
|
|
571
|
+
{
|
|
572
|
+
displayMessage: `RPC call to ${method}`,
|
|
573
|
+
id: nanoid(),
|
|
574
|
+
payload: {
|
|
575
|
+
method,
|
|
576
|
+
streaming: metadata?.streaming
|
|
577
|
+
},
|
|
578
|
+
timestamp: Date.now(),
|
|
579
|
+
type: "rpc"
|
|
580
|
+
},
|
|
581
|
+
this.ctx
|
|
582
|
+
);
|
|
583
|
+
|
|
349
584
|
const response: RPCResponse = {
|
|
350
|
-
|
|
585
|
+
done: true,
|
|
351
586
|
id,
|
|
352
|
-
success: true,
|
|
353
587
|
result,
|
|
354
|
-
|
|
588
|
+
success: true,
|
|
589
|
+
type: MessageType.RPC
|
|
355
590
|
};
|
|
356
591
|
connection.send(JSON.stringify(response));
|
|
357
592
|
} catch (e) {
|
|
358
593
|
// Send error response
|
|
359
594
|
const response: RPCResponse = {
|
|
360
|
-
type: "rpc",
|
|
361
|
-
id: parsed.id,
|
|
362
|
-
success: false,
|
|
363
595
|
error:
|
|
364
596
|
e instanceof Error ? e.message : "Unknown error occurred",
|
|
597
|
+
id: parsed.id,
|
|
598
|
+
success: false,
|
|
599
|
+
type: MessageType.RPC
|
|
365
600
|
};
|
|
366
601
|
connection.send(JSON.stringify(response));
|
|
367
602
|
console.error("RPC error:", e);
|
|
@@ -369,7 +604,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
369
604
|
return;
|
|
370
605
|
}
|
|
371
606
|
|
|
372
|
-
return this
|
|
607
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
373
608
|
}
|
|
374
609
|
);
|
|
375
610
|
};
|
|
@@ -378,27 +613,110 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
378
613
|
this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
|
|
379
614
|
// TODO: This is a hack to ensure the state is sent after the connection is established
|
|
380
615
|
// must fix this
|
|
381
|
-
return
|
|
382
|
-
{ agent: this, connection, request: ctx.request },
|
|
616
|
+
return agentContext.run(
|
|
617
|
+
{ agent: this, connection, request: ctx.request, email: undefined },
|
|
618
|
+
() => {
|
|
619
|
+
if (this.state) {
|
|
620
|
+
connection.send(
|
|
621
|
+
JSON.stringify({
|
|
622
|
+
state: this.state,
|
|
623
|
+
type: MessageType.CF_AGENT_STATE
|
|
624
|
+
})
|
|
625
|
+
);
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
connection.send(
|
|
629
|
+
JSON.stringify({
|
|
630
|
+
mcp: this.getMcpServers(),
|
|
631
|
+
type: MessageType.CF_AGENT_MCP_SERVERS
|
|
632
|
+
})
|
|
633
|
+
);
|
|
634
|
+
|
|
635
|
+
this.observability?.emit(
|
|
636
|
+
{
|
|
637
|
+
displayMessage: "Connection established",
|
|
638
|
+
id: nanoid(),
|
|
639
|
+
payload: {
|
|
640
|
+
connectionId: connection.id
|
|
641
|
+
},
|
|
642
|
+
timestamp: Date.now(),
|
|
643
|
+
type: "connect"
|
|
644
|
+
},
|
|
645
|
+
this.ctx
|
|
646
|
+
);
|
|
647
|
+
return this._tryCatch(() => _onConnect(connection, ctx));
|
|
648
|
+
}
|
|
649
|
+
);
|
|
650
|
+
};
|
|
651
|
+
|
|
652
|
+
const _onStart = this.onStart.bind(this);
|
|
653
|
+
this.onStart = async (props?: Props) => {
|
|
654
|
+
return agentContext.run(
|
|
655
|
+
{
|
|
656
|
+
agent: this,
|
|
657
|
+
connection: undefined,
|
|
658
|
+
request: undefined,
|
|
659
|
+
email: undefined
|
|
660
|
+
},
|
|
383
661
|
async () => {
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
662
|
+
await this._tryCatch(() => {
|
|
663
|
+
const servers = this.sql<MCPServerRow>`
|
|
664
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
665
|
+
`;
|
|
666
|
+
|
|
667
|
+
this.broadcastMcpServers();
|
|
668
|
+
|
|
669
|
+
// from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
|
|
670
|
+
if (servers && Array.isArray(servers) && servers.length > 0) {
|
|
671
|
+
// Restore callback URLs for OAuth-enabled servers
|
|
672
|
+
servers.forEach((server) => {
|
|
673
|
+
if (server.callback_url) {
|
|
674
|
+
// Register the full redirect URL including serverId to avoid ambiguous matches
|
|
675
|
+
this.mcp.registerCallbackUrl(
|
|
676
|
+
`${server.callback_url}/${server.id}`
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
});
|
|
680
|
+
|
|
681
|
+
servers.forEach((server) => {
|
|
682
|
+
this._connectToMcpServerInternal(
|
|
683
|
+
server.name,
|
|
684
|
+
server.server_url,
|
|
685
|
+
server.callback_url,
|
|
686
|
+
server.server_options
|
|
687
|
+
? JSON.parse(server.server_options)
|
|
688
|
+
: undefined,
|
|
689
|
+
{
|
|
690
|
+
id: server.id,
|
|
691
|
+
oauthClientId: server.client_id ?? undefined
|
|
692
|
+
}
|
|
693
|
+
)
|
|
694
|
+
.then(() => {
|
|
695
|
+
// Broadcast updated MCP servers state after each server connects
|
|
696
|
+
this.broadcastMcpServers();
|
|
697
|
+
})
|
|
698
|
+
.catch((error) => {
|
|
699
|
+
console.error(
|
|
700
|
+
`Error connecting to MCP server: ${server.name} (${server.server_url})`,
|
|
701
|
+
error
|
|
702
|
+
);
|
|
703
|
+
// Still broadcast even if connection fails, so clients know about the failure
|
|
704
|
+
this.broadcastMcpServers();
|
|
705
|
+
});
|
|
706
|
+
});
|
|
392
707
|
}
|
|
393
|
-
return
|
|
394
|
-
}
|
|
708
|
+
return _onStart(props);
|
|
709
|
+
});
|
|
395
710
|
}
|
|
396
711
|
);
|
|
397
712
|
};
|
|
398
713
|
}
|
|
399
714
|
|
|
400
|
-
|
|
401
|
-
|
|
715
|
+
private _setStateInternal(
|
|
716
|
+
state: State,
|
|
717
|
+
source: Connection | "server" = "server"
|
|
718
|
+
) {
|
|
719
|
+
this._state = state;
|
|
402
720
|
this.sql`
|
|
403
721
|
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
404
722
|
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
@@ -409,16 +727,26 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
409
727
|
`;
|
|
410
728
|
this.broadcast(
|
|
411
729
|
JSON.stringify({
|
|
412
|
-
type: "cf_agent_state",
|
|
413
730
|
state: state,
|
|
731
|
+
type: MessageType.CF_AGENT_STATE
|
|
414
732
|
}),
|
|
415
733
|
source !== "server" ? [source.id] : []
|
|
416
734
|
);
|
|
417
|
-
return this
|
|
418
|
-
const { connection, request } =
|
|
419
|
-
return
|
|
420
|
-
{ agent: this, connection, request },
|
|
735
|
+
return this._tryCatch(() => {
|
|
736
|
+
const { connection, request, email } = agentContext.getStore() || {};
|
|
737
|
+
return agentContext.run(
|
|
738
|
+
{ agent: this, connection, request, email },
|
|
421
739
|
async () => {
|
|
740
|
+
this.observability?.emit(
|
|
741
|
+
{
|
|
742
|
+
displayMessage: "State updated",
|
|
743
|
+
id: nanoid(),
|
|
744
|
+
payload: {},
|
|
745
|
+
timestamp: Date.now(),
|
|
746
|
+
type: "state:update"
|
|
747
|
+
},
|
|
748
|
+
this.ctx
|
|
749
|
+
);
|
|
422
750
|
return this.onStateUpdate(state, source);
|
|
423
751
|
}
|
|
424
752
|
);
|
|
@@ -430,7 +758,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
430
758
|
* @param state New state to set
|
|
431
759
|
*/
|
|
432
760
|
setState(state: State) {
|
|
433
|
-
this
|
|
761
|
+
this._setStateInternal(state, "server");
|
|
434
762
|
}
|
|
435
763
|
|
|
436
764
|
/**
|
|
@@ -438,24 +766,90 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
438
766
|
* @param state Updated state
|
|
439
767
|
* @param source Source of the state update ("server" or a client connection)
|
|
440
768
|
*/
|
|
769
|
+
// biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
|
|
441
770
|
onStateUpdate(state: State | undefined, source: Connection | "server") {
|
|
442
771
|
// override this to handle state updates
|
|
443
772
|
}
|
|
444
773
|
|
|
445
774
|
/**
|
|
446
|
-
* Called when the Agent receives an email
|
|
775
|
+
* Called when the Agent receives an email via routeAgentEmail()
|
|
776
|
+
* Override this method to handle incoming emails
|
|
447
777
|
* @param email Email message to process
|
|
448
778
|
*/
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
779
|
+
async _onEmail(email: AgentEmail) {
|
|
780
|
+
// nb: we use this roundabout way of getting to onEmail
|
|
781
|
+
// because of https://github.com/cloudflare/workerd/issues/4499
|
|
782
|
+
return agentContext.run(
|
|
783
|
+
{ agent: this, connection: undefined, request: undefined, email: email },
|
|
452
784
|
async () => {
|
|
453
|
-
|
|
785
|
+
if ("onEmail" in this && typeof this.onEmail === "function") {
|
|
786
|
+
return this._tryCatch(() =>
|
|
787
|
+
(this.onEmail as (email: AgentEmail) => Promise<void>)(email)
|
|
788
|
+
);
|
|
789
|
+
} else {
|
|
790
|
+
console.log("Received email from:", email.from, "to:", email.to);
|
|
791
|
+
console.log("Subject:", email.headers.get("subject"));
|
|
792
|
+
console.log(
|
|
793
|
+
"Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
|
|
794
|
+
);
|
|
795
|
+
}
|
|
454
796
|
}
|
|
455
797
|
);
|
|
456
798
|
}
|
|
457
799
|
|
|
458
|
-
|
|
800
|
+
/**
|
|
801
|
+
* Reply to an email
|
|
802
|
+
* @param email The email to reply to
|
|
803
|
+
* @param options Options for the reply
|
|
804
|
+
* @returns void
|
|
805
|
+
*/
|
|
806
|
+
async replyToEmail(
|
|
807
|
+
email: AgentEmail,
|
|
808
|
+
options: {
|
|
809
|
+
fromName: string;
|
|
810
|
+
subject?: string | undefined;
|
|
811
|
+
body: string;
|
|
812
|
+
contentType?: string;
|
|
813
|
+
headers?: Record<string, string>;
|
|
814
|
+
}
|
|
815
|
+
): Promise<void> {
|
|
816
|
+
return this._tryCatch(async () => {
|
|
817
|
+
const agentName = camelCaseToKebabCase(this._ParentClass.name);
|
|
818
|
+
const agentId = this.name;
|
|
819
|
+
|
|
820
|
+
const { createMimeMessage } = await import("mimetext");
|
|
821
|
+
const msg = createMimeMessage();
|
|
822
|
+
msg.setSender({ addr: email.to, name: options.fromName });
|
|
823
|
+
msg.setRecipient(email.from);
|
|
824
|
+
msg.setSubject(
|
|
825
|
+
options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
|
|
826
|
+
);
|
|
827
|
+
msg.addMessage({
|
|
828
|
+
contentType: options.contentType || "text/plain",
|
|
829
|
+
data: options.body
|
|
830
|
+
});
|
|
831
|
+
|
|
832
|
+
const domain = email.from.split("@")[1];
|
|
833
|
+
const messageId = `<${agentId}@${domain}>`;
|
|
834
|
+
msg.setHeader("In-Reply-To", email.headers.get("Message-ID")!);
|
|
835
|
+
msg.setHeader("Message-ID", messageId);
|
|
836
|
+
msg.setHeader("X-Agent-Name", agentName);
|
|
837
|
+
msg.setHeader("X-Agent-ID", agentId);
|
|
838
|
+
|
|
839
|
+
if (options.headers) {
|
|
840
|
+
for (const [key, value] of Object.entries(options.headers)) {
|
|
841
|
+
msg.setHeader(key, value);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
await email.reply({
|
|
845
|
+
from: email.to,
|
|
846
|
+
raw: msg.asRaw(),
|
|
847
|
+
to: email.from
|
|
848
|
+
});
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
private async _tryCatch<T>(fn: () => T | Promise<T>) {
|
|
459
853
|
try {
|
|
460
854
|
return await fn();
|
|
461
855
|
} catch (e) {
|
|
@@ -463,6 +857,68 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
463
857
|
}
|
|
464
858
|
}
|
|
465
859
|
|
|
860
|
+
/**
|
|
861
|
+
* Automatically wrap custom methods with agent context
|
|
862
|
+
* This ensures getCurrentAgent() works in all custom methods without decorators
|
|
863
|
+
*/
|
|
864
|
+
private _autoWrapCustomMethods() {
|
|
865
|
+
// Collect all methods from base prototypes (Agent and Server)
|
|
866
|
+
const basePrototypes = [Agent.prototype, Server.prototype];
|
|
867
|
+
const baseMethods = new Set<string>();
|
|
868
|
+
for (const baseProto of basePrototypes) {
|
|
869
|
+
let proto = baseProto;
|
|
870
|
+
while (proto && proto !== Object.prototype) {
|
|
871
|
+
const methodNames = Object.getOwnPropertyNames(proto);
|
|
872
|
+
for (const methodName of methodNames) {
|
|
873
|
+
baseMethods.add(methodName);
|
|
874
|
+
}
|
|
875
|
+
proto = Object.getPrototypeOf(proto);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
// Get all methods from the current instance's prototype chain
|
|
879
|
+
let proto = Object.getPrototypeOf(this);
|
|
880
|
+
let depth = 0;
|
|
881
|
+
while (proto && proto !== Object.prototype && depth < 10) {
|
|
882
|
+
const methodNames = Object.getOwnPropertyNames(proto);
|
|
883
|
+
for (const methodName of methodNames) {
|
|
884
|
+
const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
|
|
885
|
+
|
|
886
|
+
// Skip if it's a private method, a base method, a getter, or not a function,
|
|
887
|
+
if (
|
|
888
|
+
baseMethods.has(methodName) ||
|
|
889
|
+
methodName.startsWith("_") ||
|
|
890
|
+
!descriptor ||
|
|
891
|
+
!!descriptor.get ||
|
|
892
|
+
typeof descriptor.value !== "function"
|
|
893
|
+
) {
|
|
894
|
+
continue;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
// Now, methodName is confirmed to be a custom method/function
|
|
898
|
+
// Wrap the custom method with context
|
|
899
|
+
const wrappedFunction = withAgentContext(
|
|
900
|
+
// biome-ignore lint/suspicious/noExplicitAny: I can't typescript
|
|
901
|
+
this[methodName as keyof this] as (...args: any[]) => any
|
|
902
|
+
// biome-ignore lint/suspicious/noExplicitAny: I can't typescript
|
|
903
|
+
) as any;
|
|
904
|
+
|
|
905
|
+
// if the method is callable, copy the metadata from the original method
|
|
906
|
+
if (this._isCallable(methodName)) {
|
|
907
|
+
callableMetadata.set(
|
|
908
|
+
wrappedFunction,
|
|
909
|
+
callableMetadata.get(this[methodName as keyof this] as Function)!
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
// set the wrapped function on the prototype
|
|
914
|
+
this.constructor.prototype[methodName as keyof this] = wrappedFunction;
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
proto = Object.getPrototypeOf(proto);
|
|
918
|
+
depth++;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
466
922
|
override onError(
|
|
467
923
|
connection: Connection,
|
|
468
924
|
error: unknown
|
|
@@ -497,6 +953,131 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
497
953
|
throw new Error("Not implemented");
|
|
498
954
|
}
|
|
499
955
|
|
|
956
|
+
/**
|
|
957
|
+
* Queue a task to be executed in the future
|
|
958
|
+
* @param payload Payload to pass to the callback
|
|
959
|
+
* @param callback Name of the method to call
|
|
960
|
+
* @returns The ID of the queued task
|
|
961
|
+
*/
|
|
962
|
+
async queue<T = unknown>(callback: keyof this, payload: T): Promise<string> {
|
|
963
|
+
const id = nanoid(9);
|
|
964
|
+
if (typeof callback !== "string") {
|
|
965
|
+
throw new Error("Callback must be a string");
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
if (typeof this[callback] !== "function") {
|
|
969
|
+
throw new Error(`this.${callback} is not a function`);
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
this.sql`
|
|
973
|
+
INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
|
|
974
|
+
VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
|
|
975
|
+
`;
|
|
976
|
+
|
|
977
|
+
void this._flushQueue().catch((e) => {
|
|
978
|
+
console.error("Error flushing queue:", e);
|
|
979
|
+
});
|
|
980
|
+
|
|
981
|
+
return id;
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
private _flushingQueue = false;
|
|
985
|
+
|
|
986
|
+
private async _flushQueue() {
|
|
987
|
+
if (this._flushingQueue) {
|
|
988
|
+
return;
|
|
989
|
+
}
|
|
990
|
+
this._flushingQueue = true;
|
|
991
|
+
while (true) {
|
|
992
|
+
const result = this.sql<QueueItem<string>>`
|
|
993
|
+
SELECT * FROM cf_agents_queues
|
|
994
|
+
ORDER BY created_at ASC
|
|
995
|
+
`;
|
|
996
|
+
|
|
997
|
+
if (!result || result.length === 0) {
|
|
998
|
+
break;
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
for (const row of result || []) {
|
|
1002
|
+
const callback = this[row.callback as keyof Agent<Env>];
|
|
1003
|
+
if (!callback) {
|
|
1004
|
+
console.error(`callback ${row.callback} not found`);
|
|
1005
|
+
continue;
|
|
1006
|
+
}
|
|
1007
|
+
const { connection, request, email } = agentContext.getStore() || {};
|
|
1008
|
+
await agentContext.run(
|
|
1009
|
+
{
|
|
1010
|
+
agent: this,
|
|
1011
|
+
connection,
|
|
1012
|
+
request,
|
|
1013
|
+
email
|
|
1014
|
+
},
|
|
1015
|
+
async () => {
|
|
1016
|
+
// TODO: add retries and backoff
|
|
1017
|
+
await (
|
|
1018
|
+
callback as (
|
|
1019
|
+
payload: unknown,
|
|
1020
|
+
queueItem: QueueItem<string>
|
|
1021
|
+
) => Promise<void>
|
|
1022
|
+
).bind(this)(JSON.parse(row.payload as string), row);
|
|
1023
|
+
await this.dequeue(row.id);
|
|
1024
|
+
}
|
|
1025
|
+
);
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
this._flushingQueue = false;
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
/**
|
|
1032
|
+
* Dequeue a task by ID
|
|
1033
|
+
* @param id ID of the task to dequeue
|
|
1034
|
+
*/
|
|
1035
|
+
async dequeue(id: string) {
|
|
1036
|
+
this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
/**
|
|
1040
|
+
* Dequeue all tasks
|
|
1041
|
+
*/
|
|
1042
|
+
async dequeueAll() {
|
|
1043
|
+
this.sql`DELETE FROM cf_agents_queues`;
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
/**
|
|
1047
|
+
* Dequeue all tasks by callback
|
|
1048
|
+
* @param callback Name of the callback to dequeue
|
|
1049
|
+
*/
|
|
1050
|
+
async dequeueAllByCallback(callback: string) {
|
|
1051
|
+
this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* Get a queued task by ID
|
|
1056
|
+
* @param id ID of the task to get
|
|
1057
|
+
* @returns The task or undefined if not found
|
|
1058
|
+
*/
|
|
1059
|
+
async getQueue(id: string): Promise<QueueItem<string> | undefined> {
|
|
1060
|
+
const result = this.sql<QueueItem<string>>`
|
|
1061
|
+
SELECT * FROM cf_agents_queues WHERE id = ${id}
|
|
1062
|
+
`;
|
|
1063
|
+
return result
|
|
1064
|
+
? { ...result[0], payload: JSON.parse(result[0].payload) }
|
|
1065
|
+
: undefined;
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
/**
|
|
1069
|
+
* Get all queues by key and value
|
|
1070
|
+
* @param key Key to filter by
|
|
1071
|
+
* @param value Value to filter by
|
|
1072
|
+
* @returns Array of matching QueueItem objects
|
|
1073
|
+
*/
|
|
1074
|
+
async getQueues(key: string, value: string): Promise<QueueItem<string>[]> {
|
|
1075
|
+
const result = this.sql<QueueItem<string>>`
|
|
1076
|
+
SELECT * FROM cf_agents_queues
|
|
1077
|
+
`;
|
|
1078
|
+
return result.filter((row) => JSON.parse(row.payload)[key] === value);
|
|
1079
|
+
}
|
|
1080
|
+
|
|
500
1081
|
/**
|
|
501
1082
|
* Schedule a task to be executed in the future
|
|
502
1083
|
* @template T Type of the payload data
|
|
@@ -512,6 +1093,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
512
1093
|
): Promise<Schedule<T>> {
|
|
513
1094
|
const id = nanoid(9);
|
|
514
1095
|
|
|
1096
|
+
const emitScheduleCreate = (schedule: Schedule<T>) =>
|
|
1097
|
+
this.observability?.emit(
|
|
1098
|
+
{
|
|
1099
|
+
displayMessage: `Schedule ${schedule.id} created`,
|
|
1100
|
+
id: nanoid(),
|
|
1101
|
+
payload: {
|
|
1102
|
+
callback: callback as string,
|
|
1103
|
+
id: id
|
|
1104
|
+
},
|
|
1105
|
+
timestamp: Date.now(),
|
|
1106
|
+
type: "schedule:create"
|
|
1107
|
+
},
|
|
1108
|
+
this.ctx
|
|
1109
|
+
);
|
|
1110
|
+
|
|
515
1111
|
if (typeof callback !== "string") {
|
|
516
1112
|
throw new Error("Callback must be a string");
|
|
517
1113
|
}
|
|
@@ -529,15 +1125,19 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
529
1125
|
)}, 'scheduled', ${timestamp})
|
|
530
1126
|
`;
|
|
531
1127
|
|
|
532
|
-
await this
|
|
1128
|
+
await this._scheduleNextAlarm();
|
|
533
1129
|
|
|
534
|
-
|
|
535
|
-
id,
|
|
1130
|
+
const schedule: Schedule<T> = {
|
|
536
1131
|
callback: callback,
|
|
1132
|
+
id,
|
|
537
1133
|
payload: payload as T,
|
|
538
1134
|
time: timestamp,
|
|
539
|
-
type: "scheduled"
|
|
1135
|
+
type: "scheduled"
|
|
540
1136
|
};
|
|
1137
|
+
|
|
1138
|
+
emitScheduleCreate(schedule);
|
|
1139
|
+
|
|
1140
|
+
return schedule;
|
|
541
1141
|
}
|
|
542
1142
|
if (typeof when === "number") {
|
|
543
1143
|
const time = new Date(Date.now() + when * 1000);
|
|
@@ -550,16 +1150,20 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
550
1150
|
)}, 'delayed', ${when}, ${timestamp})
|
|
551
1151
|
`;
|
|
552
1152
|
|
|
553
|
-
await this
|
|
1153
|
+
await this._scheduleNextAlarm();
|
|
554
1154
|
|
|
555
|
-
|
|
556
|
-
id,
|
|
1155
|
+
const schedule: Schedule<T> = {
|
|
557
1156
|
callback: callback,
|
|
558
|
-
payload: payload as T,
|
|
559
1157
|
delayInSeconds: when,
|
|
1158
|
+
id,
|
|
1159
|
+
payload: payload as T,
|
|
560
1160
|
time: timestamp,
|
|
561
|
-
type: "delayed"
|
|
1161
|
+
type: "delayed"
|
|
562
1162
|
};
|
|
1163
|
+
|
|
1164
|
+
emitScheduleCreate(schedule);
|
|
1165
|
+
|
|
1166
|
+
return schedule;
|
|
563
1167
|
}
|
|
564
1168
|
if (typeof when === "string") {
|
|
565
1169
|
const nextExecutionTime = getNextCronTime(when);
|
|
@@ -572,16 +1176,20 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
572
1176
|
)}, 'cron', ${when}, ${timestamp})
|
|
573
1177
|
`;
|
|
574
1178
|
|
|
575
|
-
await this
|
|
1179
|
+
await this._scheduleNextAlarm();
|
|
576
1180
|
|
|
577
|
-
|
|
578
|
-
id,
|
|
1181
|
+
const schedule: Schedule<T> = {
|
|
579
1182
|
callback: callback,
|
|
580
|
-
payload: payload as T,
|
|
581
1183
|
cron: when,
|
|
1184
|
+
id,
|
|
1185
|
+
payload: payload as T,
|
|
582
1186
|
time: timestamp,
|
|
583
|
-
type: "cron"
|
|
1187
|
+
type: "cron"
|
|
584
1188
|
};
|
|
1189
|
+
|
|
1190
|
+
emitScheduleCreate(schedule);
|
|
1191
|
+
|
|
1192
|
+
return schedule;
|
|
585
1193
|
}
|
|
586
1194
|
throw new Error("Invalid schedule type");
|
|
587
1195
|
}
|
|
@@ -645,7 +1253,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
645
1253
|
.toArray()
|
|
646
1254
|
.map((row) => ({
|
|
647
1255
|
...row,
|
|
648
|
-
payload: JSON.parse(row.payload as string) as T
|
|
1256
|
+
payload: JSON.parse(row.payload as string) as T
|
|
649
1257
|
})) as Schedule<T>[];
|
|
650
1258
|
|
|
651
1259
|
return result;
|
|
@@ -657,18 +1265,34 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
657
1265
|
* @returns true if the task was cancelled, false otherwise
|
|
658
1266
|
*/
|
|
659
1267
|
async cancelSchedule(id: string): Promise<boolean> {
|
|
1268
|
+
const schedule = await this.getSchedule(id);
|
|
1269
|
+
if (schedule) {
|
|
1270
|
+
this.observability?.emit(
|
|
1271
|
+
{
|
|
1272
|
+
displayMessage: `Schedule ${id} cancelled`,
|
|
1273
|
+
id: nanoid(),
|
|
1274
|
+
payload: {
|
|
1275
|
+
callback: schedule.callback,
|
|
1276
|
+
id: schedule.id
|
|
1277
|
+
},
|
|
1278
|
+
timestamp: Date.now(),
|
|
1279
|
+
type: "schedule:cancel"
|
|
1280
|
+
},
|
|
1281
|
+
this.ctx
|
|
1282
|
+
);
|
|
1283
|
+
}
|
|
660
1284
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
661
1285
|
|
|
662
|
-
await this
|
|
1286
|
+
await this._scheduleNextAlarm();
|
|
663
1287
|
return true;
|
|
664
1288
|
}
|
|
665
1289
|
|
|
666
|
-
async
|
|
1290
|
+
private async _scheduleNextAlarm() {
|
|
667
1291
|
// Find the next schedule that needs to be executed
|
|
668
1292
|
const result = this.sql`
|
|
669
|
-
SELECT time FROM cf_agents_schedules
|
|
1293
|
+
SELECT time FROM cf_agents_schedules
|
|
670
1294
|
WHERE time > ${Math.floor(Date.now() / 1000)}
|
|
671
|
-
ORDER BY time ASC
|
|
1295
|
+
ORDER BY time ASC
|
|
672
1296
|
LIMIT 1
|
|
673
1297
|
`;
|
|
674
1298
|
if (!result) return;
|
|
@@ -680,10 +1304,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
680
1304
|
}
|
|
681
1305
|
|
|
682
1306
|
/**
|
|
683
|
-
* Method called when an alarm fires
|
|
684
|
-
* Executes any scheduled tasks that are due
|
|
1307
|
+
* Method called when an alarm fires.
|
|
1308
|
+
* Executes any scheduled tasks that are due.
|
|
1309
|
+
*
|
|
1310
|
+
* @remarks
|
|
1311
|
+
* To schedule a task, please use the `this.schedule` method instead.
|
|
1312
|
+
* See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
|
|
685
1313
|
*/
|
|
686
|
-
async
|
|
1314
|
+
public readonly alarm = async () => {
|
|
687
1315
|
const now = Math.floor(Date.now() / 1000);
|
|
688
1316
|
|
|
689
1317
|
// Get all schedules that should be executed now
|
|
@@ -691,46 +1319,67 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
691
1319
|
SELECT * FROM cf_agents_schedules WHERE time <= ${now}
|
|
692
1320
|
`;
|
|
693
1321
|
|
|
694
|
-
|
|
695
|
-
const
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
await unstable_context.run(
|
|
701
|
-
{ agent: this, connection: undefined, request: undefined },
|
|
702
|
-
async () => {
|
|
703
|
-
try {
|
|
704
|
-
await (
|
|
705
|
-
callback as (
|
|
706
|
-
payload: unknown,
|
|
707
|
-
schedule: Schedule<unknown>
|
|
708
|
-
) => Promise<void>
|
|
709
|
-
).bind(this)(JSON.parse(row.payload as string), row);
|
|
710
|
-
} catch (e) {
|
|
711
|
-
console.error(`error executing callback "${row.callback}"`, e);
|
|
712
|
-
}
|
|
1322
|
+
if (result && Array.isArray(result)) {
|
|
1323
|
+
for (const row of result) {
|
|
1324
|
+
const callback = this[row.callback as keyof Agent<Env>];
|
|
1325
|
+
if (!callback) {
|
|
1326
|
+
console.error(`callback ${row.callback} not found`);
|
|
1327
|
+
continue;
|
|
713
1328
|
}
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
1329
|
+
await agentContext.run(
|
|
1330
|
+
{
|
|
1331
|
+
agent: this,
|
|
1332
|
+
connection: undefined,
|
|
1333
|
+
request: undefined,
|
|
1334
|
+
email: undefined
|
|
1335
|
+
},
|
|
1336
|
+
async () => {
|
|
1337
|
+
try {
|
|
1338
|
+
this.observability?.emit(
|
|
1339
|
+
{
|
|
1340
|
+
displayMessage: `Schedule ${row.id} executed`,
|
|
1341
|
+
id: nanoid(),
|
|
1342
|
+
payload: {
|
|
1343
|
+
callback: row.callback,
|
|
1344
|
+
id: row.id
|
|
1345
|
+
},
|
|
1346
|
+
timestamp: Date.now(),
|
|
1347
|
+
type: "schedule:execute"
|
|
1348
|
+
},
|
|
1349
|
+
this.ctx
|
|
1350
|
+
);
|
|
719
1351
|
|
|
720
|
-
|
|
1352
|
+
await (
|
|
1353
|
+
callback as (
|
|
1354
|
+
payload: unknown,
|
|
1355
|
+
schedule: Schedule<unknown>
|
|
1356
|
+
) => Promise<void>
|
|
1357
|
+
).bind(this)(JSON.parse(row.payload as string), row);
|
|
1358
|
+
} catch (e) {
|
|
1359
|
+
console.error(`error executing callback "${row.callback}"`, e);
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
);
|
|
1363
|
+
if (row.type === "cron") {
|
|
1364
|
+
// Update next execution time for cron schedules
|
|
1365
|
+
const nextExecutionTime = getNextCronTime(row.cron);
|
|
1366
|
+
const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
|
|
1367
|
+
|
|
1368
|
+
this.sql`
|
|
721
1369
|
UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
|
|
722
1370
|
`;
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
1371
|
+
} else {
|
|
1372
|
+
// Delete one-time schedules after execution
|
|
1373
|
+
this.sql`
|
|
726
1374
|
DELETE FROM cf_agents_schedules WHERE id = ${row.id}
|
|
727
1375
|
`;
|
|
1376
|
+
}
|
|
728
1377
|
}
|
|
729
1378
|
}
|
|
730
1379
|
|
|
731
1380
|
// Schedule the next alarm
|
|
732
|
-
await this
|
|
733
|
-
}
|
|
1381
|
+
await this._scheduleNextAlarm();
|
|
1382
|
+
};
|
|
734
1383
|
|
|
735
1384
|
/**
|
|
736
1385
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -739,22 +1388,266 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
739
1388
|
// drop all tables
|
|
740
1389
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
741
1390
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
1391
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
1392
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
|
|
742
1393
|
|
|
743
1394
|
// delete all alarms
|
|
744
1395
|
await this.ctx.storage.deleteAlarm();
|
|
745
1396
|
await this.ctx.storage.deleteAll();
|
|
1397
|
+
this._disposables.dispose();
|
|
1398
|
+
await this.mcp.dispose?.();
|
|
1399
|
+
this.ctx.abort("destroyed"); // enforce that the agent is evicted
|
|
1400
|
+
|
|
1401
|
+
this.observability?.emit(
|
|
1402
|
+
{
|
|
1403
|
+
displayMessage: "Agent destroyed",
|
|
1404
|
+
id: nanoid(),
|
|
1405
|
+
payload: {},
|
|
1406
|
+
timestamp: Date.now(),
|
|
1407
|
+
type: "destroy"
|
|
1408
|
+
},
|
|
1409
|
+
this.ctx
|
|
1410
|
+
);
|
|
746
1411
|
}
|
|
747
1412
|
|
|
748
1413
|
/**
|
|
749
1414
|
* Get all methods marked as callable on this Agent
|
|
750
1415
|
* @returns A map of method names to their metadata
|
|
751
1416
|
*/
|
|
752
|
-
|
|
753
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
1417
|
+
private _isCallable(method: string): boolean {
|
|
754
1418
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
755
1419
|
}
|
|
1420
|
+
|
|
1421
|
+
/**
|
|
1422
|
+
* Connect to a new MCP Server
|
|
1423
|
+
*
|
|
1424
|
+
* @param serverName Name of the MCP server
|
|
1425
|
+
* @param url MCP Server SSE URL
|
|
1426
|
+
* @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
|
|
1427
|
+
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
1428
|
+
* @param options MCP client and transport options
|
|
1429
|
+
* @returns authUrl
|
|
1430
|
+
*/
|
|
1431
|
+
async addMcpServer(
|
|
1432
|
+
serverName: string,
|
|
1433
|
+
url: string,
|
|
1434
|
+
callbackHost?: string,
|
|
1435
|
+
agentsPrefix = "agents",
|
|
1436
|
+
options?: {
|
|
1437
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
1438
|
+
transport?: {
|
|
1439
|
+
headers?: HeadersInit;
|
|
1440
|
+
type?: TransportType;
|
|
1441
|
+
};
|
|
1442
|
+
}
|
|
1443
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
1444
|
+
// If callbackHost is not provided, derive it from the current request
|
|
1445
|
+
let resolvedCallbackHost = callbackHost;
|
|
1446
|
+
if (!resolvedCallbackHost) {
|
|
1447
|
+
const { request } = getCurrentAgent();
|
|
1448
|
+
if (!request) {
|
|
1449
|
+
throw new Error(
|
|
1450
|
+
"callbackHost is required when not called within a request context"
|
|
1451
|
+
);
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
// Extract the origin from the request
|
|
1455
|
+
const requestUrl = new URL(request.url);
|
|
1456
|
+
resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
1460
|
+
|
|
1461
|
+
const result = await this._connectToMcpServerInternal(
|
|
1462
|
+
serverName,
|
|
1463
|
+
url,
|
|
1464
|
+
callbackUrl,
|
|
1465
|
+
options
|
|
1466
|
+
);
|
|
1467
|
+
|
|
1468
|
+
this.sql`
|
|
1469
|
+
INSERT
|
|
1470
|
+
OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
1471
|
+
VALUES (
|
|
1472
|
+
${result.id},
|
|
1473
|
+
${serverName},
|
|
1474
|
+
${url},
|
|
1475
|
+
${result.clientId ?? null},
|
|
1476
|
+
${result.authUrl ?? null},
|
|
1477
|
+
${callbackUrl},
|
|
1478
|
+
${options ? JSON.stringify(options) : null}
|
|
1479
|
+
);
|
|
1480
|
+
`;
|
|
1481
|
+
|
|
1482
|
+
this.broadcastMcpServers();
|
|
1483
|
+
|
|
1484
|
+
return result;
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
private async _connectToMcpServerInternal(
|
|
1488
|
+
_serverName: string,
|
|
1489
|
+
url: string,
|
|
1490
|
+
callbackUrl: string,
|
|
1491
|
+
// it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
|
|
1492
|
+
options?: {
|
|
1493
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
1494
|
+
/**
|
|
1495
|
+
* We don't expose the normal set of transport options because:
|
|
1496
|
+
* 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
|
|
1497
|
+
* 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
|
|
1498
|
+
*
|
|
1499
|
+
* 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).
|
|
1500
|
+
*/
|
|
1501
|
+
transport?: {
|
|
1502
|
+
headers?: HeadersInit;
|
|
1503
|
+
type?: TransportType;
|
|
1504
|
+
};
|
|
1505
|
+
},
|
|
1506
|
+
reconnect?: {
|
|
1507
|
+
id: string;
|
|
1508
|
+
oauthClientId?: string;
|
|
1509
|
+
}
|
|
1510
|
+
): Promise<{
|
|
1511
|
+
id: string;
|
|
1512
|
+
authUrl: string | undefined;
|
|
1513
|
+
clientId: string | undefined;
|
|
1514
|
+
}> {
|
|
1515
|
+
const authProvider = new DurableObjectOAuthClientProvider(
|
|
1516
|
+
this.ctx.storage,
|
|
1517
|
+
this.name,
|
|
1518
|
+
callbackUrl
|
|
1519
|
+
);
|
|
1520
|
+
|
|
1521
|
+
if (reconnect) {
|
|
1522
|
+
authProvider.serverId = reconnect.id;
|
|
1523
|
+
if (reconnect.oauthClientId) {
|
|
1524
|
+
authProvider.clientId = reconnect.oauthClientId;
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
// Use the transport type specified in options, or default to "auto"
|
|
1529
|
+
const transportType: TransportType = options?.transport?.type ?? "auto";
|
|
1530
|
+
|
|
1531
|
+
// allows passing through transport headers if necessary
|
|
1532
|
+
// this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
|
|
1533
|
+
let headerTransportOpts: SSEClientTransportOptions = {};
|
|
1534
|
+
if (options?.transport?.headers) {
|
|
1535
|
+
headerTransportOpts = {
|
|
1536
|
+
eventSourceInit: {
|
|
1537
|
+
fetch: (url, init) =>
|
|
1538
|
+
fetch(url, {
|
|
1539
|
+
...init,
|
|
1540
|
+
headers: options?.transport?.headers
|
|
1541
|
+
})
|
|
1542
|
+
},
|
|
1543
|
+
requestInit: {
|
|
1544
|
+
headers: options?.transport?.headers
|
|
1545
|
+
}
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
const { id, authUrl, clientId } = await this.mcp.connect(url, {
|
|
1550
|
+
client: options?.client,
|
|
1551
|
+
reconnect,
|
|
1552
|
+
transport: {
|
|
1553
|
+
...headerTransportOpts,
|
|
1554
|
+
authProvider,
|
|
1555
|
+
type: transportType
|
|
1556
|
+
}
|
|
1557
|
+
});
|
|
1558
|
+
|
|
1559
|
+
return {
|
|
1560
|
+
authUrl,
|
|
1561
|
+
clientId,
|
|
1562
|
+
id
|
|
1563
|
+
};
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
async removeMcpServer(id: string) {
|
|
1567
|
+
this.mcp.closeConnection(id);
|
|
1568
|
+
this.mcp.unregisterCallbackUrl(id);
|
|
1569
|
+
this.sql`
|
|
1570
|
+
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
1571
|
+
`;
|
|
1572
|
+
this.broadcastMcpServers();
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
getMcpServers(): MCPServersState {
|
|
1576
|
+
const mcpState: MCPServersState = {
|
|
1577
|
+
prompts: this.mcp.listPrompts(),
|
|
1578
|
+
resources: this.mcp.listResources(),
|
|
1579
|
+
servers: {},
|
|
1580
|
+
tools: this.mcp.listTools()
|
|
1581
|
+
};
|
|
1582
|
+
|
|
1583
|
+
const servers = this.sql<MCPServerRow>`
|
|
1584
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
1585
|
+
`;
|
|
1586
|
+
|
|
1587
|
+
if (servers && Array.isArray(servers) && servers.length > 0) {
|
|
1588
|
+
for (const server of servers) {
|
|
1589
|
+
const serverConn = this.mcp.mcpConnections[server.id];
|
|
1590
|
+
mcpState.servers[server.id] = {
|
|
1591
|
+
auth_url: server.auth_url,
|
|
1592
|
+
capabilities: serverConn?.serverCapabilities ?? null,
|
|
1593
|
+
instructions: serverConn?.instructions ?? null,
|
|
1594
|
+
name: server.name,
|
|
1595
|
+
server_url: server.server_url,
|
|
1596
|
+
// mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
|
|
1597
|
+
state: serverConn?.connectionState ?? "authenticating"
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
return mcpState;
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
private broadcastMcpServers() {
|
|
1606
|
+
this.broadcast(
|
|
1607
|
+
JSON.stringify({
|
|
1608
|
+
mcp: this.getMcpServers(),
|
|
1609
|
+
type: MessageType.CF_AGENT_MCP_SERVERS
|
|
1610
|
+
})
|
|
1611
|
+
);
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
/**
|
|
1615
|
+
* Handle OAuth callback response using MCPClientManager configuration
|
|
1616
|
+
* @param result OAuth callback result
|
|
1617
|
+
* @param request The original request (needed for base URL)
|
|
1618
|
+
* @returns Response for the OAuth callback
|
|
1619
|
+
*/
|
|
1620
|
+
private handleOAuthCallbackResponse(
|
|
1621
|
+
result: MCPClientOAuthResult,
|
|
1622
|
+
request: Request
|
|
1623
|
+
): Response {
|
|
1624
|
+
const config = this.mcp.getOAuthCallbackConfig();
|
|
1625
|
+
|
|
1626
|
+
// Use custom handler if configured
|
|
1627
|
+
if (config?.customHandler) {
|
|
1628
|
+
return config.customHandler(result);
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
// Use redirect URLs if configured
|
|
1632
|
+
if (config?.successRedirect && result.authSuccess) {
|
|
1633
|
+
return Response.redirect(config.successRedirect);
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
if (config?.errorRedirect && !result.authSuccess) {
|
|
1637
|
+
return Response.redirect(
|
|
1638
|
+
`${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`
|
|
1639
|
+
);
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
// Default behavior - redirect to base URL
|
|
1643
|
+
const baseUrl = new URL(request.url).origin;
|
|
1644
|
+
return Response.redirect(baseUrl);
|
|
1645
|
+
}
|
|
756
1646
|
}
|
|
757
1647
|
|
|
1648
|
+
// A set of classes that have been wrapped with agent context
|
|
1649
|
+
const wrappedClasses = new Set<typeof Agent.prototype.constructor>();
|
|
1650
|
+
|
|
758
1651
|
/**
|
|
759
1652
|
* Namespace for creating Agent instances
|
|
760
1653
|
* @template Agentic Type of the Agent class
|
|
@@ -792,17 +1685,17 @@ export async function routeAgentRequest<Env>(
|
|
|
792
1685
|
const corsHeaders =
|
|
793
1686
|
options?.cors === true
|
|
794
1687
|
? {
|
|
795
|
-
"Access-Control-Allow-Origin": "*",
|
|
796
|
-
"Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
|
|
797
1688
|
"Access-Control-Allow-Credentials": "true",
|
|
798
|
-
"Access-Control-
|
|
1689
|
+
"Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
|
|
1690
|
+
"Access-Control-Allow-Origin": "*",
|
|
1691
|
+
"Access-Control-Max-Age": "86400"
|
|
799
1692
|
}
|
|
800
1693
|
: options?.cors;
|
|
801
1694
|
|
|
802
1695
|
if (request.method === "OPTIONS") {
|
|
803
1696
|
if (corsHeaders) {
|
|
804
1697
|
return new Response(null, {
|
|
805
|
-
headers: corsHeaders
|
|
1698
|
+
headers: corsHeaders
|
|
806
1699
|
});
|
|
807
1700
|
}
|
|
808
1701
|
console.warn(
|
|
@@ -815,7 +1708,7 @@ export async function routeAgentRequest<Env>(
|
|
|
815
1708
|
env as Record<string, unknown>,
|
|
816
1709
|
{
|
|
817
1710
|
prefix: "agents",
|
|
818
|
-
...(options as PartyServerOptions<Record<string, unknown>>)
|
|
1711
|
+
...(options as PartyServerOptions<Record<string, unknown>>)
|
|
819
1712
|
}
|
|
820
1713
|
);
|
|
821
1714
|
|
|
@@ -828,24 +1721,238 @@ export async function routeAgentRequest<Env>(
|
|
|
828
1721
|
response = new Response(response.body, {
|
|
829
1722
|
headers: {
|
|
830
1723
|
...response.headers,
|
|
831
|
-
...corsHeaders
|
|
832
|
-
}
|
|
1724
|
+
...corsHeaders
|
|
1725
|
+
}
|
|
833
1726
|
});
|
|
834
1727
|
}
|
|
835
1728
|
return response;
|
|
836
1729
|
}
|
|
837
1730
|
|
|
1731
|
+
export type EmailResolver<Env> = (
|
|
1732
|
+
email: ForwardableEmailMessage,
|
|
1733
|
+
env: Env
|
|
1734
|
+
) => Promise<{
|
|
1735
|
+
agentName: string;
|
|
1736
|
+
agentId: string;
|
|
1737
|
+
} | null>;
|
|
1738
|
+
|
|
1739
|
+
/**
|
|
1740
|
+
* Create a resolver that uses the message-id header to determine the agent to route the email to
|
|
1741
|
+
* @returns A function that resolves the agent to route the email to
|
|
1742
|
+
*/
|
|
1743
|
+
export function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {
|
|
1744
|
+
return async (email: ForwardableEmailMessage, _env: Env) => {
|
|
1745
|
+
const messageId = email.headers.get("message-id");
|
|
1746
|
+
if (messageId) {
|
|
1747
|
+
const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
|
|
1748
|
+
if (messageIdMatch) {
|
|
1749
|
+
const [, agentId, domain] = messageIdMatch;
|
|
1750
|
+
const agentName = domain.split(".")[0];
|
|
1751
|
+
return { agentName, agentId };
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1755
|
+
const references = email.headers.get("references");
|
|
1756
|
+
if (references) {
|
|
1757
|
+
const referencesMatch = references.match(
|
|
1758
|
+
/<([A-Za-z0-9+/]{43}=)@([^>]+)>/
|
|
1759
|
+
);
|
|
1760
|
+
if (referencesMatch) {
|
|
1761
|
+
const [, base64Id, domain] = referencesMatch;
|
|
1762
|
+
const agentId = Buffer.from(base64Id, "base64").toString("hex");
|
|
1763
|
+
const agentName = domain.split(".")[0];
|
|
1764
|
+
return { agentName, agentId };
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
const agentName = email.headers.get("x-agent-name");
|
|
1769
|
+
const agentId = email.headers.get("x-agent-id");
|
|
1770
|
+
if (agentName && agentId) {
|
|
1771
|
+
return { agentName, agentId };
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
return null;
|
|
1775
|
+
};
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
/**
|
|
1779
|
+
* Create a resolver that uses the email address to determine the agent to route the email to
|
|
1780
|
+
* @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
|
|
1781
|
+
* @returns A function that resolves the agent to route the email to
|
|
1782
|
+
*/
|
|
1783
|
+
export function createAddressBasedEmailResolver<Env>(
|
|
1784
|
+
defaultAgentName: string
|
|
1785
|
+
): EmailResolver<Env> {
|
|
1786
|
+
return async (email: ForwardableEmailMessage, _env: Env) => {
|
|
1787
|
+
const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
|
|
1788
|
+
if (!emailMatch) {
|
|
1789
|
+
return null;
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
const [, localPart, subAddress] = emailMatch;
|
|
1793
|
+
|
|
1794
|
+
if (subAddress) {
|
|
1795
|
+
return {
|
|
1796
|
+
agentName: localPart,
|
|
1797
|
+
agentId: subAddress
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
// Option 2: Use defaultAgentName namespace, localPart as agentId
|
|
1802
|
+
// Common for catch-all email routing to a single EmailAgent namespace
|
|
1803
|
+
return {
|
|
1804
|
+
agentName: defaultAgentName,
|
|
1805
|
+
agentId: localPart
|
|
1806
|
+
};
|
|
1807
|
+
};
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
/**
|
|
1811
|
+
* Create a resolver that uses the agentName and agentId to determine the agent to route the email to
|
|
1812
|
+
* @param agentName The name of the agent to route the email to
|
|
1813
|
+
* @param agentId The id of the agent to route the email to
|
|
1814
|
+
* @returns A function that resolves the agent to route the email to
|
|
1815
|
+
*/
|
|
1816
|
+
export function createCatchAllEmailResolver<Env>(
|
|
1817
|
+
agentName: string,
|
|
1818
|
+
agentId: string
|
|
1819
|
+
): EmailResolver<Env> {
|
|
1820
|
+
return async () => ({ agentName, agentId });
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
export type EmailRoutingOptions<Env> = AgentOptions<Env> & {
|
|
1824
|
+
resolver: EmailResolver<Env>;
|
|
1825
|
+
};
|
|
1826
|
+
|
|
1827
|
+
// Cache the agent namespace map for email routing
|
|
1828
|
+
// This maps both kebab-case and original names to namespaces
|
|
1829
|
+
const agentMapCache = new WeakMap<
|
|
1830
|
+
Record<string, unknown>,
|
|
1831
|
+
Record<string, unknown>
|
|
1832
|
+
>();
|
|
1833
|
+
|
|
838
1834
|
/**
|
|
839
1835
|
* Route an email to the appropriate Agent
|
|
840
|
-
* @param email
|
|
841
|
-
* @param env
|
|
842
|
-
* @param options
|
|
1836
|
+
* @param email The email to route
|
|
1837
|
+
* @param env The environment containing the Agent bindings
|
|
1838
|
+
* @param options The options for routing the email
|
|
1839
|
+
* @returns A promise that resolves when the email has been routed
|
|
843
1840
|
*/
|
|
844
1841
|
export async function routeAgentEmail<Env>(
|
|
845
1842
|
email: ForwardableEmailMessage,
|
|
846
1843
|
env: Env,
|
|
847
|
-
options
|
|
848
|
-
): Promise<void> {
|
|
1844
|
+
options: EmailRoutingOptions<Env>
|
|
1845
|
+
): Promise<void> {
|
|
1846
|
+
const routingInfo = await options.resolver(email, env);
|
|
1847
|
+
|
|
1848
|
+
if (!routingInfo) {
|
|
1849
|
+
console.warn("No routing information found for email, dropping message");
|
|
1850
|
+
return;
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
// Build a map that includes both original names and kebab-case versions
|
|
1854
|
+
if (!agentMapCache.has(env as Record<string, unknown>)) {
|
|
1855
|
+
const map: Record<string, unknown> = {};
|
|
1856
|
+
for (const [key, value] of Object.entries(env as Record<string, unknown>)) {
|
|
1857
|
+
if (
|
|
1858
|
+
value &&
|
|
1859
|
+
typeof value === "object" &&
|
|
1860
|
+
"idFromName" in value &&
|
|
1861
|
+
typeof value.idFromName === "function"
|
|
1862
|
+
) {
|
|
1863
|
+
// Add both the original name and kebab-case version
|
|
1864
|
+
map[key] = value;
|
|
1865
|
+
map[camelCaseToKebabCase(key)] = value;
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
agentMapCache.set(env as Record<string, unknown>, map);
|
|
1869
|
+
}
|
|
1870
|
+
|
|
1871
|
+
const agentMap = agentMapCache.get(env as Record<string, unknown>)!;
|
|
1872
|
+
const namespace = agentMap[routingInfo.agentName];
|
|
1873
|
+
|
|
1874
|
+
if (!namespace) {
|
|
1875
|
+
// Provide helpful error message listing available agents
|
|
1876
|
+
const availableAgents = Object.keys(agentMap)
|
|
1877
|
+
.filter((key) => !key.includes("-")) // Show only original names, not kebab-case duplicates
|
|
1878
|
+
.join(", ");
|
|
1879
|
+
throw new Error(
|
|
1880
|
+
`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
|
|
1881
|
+
);
|
|
1882
|
+
}
|
|
1883
|
+
|
|
1884
|
+
const agent = await getAgentByName(
|
|
1885
|
+
namespace as unknown as AgentNamespace<Agent<Env>>,
|
|
1886
|
+
routingInfo.agentId
|
|
1887
|
+
);
|
|
1888
|
+
|
|
1889
|
+
// let's make a serialisable version of the email
|
|
1890
|
+
const serialisableEmail: AgentEmail = {
|
|
1891
|
+
getRaw: async () => {
|
|
1892
|
+
const reader = email.raw.getReader();
|
|
1893
|
+
const chunks: Uint8Array[] = [];
|
|
1894
|
+
|
|
1895
|
+
let done = false;
|
|
1896
|
+
while (!done) {
|
|
1897
|
+
const { value, done: readerDone } = await reader.read();
|
|
1898
|
+
done = readerDone;
|
|
1899
|
+
if (value) {
|
|
1900
|
+
chunks.push(value);
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
|
|
1905
|
+
const combined = new Uint8Array(totalLength);
|
|
1906
|
+
let offset = 0;
|
|
1907
|
+
for (const chunk of chunks) {
|
|
1908
|
+
combined.set(chunk, offset);
|
|
1909
|
+
offset += chunk.length;
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
return combined;
|
|
1913
|
+
},
|
|
1914
|
+
headers: email.headers,
|
|
1915
|
+
rawSize: email.rawSize,
|
|
1916
|
+
setReject: (reason: string) => {
|
|
1917
|
+
email.setReject(reason);
|
|
1918
|
+
},
|
|
1919
|
+
forward: (rcptTo: string, headers?: Headers) => {
|
|
1920
|
+
return email.forward(rcptTo, headers);
|
|
1921
|
+
},
|
|
1922
|
+
reply: (options: { from: string; to: string; raw: string }) => {
|
|
1923
|
+
return email.reply(
|
|
1924
|
+
new EmailMessage(options.from, options.to, options.raw)
|
|
1925
|
+
);
|
|
1926
|
+
},
|
|
1927
|
+
from: email.from,
|
|
1928
|
+
to: email.to
|
|
1929
|
+
};
|
|
1930
|
+
|
|
1931
|
+
await agent._onEmail(serialisableEmail);
|
|
1932
|
+
}
|
|
1933
|
+
|
|
1934
|
+
export type AgentEmail = {
|
|
1935
|
+
from: string;
|
|
1936
|
+
to: string;
|
|
1937
|
+
getRaw: () => Promise<Uint8Array>;
|
|
1938
|
+
headers: Headers;
|
|
1939
|
+
rawSize: number;
|
|
1940
|
+
setReject: (reason: string) => void;
|
|
1941
|
+
forward: (rcptTo: string, headers?: Headers) => Promise<void>;
|
|
1942
|
+
reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
|
|
1943
|
+
};
|
|
1944
|
+
|
|
1945
|
+
export type EmailSendOptions = {
|
|
1946
|
+
to: string;
|
|
1947
|
+
subject: string;
|
|
1948
|
+
body: string;
|
|
1949
|
+
contentType?: string;
|
|
1950
|
+
headers?: Record<string, string>;
|
|
1951
|
+
includeRoutingHeaders?: boolean;
|
|
1952
|
+
agentName?: string;
|
|
1953
|
+
agentId?: string;
|
|
1954
|
+
domain?: string;
|
|
1955
|
+
};
|
|
849
1956
|
|
|
850
1957
|
/**
|
|
851
1958
|
* Get or create an Agent by name
|
|
@@ -856,12 +1963,17 @@ export async function routeAgentEmail<Env>(
|
|
|
856
1963
|
* @param options Options for Agent creation
|
|
857
1964
|
* @returns Promise resolving to an Agent instance stub
|
|
858
1965
|
*/
|
|
859
|
-
export function getAgentByName<
|
|
1966
|
+
export async function getAgentByName<
|
|
1967
|
+
Env,
|
|
1968
|
+
T extends Agent<Env>,
|
|
1969
|
+
Props extends Record<string, unknown> = Record<string, unknown>
|
|
1970
|
+
>(
|
|
860
1971
|
namespace: AgentNamespace<T>,
|
|
861
1972
|
name: string,
|
|
862
1973
|
options?: {
|
|
863
1974
|
jurisdiction?: DurableObjectJurisdiction;
|
|
864
1975
|
locationHint?: DurableObjectLocationHint;
|
|
1976
|
+
props?: Props;
|
|
865
1977
|
}
|
|
866
1978
|
) {
|
|
867
1979
|
return getServerByName<Env, T>(namespace, name, options);
|
|
@@ -871,13 +1983,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
|
|
|
871
1983
|
* A wrapper for streaming responses in callable methods
|
|
872
1984
|
*/
|
|
873
1985
|
export class StreamingResponse {
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
1986
|
+
private _connection: Connection;
|
|
1987
|
+
private _id: string;
|
|
1988
|
+
private _closed = false;
|
|
877
1989
|
|
|
878
1990
|
constructor(connection: Connection, id: string) {
|
|
879
|
-
this
|
|
880
|
-
this
|
|
1991
|
+
this._connection = connection;
|
|
1992
|
+
this._id = id;
|
|
881
1993
|
}
|
|
882
1994
|
|
|
883
1995
|
/**
|
|
@@ -885,17 +1997,17 @@ export class StreamingResponse {
|
|
|
885
1997
|
* @param chunk The data to send
|
|
886
1998
|
*/
|
|
887
1999
|
send(chunk: unknown) {
|
|
888
|
-
if (this
|
|
2000
|
+
if (this._closed) {
|
|
889
2001
|
throw new Error("StreamingResponse is already closed");
|
|
890
2002
|
}
|
|
891
2003
|
const response: RPCResponse = {
|
|
892
|
-
type: "rpc",
|
|
893
|
-
id: this.#id,
|
|
894
|
-
success: true,
|
|
895
|
-
result: chunk,
|
|
896
2004
|
done: false,
|
|
2005
|
+
id: this._id,
|
|
2006
|
+
result: chunk,
|
|
2007
|
+
success: true,
|
|
2008
|
+
type: MessageType.RPC
|
|
897
2009
|
};
|
|
898
|
-
this
|
|
2010
|
+
this._connection.send(JSON.stringify(response));
|
|
899
2011
|
}
|
|
900
2012
|
|
|
901
2013
|
/**
|
|
@@ -903,17 +2015,17 @@ export class StreamingResponse {
|
|
|
903
2015
|
* @param finalChunk Optional final chunk of data to send
|
|
904
2016
|
*/
|
|
905
2017
|
end(finalChunk?: unknown) {
|
|
906
|
-
if (this
|
|
2018
|
+
if (this._closed) {
|
|
907
2019
|
throw new Error("StreamingResponse is already closed");
|
|
908
2020
|
}
|
|
909
|
-
this
|
|
2021
|
+
this._closed = true;
|
|
910
2022
|
const response: RPCResponse = {
|
|
911
|
-
type: "rpc",
|
|
912
|
-
id: this.#id,
|
|
913
|
-
success: true,
|
|
914
|
-
result: finalChunk,
|
|
915
2023
|
done: true,
|
|
2024
|
+
id: this._id,
|
|
2025
|
+
result: finalChunk,
|
|
2026
|
+
success: true,
|
|
2027
|
+
type: MessageType.RPC
|
|
916
2028
|
};
|
|
917
|
-
this
|
|
2029
|
+
this._connection.send(JSON.stringify(response));
|
|
918
2030
|
}
|
|
919
2031
|
}
|