agents 0.0.0-851f7e1 → 0.0.0-8671aae
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-chat-agent.d.ts +45 -3
- package/dist/ai-chat-agent.js +117 -55
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +13 -0
- package/dist/ai-react.js +24 -13
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types.d.ts +5 -0
- package/dist/chunk-BZXOAZUX.js +106 -0
- package/dist/chunk-BZXOAZUX.js.map +1 -0
- package/dist/chunk-OYJXQRRH.js +465 -0
- package/dist/chunk-OYJXQRRH.js.map +1 -0
- package/dist/{chunk-XG52S6YY.js → chunk-P3RZJ72N.js} +328 -136
- package/dist/chunk-P3RZJ72N.js.map +1 -0
- package/dist/chunk-VCSB47AK.js +116 -0
- package/dist/chunk-VCSB47AK.js.map +1 -0
- package/dist/client.d.ts +15 -1
- package/dist/client.js +6 -126
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +120 -11
- package/dist/index.js +8 -6
- package/dist/mcp/client.d.ts +33 -13
- package/dist/mcp/client.js +3 -402
- package/dist/mcp/client.js.map +1 -1
- package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
- package/dist/mcp/do-oauth-client-provider.js +3 -103
- package/dist/mcp/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/index.d.ts +44 -5
- package/dist/mcp/index.js +591 -158
- package/dist/mcp/index.js.map +1 -1
- package/dist/react.d.ts +85 -5
- package/dist/react.js +14 -2
- package/dist/react.js.map +1 -1
- package/dist/schedule.js +0 -2
- package/dist/schedule.js.map +1 -1
- package/dist/serializable.d.ts +32 -0
- package/dist/serializable.js +1 -0
- package/package.json +20 -5
- package/src/index.ts +394 -54
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-XG52S6YY.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → serializable.js.map} +0 -0
package/src/index.ts
CHANGED
|
@@ -1,19 +1,32 @@
|
|
|
1
1
|
import {
|
|
2
2
|
Server,
|
|
3
|
-
routePartykitRequest,
|
|
4
|
-
type PartyServerOptions,
|
|
5
3
|
getServerByName,
|
|
4
|
+
routePartykitRequest,
|
|
6
5
|
type Connection,
|
|
7
6
|
type ConnectionContext,
|
|
7
|
+
type PartyServerOptions,
|
|
8
8
|
type WSMessage,
|
|
9
9
|
} from "partyserver";
|
|
10
10
|
|
|
11
11
|
import { parseCronExpression } from "cron-schedule";
|
|
12
12
|
import { nanoid } from "nanoid";
|
|
13
13
|
|
|
14
|
+
import type {
|
|
15
|
+
Prompt,
|
|
16
|
+
Resource,
|
|
17
|
+
ServerCapabilities,
|
|
18
|
+
Tool,
|
|
19
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
14
20
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
21
|
+
import { MCPClientManager } from "./mcp/client";
|
|
22
|
+
import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
|
|
15
23
|
|
|
16
|
-
|
|
24
|
+
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
25
|
+
import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
26
|
+
|
|
27
|
+
import { camelCaseToKebabCase } from "./client";
|
|
28
|
+
|
|
29
|
+
export type { Connection, ConnectionContext, WSMessage } from "partyserver";
|
|
17
30
|
|
|
18
31
|
/**
|
|
19
32
|
* RPC request message from client
|
|
@@ -97,7 +110,6 @@ export type CallableMetadata = {
|
|
|
97
110
|
streaming?: boolean;
|
|
98
111
|
};
|
|
99
112
|
|
|
100
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
101
113
|
const callableMetadata = new Map<Function, CallableMetadata>();
|
|
102
114
|
|
|
103
115
|
/**
|
|
@@ -158,24 +170,95 @@ function getNextCronTime(cron: string) {
|
|
|
158
170
|
return interval.getNextDate();
|
|
159
171
|
}
|
|
160
172
|
|
|
173
|
+
/**
|
|
174
|
+
* MCP Server state update message from server -> Client
|
|
175
|
+
*/
|
|
176
|
+
export type MCPServerMessage = {
|
|
177
|
+
type: "cf_agent_mcp_servers";
|
|
178
|
+
mcp: MCPServersState;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
export type MCPServersState = {
|
|
182
|
+
servers: {
|
|
183
|
+
[id: string]: MCPServer;
|
|
184
|
+
};
|
|
185
|
+
tools: Tool[];
|
|
186
|
+
prompts: Prompt[];
|
|
187
|
+
resources: Resource[];
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
export type MCPServer = {
|
|
191
|
+
name: string;
|
|
192
|
+
server_url: string;
|
|
193
|
+
auth_url: string | null;
|
|
194
|
+
// This state is specifically about the temporary process of getting a token (if needed).
|
|
195
|
+
// Scope outside of that can't be relied upon because when the DO sleeps, there's no way
|
|
196
|
+
// to communicate a change to a non-ready state.
|
|
197
|
+
state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
|
|
198
|
+
instructions: string | null;
|
|
199
|
+
capabilities: ServerCapabilities | null;
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* MCP Server data stored in DO SQL for resuming MCP Server connections
|
|
204
|
+
*/
|
|
205
|
+
type MCPServerRow = {
|
|
206
|
+
id: string;
|
|
207
|
+
name: string;
|
|
208
|
+
server_url: string;
|
|
209
|
+
client_id: string | null;
|
|
210
|
+
auth_url: string | null;
|
|
211
|
+
callback_url: string;
|
|
212
|
+
server_options: string;
|
|
213
|
+
};
|
|
214
|
+
|
|
161
215
|
const STATE_ROW_ID = "cf_state_row_id";
|
|
162
216
|
const STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
163
217
|
|
|
164
218
|
const DEFAULT_STATE = {} as unknown;
|
|
165
219
|
|
|
166
|
-
|
|
220
|
+
const agentContext = new AsyncLocalStorage<{
|
|
167
221
|
agent: Agent<unknown>;
|
|
168
222
|
connection: Connection | undefined;
|
|
169
223
|
request: Request | undefined;
|
|
170
224
|
}>();
|
|
171
225
|
|
|
226
|
+
export function getCurrentAgent<
|
|
227
|
+
T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
|
|
228
|
+
>(): {
|
|
229
|
+
agent: T | undefined;
|
|
230
|
+
connection: Connection | undefined;
|
|
231
|
+
request: Request<unknown, CfProperties<unknown>> | undefined;
|
|
232
|
+
} {
|
|
233
|
+
const store = agentContext.getStore() as
|
|
234
|
+
| {
|
|
235
|
+
agent: T;
|
|
236
|
+
connection: Connection | undefined;
|
|
237
|
+
request: Request<unknown, CfProperties<unknown>> | undefined;
|
|
238
|
+
}
|
|
239
|
+
| undefined;
|
|
240
|
+
if (!store) {
|
|
241
|
+
return {
|
|
242
|
+
agent: undefined,
|
|
243
|
+
connection: undefined,
|
|
244
|
+
request: undefined,
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
return store;
|
|
248
|
+
}
|
|
249
|
+
|
|
172
250
|
/**
|
|
173
251
|
* Base class for creating Agent implementations
|
|
174
252
|
* @template Env Environment type containing bindings
|
|
175
253
|
* @template State State type to store within the Agent
|
|
176
254
|
*/
|
|
177
255
|
export class Agent<Env, State = unknown> extends Server<Env> {
|
|
178
|
-
|
|
256
|
+
private _state = DEFAULT_STATE as State;
|
|
257
|
+
|
|
258
|
+
private _ParentClass: typeof Agent<Env, State> =
|
|
259
|
+
Object.getPrototypeOf(this).constructor;
|
|
260
|
+
|
|
261
|
+
mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
179
262
|
|
|
180
263
|
/**
|
|
181
264
|
* Initial state for the Agent
|
|
@@ -187,9 +270,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
187
270
|
* Current state of the Agent
|
|
188
271
|
*/
|
|
189
272
|
get state(): State {
|
|
190
|
-
if (this
|
|
273
|
+
if (this._state !== DEFAULT_STATE) {
|
|
191
274
|
// state was previously set, and populated internal state
|
|
192
|
-
return this
|
|
275
|
+
return this._state;
|
|
193
276
|
}
|
|
194
277
|
// looks like this is the first time the state is being accessed
|
|
195
278
|
// check if the state was set in a previous life
|
|
@@ -209,8 +292,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
209
292
|
) {
|
|
210
293
|
const state = result[0]?.state as string; // could be null?
|
|
211
294
|
|
|
212
|
-
this
|
|
213
|
-
return this
|
|
295
|
+
this._state = JSON.parse(state);
|
|
296
|
+
return this._state;
|
|
214
297
|
}
|
|
215
298
|
|
|
216
299
|
// ok, this is the first time the state is being accessed
|
|
@@ -271,7 +354,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
271
354
|
`;
|
|
272
355
|
|
|
273
356
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
274
|
-
return this
|
|
357
|
+
return this._tryCatch(async () => {
|
|
275
358
|
// Create alarms table if it doesn't exist
|
|
276
359
|
this.sql`
|
|
277
360
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
@@ -291,13 +374,53 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
291
374
|
});
|
|
292
375
|
});
|
|
293
376
|
|
|
377
|
+
this.sql`
|
|
378
|
+
CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
|
|
379
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
380
|
+
name TEXT NOT NULL,
|
|
381
|
+
server_url TEXT NOT NULL,
|
|
382
|
+
callback_url TEXT NOT NULL,
|
|
383
|
+
client_id TEXT,
|
|
384
|
+
auth_url TEXT,
|
|
385
|
+
server_options TEXT
|
|
386
|
+
)
|
|
387
|
+
`;
|
|
388
|
+
|
|
389
|
+
const _onRequest = this.onRequest.bind(this);
|
|
390
|
+
this.onRequest = (request: Request) => {
|
|
391
|
+
return agentContext.run(
|
|
392
|
+
{ agent: this, connection: undefined, request },
|
|
393
|
+
async () => {
|
|
394
|
+
if (this.mcp.isCallbackRequest(request)) {
|
|
395
|
+
await this.mcp.handleCallbackRequest(request);
|
|
396
|
+
|
|
397
|
+
// after the MCP connection handshake, we can send updated mcp state
|
|
398
|
+
this.broadcast(
|
|
399
|
+
JSON.stringify({
|
|
400
|
+
type: "cf_agent_mcp_servers",
|
|
401
|
+
mcp: this.getMcpServers(),
|
|
402
|
+
})
|
|
403
|
+
);
|
|
404
|
+
|
|
405
|
+
// We probably should let the user configure this response/redirect, but this is fine for now.
|
|
406
|
+
return new Response("<script>window.close();</script>", {
|
|
407
|
+
status: 200,
|
|
408
|
+
headers: { "content-type": "text/html" },
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
return this._tryCatch(() => _onRequest(request));
|
|
413
|
+
}
|
|
414
|
+
);
|
|
415
|
+
};
|
|
416
|
+
|
|
294
417
|
const _onMessage = this.onMessage.bind(this);
|
|
295
418
|
this.onMessage = async (connection: Connection, message: WSMessage) => {
|
|
296
|
-
return
|
|
419
|
+
return agentContext.run(
|
|
297
420
|
{ agent: this, connection, request: undefined },
|
|
298
421
|
async () => {
|
|
299
422
|
if (typeof message !== "string") {
|
|
300
|
-
return this
|
|
423
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
301
424
|
}
|
|
302
425
|
|
|
303
426
|
let parsed: unknown;
|
|
@@ -305,11 +428,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
305
428
|
parsed = JSON.parse(message);
|
|
306
429
|
} catch (e) {
|
|
307
430
|
// silently fail and let the onMessage handler handle it
|
|
308
|
-
return this
|
|
431
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
309
432
|
}
|
|
310
433
|
|
|
311
434
|
if (isStateUpdateMessage(parsed)) {
|
|
312
|
-
this
|
|
435
|
+
this._setStateInternal(parsed.state as State, connection);
|
|
313
436
|
return;
|
|
314
437
|
}
|
|
315
438
|
|
|
@@ -323,11 +446,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
323
446
|
throw new Error(`Method ${method} does not exist`);
|
|
324
447
|
}
|
|
325
448
|
|
|
326
|
-
if (!this
|
|
449
|
+
if (!this._isCallable(method)) {
|
|
327
450
|
throw new Error(`Method ${method} is not callable`);
|
|
328
451
|
}
|
|
329
452
|
|
|
330
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
331
453
|
const metadata = callableMetadata.get(methodFn as Function);
|
|
332
454
|
|
|
333
455
|
// For streaming methods, pass a StreamingResponse object
|
|
@@ -362,7 +484,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
362
484
|
return;
|
|
363
485
|
}
|
|
364
486
|
|
|
365
|
-
return this
|
|
487
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
366
488
|
}
|
|
367
489
|
);
|
|
368
490
|
};
|
|
@@ -371,7 +493,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
371
493
|
this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
|
|
372
494
|
// TODO: This is a hack to ensure the state is sent after the connection is established
|
|
373
495
|
// must fix this
|
|
374
|
-
return
|
|
496
|
+
return agentContext.run(
|
|
375
497
|
{ agent: this, connection, request: ctx.request },
|
|
376
498
|
async () => {
|
|
377
499
|
setTimeout(() => {
|
|
@@ -383,15 +505,67 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
383
505
|
})
|
|
384
506
|
);
|
|
385
507
|
}
|
|
386
|
-
|
|
508
|
+
|
|
509
|
+
connection.send(
|
|
510
|
+
JSON.stringify({
|
|
511
|
+
type: "cf_agent_mcp_servers",
|
|
512
|
+
mcp: this.getMcpServers(),
|
|
513
|
+
})
|
|
514
|
+
);
|
|
515
|
+
|
|
516
|
+
return this._tryCatch(() => _onConnect(connection, ctx));
|
|
387
517
|
}, 20);
|
|
388
518
|
}
|
|
389
519
|
);
|
|
390
520
|
};
|
|
521
|
+
|
|
522
|
+
const _onStart = this.onStart.bind(this);
|
|
523
|
+
this.onStart = async () => {
|
|
524
|
+
return agentContext.run(
|
|
525
|
+
{ agent: this, connection: undefined, request: undefined },
|
|
526
|
+
async () => {
|
|
527
|
+
const servers = this.sql<MCPServerRow>`
|
|
528
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
529
|
+
`;
|
|
530
|
+
|
|
531
|
+
// from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
|
|
532
|
+
await Promise.allSettled(
|
|
533
|
+
servers
|
|
534
|
+
.filter((server) => server.auth_url === null)
|
|
535
|
+
.map((server) => {
|
|
536
|
+
return this._connectToMcpServerInternal(
|
|
537
|
+
server.name,
|
|
538
|
+
server.server_url,
|
|
539
|
+
server.callback_url,
|
|
540
|
+
server.server_options
|
|
541
|
+
? JSON.parse(server.server_options)
|
|
542
|
+
: undefined,
|
|
543
|
+
{
|
|
544
|
+
id: server.id,
|
|
545
|
+
oauthClientId: server.client_id ?? undefined,
|
|
546
|
+
}
|
|
547
|
+
);
|
|
548
|
+
})
|
|
549
|
+
);
|
|
550
|
+
|
|
551
|
+
this.broadcast(
|
|
552
|
+
JSON.stringify({
|
|
553
|
+
type: "cf_agent_mcp_servers",
|
|
554
|
+
mcp: this.getMcpServers(),
|
|
555
|
+
})
|
|
556
|
+
);
|
|
557
|
+
|
|
558
|
+
await this._tryCatch(() => _onStart());
|
|
559
|
+
}
|
|
560
|
+
);
|
|
561
|
+
};
|
|
391
562
|
}
|
|
392
563
|
|
|
393
|
-
|
|
394
|
-
|
|
564
|
+
private _setStateInternal(
|
|
565
|
+
state: State,
|
|
566
|
+
source: Connection | "server" = "server"
|
|
567
|
+
) {
|
|
568
|
+
this._state = state;
|
|
395
569
|
this.sql`
|
|
396
570
|
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
397
571
|
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
@@ -407,9 +581,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
407
581
|
}),
|
|
408
582
|
source !== "server" ? [source.id] : []
|
|
409
583
|
);
|
|
410
|
-
return this
|
|
411
|
-
const { connection, request } =
|
|
412
|
-
return
|
|
584
|
+
return this._tryCatch(() => {
|
|
585
|
+
const { connection, request } = agentContext.getStore() || {};
|
|
586
|
+
return agentContext.run(
|
|
413
587
|
{ agent: this, connection, request },
|
|
414
588
|
async () => {
|
|
415
589
|
return this.onStateUpdate(state, source);
|
|
@@ -423,7 +597,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
423
597
|
* @param state New state to set
|
|
424
598
|
*/
|
|
425
599
|
setState(state: State) {
|
|
426
|
-
this
|
|
600
|
+
this._setStateInternal(state, "server");
|
|
427
601
|
}
|
|
428
602
|
|
|
429
603
|
/**
|
|
@@ -440,7 +614,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
440
614
|
* @param email Email message to process
|
|
441
615
|
*/
|
|
442
616
|
onEmail(email: ForwardableEmailMessage) {
|
|
443
|
-
return
|
|
617
|
+
return agentContext.run(
|
|
444
618
|
{ agent: this, connection: undefined, request: undefined },
|
|
445
619
|
async () => {
|
|
446
620
|
console.error("onEmail not implemented");
|
|
@@ -448,7 +622,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
448
622
|
);
|
|
449
623
|
}
|
|
450
624
|
|
|
451
|
-
async
|
|
625
|
+
private async _tryCatch<T>(fn: () => T | Promise<T>) {
|
|
452
626
|
try {
|
|
453
627
|
return await fn();
|
|
454
628
|
} catch (e) {
|
|
@@ -522,7 +696,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
522
696
|
)}, 'scheduled', ${timestamp})
|
|
523
697
|
`;
|
|
524
698
|
|
|
525
|
-
await this
|
|
699
|
+
await this._scheduleNextAlarm();
|
|
526
700
|
|
|
527
701
|
return {
|
|
528
702
|
id,
|
|
@@ -543,7 +717,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
543
717
|
)}, 'delayed', ${when}, ${timestamp})
|
|
544
718
|
`;
|
|
545
719
|
|
|
546
|
-
await this
|
|
720
|
+
await this._scheduleNextAlarm();
|
|
547
721
|
|
|
548
722
|
return {
|
|
549
723
|
id,
|
|
@@ -565,7 +739,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
565
739
|
)}, 'cron', ${when}, ${timestamp})
|
|
566
740
|
`;
|
|
567
741
|
|
|
568
|
-
await this
|
|
742
|
+
await this._scheduleNextAlarm();
|
|
569
743
|
|
|
570
744
|
return {
|
|
571
745
|
id,
|
|
@@ -652,11 +826,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
652
826
|
async cancelSchedule(id: string): Promise<boolean> {
|
|
653
827
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
654
828
|
|
|
655
|
-
await this
|
|
829
|
+
await this._scheduleNextAlarm();
|
|
656
830
|
return true;
|
|
657
831
|
}
|
|
658
832
|
|
|
659
|
-
async
|
|
833
|
+
private async _scheduleNextAlarm() {
|
|
660
834
|
// Find the next schedule that needs to be executed
|
|
661
835
|
const result = this.sql`
|
|
662
836
|
SELECT time FROM cf_agents_schedules
|
|
@@ -673,10 +847,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
673
847
|
}
|
|
674
848
|
|
|
675
849
|
/**
|
|
676
|
-
* Method called when an alarm fires
|
|
677
|
-
* Executes any scheduled tasks that are due
|
|
850
|
+
* Method called when an alarm fires.
|
|
851
|
+
* Executes any scheduled tasks that are due.
|
|
852
|
+
*
|
|
853
|
+
* @remarks
|
|
854
|
+
* To schedule a task, please use the `this.schedule` method instead.
|
|
855
|
+
* See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
|
|
678
856
|
*/
|
|
679
|
-
async
|
|
857
|
+
public readonly alarm = async () => {
|
|
680
858
|
const now = Math.floor(Date.now() / 1000);
|
|
681
859
|
|
|
682
860
|
// Get all schedules that should be executed now
|
|
@@ -690,7 +868,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
690
868
|
console.error(`callback ${row.callback} not found`);
|
|
691
869
|
continue;
|
|
692
870
|
}
|
|
693
|
-
await
|
|
871
|
+
await agentContext.run(
|
|
694
872
|
{ agent: this, connection: undefined, request: undefined },
|
|
695
873
|
async () => {
|
|
696
874
|
try {
|
|
@@ -722,8 +900,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
722
900
|
}
|
|
723
901
|
|
|
724
902
|
// Schedule the next alarm
|
|
725
|
-
await this
|
|
726
|
-
}
|
|
903
|
+
await this._scheduleNextAlarm();
|
|
904
|
+
};
|
|
727
905
|
|
|
728
906
|
/**
|
|
729
907
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -732,6 +910,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
732
910
|
// drop all tables
|
|
733
911
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
734
912
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
913
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
735
914
|
|
|
736
915
|
// delete all alarms
|
|
737
916
|
await this.ctx.storage.deleteAlarm();
|
|
@@ -742,10 +921,171 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
742
921
|
* Get all methods marked as callable on this Agent
|
|
743
922
|
* @returns A map of method names to their metadata
|
|
744
923
|
*/
|
|
745
|
-
|
|
746
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
924
|
+
private _isCallable(method: string): boolean {
|
|
747
925
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
748
926
|
}
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* Connect to a new MCP Server
|
|
930
|
+
*
|
|
931
|
+
* @param url MCP Server SSE URL
|
|
932
|
+
* @param callbackHost Base host for the agent, used for the redirect URI.
|
|
933
|
+
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
934
|
+
* @param options MCP client and transport (header) options
|
|
935
|
+
* @returns authUrl
|
|
936
|
+
*/
|
|
937
|
+
async addMcpServer(
|
|
938
|
+
serverName: string,
|
|
939
|
+
url: string,
|
|
940
|
+
callbackHost: string,
|
|
941
|
+
agentsPrefix = "agents",
|
|
942
|
+
options?: {
|
|
943
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
944
|
+
transport?: {
|
|
945
|
+
headers: HeadersInit;
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
949
|
+
const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
950
|
+
|
|
951
|
+
const result = await this._connectToMcpServerInternal(
|
|
952
|
+
serverName,
|
|
953
|
+
url,
|
|
954
|
+
callbackUrl,
|
|
955
|
+
options
|
|
956
|
+
);
|
|
957
|
+
|
|
958
|
+
this.broadcast(
|
|
959
|
+
JSON.stringify({
|
|
960
|
+
type: "cf_agent_mcp_servers",
|
|
961
|
+
mcp: this.getMcpServers(),
|
|
962
|
+
})
|
|
963
|
+
);
|
|
964
|
+
|
|
965
|
+
return result;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
async _connectToMcpServerInternal(
|
|
969
|
+
serverName: string,
|
|
970
|
+
url: string,
|
|
971
|
+
callbackUrl: string,
|
|
972
|
+
// it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
|
|
973
|
+
options?: {
|
|
974
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
975
|
+
/**
|
|
976
|
+
* We don't expose the normal set of transport options because:
|
|
977
|
+
* 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
|
|
978
|
+
* 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
|
|
979
|
+
*
|
|
980
|
+
* This has the limitation that you can't override fetch, but I think headers should handle nearly all cases needed (i.e. non-standard bearer auth).
|
|
981
|
+
*/
|
|
982
|
+
transport?: {
|
|
983
|
+
headers?: HeadersInit;
|
|
984
|
+
};
|
|
985
|
+
},
|
|
986
|
+
reconnect?: {
|
|
987
|
+
id: string;
|
|
988
|
+
oauthClientId?: string;
|
|
989
|
+
}
|
|
990
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
991
|
+
const authProvider = new DurableObjectOAuthClientProvider(
|
|
992
|
+
this.ctx.storage,
|
|
993
|
+
this.name,
|
|
994
|
+
callbackUrl
|
|
995
|
+
);
|
|
996
|
+
|
|
997
|
+
if (reconnect) {
|
|
998
|
+
authProvider.serverId = reconnect.id;
|
|
999
|
+
if (reconnect.oauthClientId) {
|
|
1000
|
+
authProvider.clientId = reconnect.oauthClientId;
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
// allows passing through transport headers if necessary
|
|
1005
|
+
// this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
|
|
1006
|
+
let headerTransportOpts: SSEClientTransportOptions = {};
|
|
1007
|
+
if (options?.transport?.headers) {
|
|
1008
|
+
headerTransportOpts = {
|
|
1009
|
+
eventSourceInit: {
|
|
1010
|
+
fetch: (url, init) =>
|
|
1011
|
+
fetch(url, {
|
|
1012
|
+
...init,
|
|
1013
|
+
headers: options?.transport?.headers,
|
|
1014
|
+
}),
|
|
1015
|
+
},
|
|
1016
|
+
requestInit: {
|
|
1017
|
+
headers: options?.transport?.headers,
|
|
1018
|
+
},
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
const { id, authUrl, clientId } = await this.mcp.connect(url, {
|
|
1023
|
+
reconnect,
|
|
1024
|
+
transport: {
|
|
1025
|
+
...headerTransportOpts,
|
|
1026
|
+
authProvider,
|
|
1027
|
+
},
|
|
1028
|
+
client: options?.client,
|
|
1029
|
+
});
|
|
1030
|
+
|
|
1031
|
+
this.sql`
|
|
1032
|
+
INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
1033
|
+
VALUES (
|
|
1034
|
+
${id},
|
|
1035
|
+
${serverName},
|
|
1036
|
+
${url},
|
|
1037
|
+
${clientId ?? null},
|
|
1038
|
+
${authUrl ?? null},
|
|
1039
|
+
${callbackUrl},
|
|
1040
|
+
${options ? JSON.stringify(options) : null}
|
|
1041
|
+
);
|
|
1042
|
+
`;
|
|
1043
|
+
|
|
1044
|
+
return {
|
|
1045
|
+
id,
|
|
1046
|
+
authUrl,
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
async removeMcpServer(id: string) {
|
|
1051
|
+
this.mcp.closeConnection(id);
|
|
1052
|
+
this.sql`
|
|
1053
|
+
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
1054
|
+
`;
|
|
1055
|
+
this.broadcast(
|
|
1056
|
+
JSON.stringify({
|
|
1057
|
+
type: "cf_agent_mcp_servers",
|
|
1058
|
+
mcp: this.getMcpServers(),
|
|
1059
|
+
})
|
|
1060
|
+
);
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
getMcpServers(): MCPServersState {
|
|
1064
|
+
const mcpState: MCPServersState = {
|
|
1065
|
+
servers: {},
|
|
1066
|
+
tools: this.mcp.listTools(),
|
|
1067
|
+
prompts: this.mcp.listPrompts(),
|
|
1068
|
+
resources: this.mcp.listResources(),
|
|
1069
|
+
};
|
|
1070
|
+
|
|
1071
|
+
const servers = this.sql<MCPServerRow>`
|
|
1072
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
1073
|
+
`;
|
|
1074
|
+
|
|
1075
|
+
for (const server of servers) {
|
|
1076
|
+
mcpState.servers[server.id] = {
|
|
1077
|
+
name: server.name,
|
|
1078
|
+
server_url: server.server_url,
|
|
1079
|
+
auth_url: server.auth_url,
|
|
1080
|
+
state: this.mcp.mcpConnections[server.id].connectionState,
|
|
1081
|
+
instructions: this.mcp.mcpConnections[server.id].instructions ?? null,
|
|
1082
|
+
capabilities:
|
|
1083
|
+
this.mcp.mcpConnections[server.id].serverCapabilities ?? null,
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
return mcpState;
|
|
1088
|
+
}
|
|
749
1089
|
}
|
|
750
1090
|
|
|
751
1091
|
/**
|
|
@@ -849,7 +1189,7 @@ export async function routeAgentEmail<Env>(
|
|
|
849
1189
|
* @param options Options for Agent creation
|
|
850
1190
|
* @returns Promise resolving to an Agent instance stub
|
|
851
1191
|
*/
|
|
852
|
-
export function getAgentByName<Env, T extends Agent<Env>>(
|
|
1192
|
+
export async function getAgentByName<Env, T extends Agent<Env>>(
|
|
853
1193
|
namespace: AgentNamespace<T>,
|
|
854
1194
|
name: string,
|
|
855
1195
|
options?: {
|
|
@@ -864,13 +1204,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
|
|
|
864
1204
|
* A wrapper for streaming responses in callable methods
|
|
865
1205
|
*/
|
|
866
1206
|
export class StreamingResponse {
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
1207
|
+
private _connection: Connection;
|
|
1208
|
+
private _id: string;
|
|
1209
|
+
private _closed = false;
|
|
870
1210
|
|
|
871
1211
|
constructor(connection: Connection, id: string) {
|
|
872
|
-
this
|
|
873
|
-
this
|
|
1212
|
+
this._connection = connection;
|
|
1213
|
+
this._id = id;
|
|
874
1214
|
}
|
|
875
1215
|
|
|
876
1216
|
/**
|
|
@@ -878,17 +1218,17 @@ export class StreamingResponse {
|
|
|
878
1218
|
* @param chunk The data to send
|
|
879
1219
|
*/
|
|
880
1220
|
send(chunk: unknown) {
|
|
881
|
-
if (this
|
|
1221
|
+
if (this._closed) {
|
|
882
1222
|
throw new Error("StreamingResponse is already closed");
|
|
883
1223
|
}
|
|
884
1224
|
const response: RPCResponse = {
|
|
885
1225
|
type: "rpc",
|
|
886
|
-
id: this
|
|
1226
|
+
id: this._id,
|
|
887
1227
|
success: true,
|
|
888
1228
|
result: chunk,
|
|
889
1229
|
done: false,
|
|
890
1230
|
};
|
|
891
|
-
this
|
|
1231
|
+
this._connection.send(JSON.stringify(response));
|
|
892
1232
|
}
|
|
893
1233
|
|
|
894
1234
|
/**
|
|
@@ -896,17 +1236,17 @@ export class StreamingResponse {
|
|
|
896
1236
|
* @param finalChunk Optional final chunk of data to send
|
|
897
1237
|
*/
|
|
898
1238
|
end(finalChunk?: unknown) {
|
|
899
|
-
if (this
|
|
1239
|
+
if (this._closed) {
|
|
900
1240
|
throw new Error("StreamingResponse is already closed");
|
|
901
1241
|
}
|
|
902
|
-
this
|
|
1242
|
+
this._closed = true;
|
|
903
1243
|
const response: RPCResponse = {
|
|
904
1244
|
type: "rpc",
|
|
905
|
-
id: this
|
|
1245
|
+
id: this._id,
|
|
906
1246
|
success: true,
|
|
907
1247
|
result: finalChunk,
|
|
908
1248
|
done: true,
|
|
909
1249
|
};
|
|
910
|
-
this
|
|
1250
|
+
this._connection.send(JSON.stringify(response));
|
|
911
1251
|
}
|
|
912
1252
|
}
|