agents 0.0.0-07086ea → 0.0.0-0ac89c6
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 +27 -2
- package/dist/ai-chat-agent.js +99 -103
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +12 -0
- package/dist/ai-react.js +1 -2
- package/dist/ai-react.js.map +1 -1
- package/dist/{chunk-ZRZEISHY.js → chunk-4ARKO5R4.js} +322 -138
- package/dist/chunk-4ARKO5R4.js.map +1 -0
- package/dist/chunk-BZXOAZUX.js +106 -0
- package/dist/chunk-BZXOAZUX.js.map +1 -0
- package/dist/chunk-QSGN3REV.js +123 -0
- package/dist/chunk-QSGN3REV.js.map +1 -0
- package/dist/{chunk-WNICV3OI.js → chunk-Y67CHZBI.js} +53 -25
- package/dist/chunk-Y67CHZBI.js.map +1 -0
- package/dist/client.d.ts +9 -1
- package/dist/client.js +6 -126
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +104 -13
- package/dist/index.js +8 -7
- package/dist/mcp/client.d.ts +30 -15
- package/dist/mcp/client.js +1 -2
- package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
- package/dist/mcp/do-oauth-client-provider.js +3 -103
- package/dist/mcp/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/index.d.ts +14 -4
- package/dist/mcp/index.js +106 -135
- package/dist/mcp/index.js.map +1 -1
- package/dist/react.d.ts +62 -0
- package/dist/react.js +4 -2
- package/dist/react.js.map +1 -1
- package/dist/schedule.js +0 -2
- package/dist/schedule.js.map +1 -1
- package/package.json +12 -8
- package/src/index.ts +379 -53
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-HMLY7DHA.js.map +0 -1
- package/dist/chunk-WNICV3OI.js.map +0 -1
- package/dist/chunk-ZRZEISHY.js.map +0 -1
package/src/index.ts
CHANGED
|
@@ -13,6 +13,20 @@ import { nanoid } from "nanoid";
|
|
|
13
13
|
|
|
14
14
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
15
15
|
import { MCPClientManager } from "./mcp/client";
|
|
16
|
+
import {
|
|
17
|
+
DurableObjectOAuthClientProvider,
|
|
18
|
+
type AgentsOAuthProvider,
|
|
19
|
+
} from "./mcp/do-oauth-client-provider";
|
|
20
|
+
import type {
|
|
21
|
+
Tool,
|
|
22
|
+
Resource,
|
|
23
|
+
Prompt,
|
|
24
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
25
|
+
|
|
26
|
+
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
27
|
+
import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
28
|
+
|
|
29
|
+
import { camelCaseToKebabCase } from "./client";
|
|
16
30
|
|
|
17
31
|
export type { Connection, WSMessage, ConnectionContext } from "partyserver";
|
|
18
32
|
|
|
@@ -98,7 +112,6 @@ export type CallableMetadata = {
|
|
|
98
112
|
streaming?: boolean;
|
|
99
113
|
};
|
|
100
114
|
|
|
101
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
102
115
|
const callableMetadata = new Map<Function, CallableMetadata>();
|
|
103
116
|
|
|
104
117
|
/**
|
|
@@ -159,29 +172,90 @@ function getNextCronTime(cron: string) {
|
|
|
159
172
|
return interval.getNextDate();
|
|
160
173
|
}
|
|
161
174
|
|
|
175
|
+
/**
|
|
176
|
+
* MCP Server state update message from server -> Client
|
|
177
|
+
*/
|
|
178
|
+
export type MCPServerMessage = {
|
|
179
|
+
type: "cf_agent_mcp_servers";
|
|
180
|
+
mcp: MCPServersState;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
export type MCPServersState = {
|
|
184
|
+
servers: {
|
|
185
|
+
[id: string]: MCPServer;
|
|
186
|
+
};
|
|
187
|
+
tools: Tool[];
|
|
188
|
+
prompts: Prompt[];
|
|
189
|
+
resources: Resource[];
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
export type MCPServer = {
|
|
193
|
+
name: string;
|
|
194
|
+
server_url: string;
|
|
195
|
+
auth_url: string | null;
|
|
196
|
+
state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* MCP Server data stored in DO SQL for resuming MCP Server connections
|
|
201
|
+
*/
|
|
202
|
+
type MCPServerRow = {
|
|
203
|
+
id: string;
|
|
204
|
+
name: string;
|
|
205
|
+
server_url: string;
|
|
206
|
+
client_id: string | null;
|
|
207
|
+
auth_url: string | null;
|
|
208
|
+
callback_url: string;
|
|
209
|
+
server_options: string;
|
|
210
|
+
};
|
|
211
|
+
|
|
162
212
|
const STATE_ROW_ID = "cf_state_row_id";
|
|
163
213
|
const STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
164
214
|
|
|
165
215
|
const DEFAULT_STATE = {} as unknown;
|
|
166
216
|
|
|
167
|
-
|
|
217
|
+
const agentContext = new AsyncLocalStorage<{
|
|
168
218
|
agent: Agent<unknown>;
|
|
169
219
|
connection: Connection | undefined;
|
|
170
220
|
request: Request | undefined;
|
|
171
221
|
}>();
|
|
172
222
|
|
|
223
|
+
export function getCurrentAgent<
|
|
224
|
+
T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
|
|
225
|
+
>(): {
|
|
226
|
+
agent: T | undefined;
|
|
227
|
+
connection: Connection | undefined;
|
|
228
|
+
request: Request<unknown, CfProperties<unknown>> | undefined;
|
|
229
|
+
} {
|
|
230
|
+
const store = agentContext.getStore() as
|
|
231
|
+
| {
|
|
232
|
+
agent: T;
|
|
233
|
+
connection: Connection | undefined;
|
|
234
|
+
request: Request<unknown, CfProperties<unknown>> | undefined;
|
|
235
|
+
}
|
|
236
|
+
| undefined;
|
|
237
|
+
if (!store) {
|
|
238
|
+
return {
|
|
239
|
+
agent: undefined,
|
|
240
|
+
connection: undefined,
|
|
241
|
+
request: undefined,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
return store;
|
|
245
|
+
}
|
|
246
|
+
|
|
173
247
|
/**
|
|
174
248
|
* Base class for creating Agent implementations
|
|
175
249
|
* @template Env Environment type containing bindings
|
|
176
250
|
* @template State State type to store within the Agent
|
|
177
251
|
*/
|
|
178
252
|
export class Agent<Env, State = unknown> extends Server<Env> {
|
|
179
|
-
|
|
253
|
+
private _state = DEFAULT_STATE as State;
|
|
180
254
|
|
|
181
|
-
|
|
255
|
+
private _ParentClass: typeof Agent<Env, State> =
|
|
182
256
|
Object.getPrototypeOf(this).constructor;
|
|
183
257
|
|
|
184
|
-
mcp: MCPClientManager = new MCPClientManager(this
|
|
258
|
+
mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
185
259
|
|
|
186
260
|
/**
|
|
187
261
|
* Initial state for the Agent
|
|
@@ -193,9 +267,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
193
267
|
* Current state of the Agent
|
|
194
268
|
*/
|
|
195
269
|
get state(): State {
|
|
196
|
-
if (this
|
|
270
|
+
if (this._state !== DEFAULT_STATE) {
|
|
197
271
|
// state was previously set, and populated internal state
|
|
198
|
-
return this
|
|
272
|
+
return this._state;
|
|
199
273
|
}
|
|
200
274
|
// looks like this is the first time the state is being accessed
|
|
201
275
|
// check if the state was set in a previous life
|
|
@@ -215,8 +289,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
215
289
|
) {
|
|
216
290
|
const state = result[0]?.state as string; // could be null?
|
|
217
291
|
|
|
218
|
-
this
|
|
219
|
-
return this
|
|
292
|
+
this._state = JSON.parse(state);
|
|
293
|
+
return this._state;
|
|
220
294
|
}
|
|
221
295
|
|
|
222
296
|
// ok, this is the first time the state is being accessed
|
|
@@ -277,7 +351,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
277
351
|
`;
|
|
278
352
|
|
|
279
353
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
280
|
-
return this
|
|
354
|
+
return this._tryCatch(async () => {
|
|
281
355
|
// Create alarms table if it doesn't exist
|
|
282
356
|
this.sql`
|
|
283
357
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
@@ -297,13 +371,53 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
297
371
|
});
|
|
298
372
|
});
|
|
299
373
|
|
|
374
|
+
this.sql`
|
|
375
|
+
CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
|
|
376
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
377
|
+
name TEXT NOT NULL,
|
|
378
|
+
server_url TEXT NOT NULL,
|
|
379
|
+
callback_url TEXT NOT NULL,
|
|
380
|
+
client_id TEXT,
|
|
381
|
+
auth_url TEXT,
|
|
382
|
+
server_options TEXT
|
|
383
|
+
)
|
|
384
|
+
`;
|
|
385
|
+
|
|
386
|
+
const _onRequest = this.onRequest.bind(this);
|
|
387
|
+
this.onRequest = (request: Request) => {
|
|
388
|
+
return agentContext.run(
|
|
389
|
+
{ agent: this, connection: undefined, request },
|
|
390
|
+
async () => {
|
|
391
|
+
if (this.mcp.isCallbackRequest(request)) {
|
|
392
|
+
await this.mcp.handleCallbackRequest(request);
|
|
393
|
+
|
|
394
|
+
// after the MCP connection handshake, we can send updated mcp state
|
|
395
|
+
this.broadcast(
|
|
396
|
+
JSON.stringify({
|
|
397
|
+
type: "cf_agent_mcp_servers",
|
|
398
|
+
mcp: this._getMcpServerStateInternal(),
|
|
399
|
+
})
|
|
400
|
+
);
|
|
401
|
+
|
|
402
|
+
// We probably should let the user configure this response/redirect, but this is fine for now.
|
|
403
|
+
return new Response("<script>window.close();</script>", {
|
|
404
|
+
status: 200,
|
|
405
|
+
headers: { "content-type": "text/html" },
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
return this._tryCatch(() => _onRequest(request));
|
|
410
|
+
}
|
|
411
|
+
);
|
|
412
|
+
};
|
|
413
|
+
|
|
300
414
|
const _onMessage = this.onMessage.bind(this);
|
|
301
415
|
this.onMessage = async (connection: Connection, message: WSMessage) => {
|
|
302
|
-
return
|
|
416
|
+
return agentContext.run(
|
|
303
417
|
{ agent: this, connection, request: undefined },
|
|
304
418
|
async () => {
|
|
305
419
|
if (typeof message !== "string") {
|
|
306
|
-
return this
|
|
420
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
307
421
|
}
|
|
308
422
|
|
|
309
423
|
let parsed: unknown;
|
|
@@ -311,11 +425,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
311
425
|
parsed = JSON.parse(message);
|
|
312
426
|
} catch (e) {
|
|
313
427
|
// silently fail and let the onMessage handler handle it
|
|
314
|
-
return this
|
|
428
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
315
429
|
}
|
|
316
430
|
|
|
317
431
|
if (isStateUpdateMessage(parsed)) {
|
|
318
|
-
this
|
|
432
|
+
this._setStateInternal(parsed.state as State, connection);
|
|
319
433
|
return;
|
|
320
434
|
}
|
|
321
435
|
|
|
@@ -329,11 +443,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
329
443
|
throw new Error(`Method ${method} does not exist`);
|
|
330
444
|
}
|
|
331
445
|
|
|
332
|
-
if (!this
|
|
446
|
+
if (!this._isCallable(method)) {
|
|
333
447
|
throw new Error(`Method ${method} is not callable`);
|
|
334
448
|
}
|
|
335
449
|
|
|
336
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
337
450
|
const metadata = callableMetadata.get(methodFn as Function);
|
|
338
451
|
|
|
339
452
|
// For streaming methods, pass a StreamingResponse object
|
|
@@ -368,7 +481,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
368
481
|
return;
|
|
369
482
|
}
|
|
370
483
|
|
|
371
|
-
return this
|
|
484
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
372
485
|
}
|
|
373
486
|
);
|
|
374
487
|
};
|
|
@@ -377,7 +490,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
377
490
|
this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
|
|
378
491
|
// TODO: This is a hack to ensure the state is sent after the connection is established
|
|
379
492
|
// must fix this
|
|
380
|
-
return
|
|
493
|
+
return agentContext.run(
|
|
381
494
|
{ agent: this, connection, request: ctx.request },
|
|
382
495
|
async () => {
|
|
383
496
|
setTimeout(() => {
|
|
@@ -389,15 +502,65 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
389
502
|
})
|
|
390
503
|
);
|
|
391
504
|
}
|
|
392
|
-
|
|
505
|
+
|
|
506
|
+
connection.send(
|
|
507
|
+
JSON.stringify({
|
|
508
|
+
type: "cf_agent_mcp_servers",
|
|
509
|
+
mcp: this._getMcpServerStateInternal(),
|
|
510
|
+
})
|
|
511
|
+
);
|
|
512
|
+
|
|
513
|
+
return this._tryCatch(() => _onConnect(connection, ctx));
|
|
393
514
|
}, 20);
|
|
394
515
|
}
|
|
395
516
|
);
|
|
396
517
|
};
|
|
518
|
+
|
|
519
|
+
const _onStart = this.onStart.bind(this);
|
|
520
|
+
this.onStart = async () => {
|
|
521
|
+
return agentContext.run(
|
|
522
|
+
{ agent: this, connection: undefined, request: undefined },
|
|
523
|
+
async () => {
|
|
524
|
+
const servers = this.sql<MCPServerRow>`
|
|
525
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
526
|
+
`;
|
|
527
|
+
|
|
528
|
+
// from DO storage, reconnect to all servers using our saved auth information
|
|
529
|
+
await Promise.allSettled(
|
|
530
|
+
servers.map((server) => {
|
|
531
|
+
return this._connectToMcpServerInternal(
|
|
532
|
+
server.name,
|
|
533
|
+
server.server_url,
|
|
534
|
+
server.callback_url,
|
|
535
|
+
server.server_options
|
|
536
|
+
? JSON.parse(server.server_options)
|
|
537
|
+
: undefined,
|
|
538
|
+
{
|
|
539
|
+
id: server.id,
|
|
540
|
+
oauthClientId: server.client_id ?? undefined,
|
|
541
|
+
}
|
|
542
|
+
);
|
|
543
|
+
})
|
|
544
|
+
);
|
|
545
|
+
|
|
546
|
+
this.broadcast(
|
|
547
|
+
JSON.stringify({
|
|
548
|
+
type: "cf_agent_mcp_servers",
|
|
549
|
+
mcp: this._getMcpServerStateInternal(),
|
|
550
|
+
})
|
|
551
|
+
);
|
|
552
|
+
|
|
553
|
+
await this._tryCatch(() => _onStart());
|
|
554
|
+
}
|
|
555
|
+
);
|
|
556
|
+
};
|
|
397
557
|
}
|
|
398
558
|
|
|
399
|
-
|
|
400
|
-
|
|
559
|
+
private _setStateInternal(
|
|
560
|
+
state: State,
|
|
561
|
+
source: Connection | "server" = "server"
|
|
562
|
+
) {
|
|
563
|
+
this._state = state;
|
|
401
564
|
this.sql`
|
|
402
565
|
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
403
566
|
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
@@ -413,9 +576,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
413
576
|
}),
|
|
414
577
|
source !== "server" ? [source.id] : []
|
|
415
578
|
);
|
|
416
|
-
return this
|
|
417
|
-
const { connection, request } =
|
|
418
|
-
return
|
|
579
|
+
return this._tryCatch(() => {
|
|
580
|
+
const { connection, request } = agentContext.getStore() || {};
|
|
581
|
+
return agentContext.run(
|
|
419
582
|
{ agent: this, connection, request },
|
|
420
583
|
async () => {
|
|
421
584
|
return this.onStateUpdate(state, source);
|
|
@@ -429,7 +592,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
429
592
|
* @param state New state to set
|
|
430
593
|
*/
|
|
431
594
|
setState(state: State) {
|
|
432
|
-
this
|
|
595
|
+
this._setStateInternal(state, "server");
|
|
433
596
|
}
|
|
434
597
|
|
|
435
598
|
/**
|
|
@@ -446,7 +609,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
446
609
|
* @param email Email message to process
|
|
447
610
|
*/
|
|
448
611
|
onEmail(email: ForwardableEmailMessage) {
|
|
449
|
-
return
|
|
612
|
+
return agentContext.run(
|
|
450
613
|
{ agent: this, connection: undefined, request: undefined },
|
|
451
614
|
async () => {
|
|
452
615
|
console.error("onEmail not implemented");
|
|
@@ -454,7 +617,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
454
617
|
);
|
|
455
618
|
}
|
|
456
619
|
|
|
457
|
-
async
|
|
620
|
+
private async _tryCatch<T>(fn: () => T | Promise<T>) {
|
|
458
621
|
try {
|
|
459
622
|
return await fn();
|
|
460
623
|
} catch (e) {
|
|
@@ -528,7 +691,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
528
691
|
)}, 'scheduled', ${timestamp})
|
|
529
692
|
`;
|
|
530
693
|
|
|
531
|
-
await this
|
|
694
|
+
await this._scheduleNextAlarm();
|
|
532
695
|
|
|
533
696
|
return {
|
|
534
697
|
id,
|
|
@@ -549,7 +712,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
549
712
|
)}, 'delayed', ${when}, ${timestamp})
|
|
550
713
|
`;
|
|
551
714
|
|
|
552
|
-
await this
|
|
715
|
+
await this._scheduleNextAlarm();
|
|
553
716
|
|
|
554
717
|
return {
|
|
555
718
|
id,
|
|
@@ -571,7 +734,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
571
734
|
)}, 'cron', ${when}, ${timestamp})
|
|
572
735
|
`;
|
|
573
736
|
|
|
574
|
-
await this
|
|
737
|
+
await this._scheduleNextAlarm();
|
|
575
738
|
|
|
576
739
|
return {
|
|
577
740
|
id,
|
|
@@ -658,11 +821,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
658
821
|
async cancelSchedule(id: string): Promise<boolean> {
|
|
659
822
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
660
823
|
|
|
661
|
-
await this
|
|
824
|
+
await this._scheduleNextAlarm();
|
|
662
825
|
return true;
|
|
663
826
|
}
|
|
664
827
|
|
|
665
|
-
async
|
|
828
|
+
private async _scheduleNextAlarm() {
|
|
666
829
|
// Find the next schedule that needs to be executed
|
|
667
830
|
const result = this.sql`
|
|
668
831
|
SELECT time FROM cf_agents_schedules
|
|
@@ -679,10 +842,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
679
842
|
}
|
|
680
843
|
|
|
681
844
|
/**
|
|
682
|
-
* Method called when an alarm fires
|
|
683
|
-
* Executes any scheduled tasks that are due
|
|
845
|
+
* Method called when an alarm fires.
|
|
846
|
+
* Executes any scheduled tasks that are due.
|
|
847
|
+
*
|
|
848
|
+
* @remarks
|
|
849
|
+
* To schedule a task, please use the `this.schedule` method instead.
|
|
850
|
+
* See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
|
|
684
851
|
*/
|
|
685
|
-
async
|
|
852
|
+
public readonly alarm = async () => {
|
|
686
853
|
const now = Math.floor(Date.now() / 1000);
|
|
687
854
|
|
|
688
855
|
// Get all schedules that should be executed now
|
|
@@ -696,7 +863,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
696
863
|
console.error(`callback ${row.callback} not found`);
|
|
697
864
|
continue;
|
|
698
865
|
}
|
|
699
|
-
await
|
|
866
|
+
await agentContext.run(
|
|
700
867
|
{ agent: this, connection: undefined, request: undefined },
|
|
701
868
|
async () => {
|
|
702
869
|
try {
|
|
@@ -728,8 +895,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
728
895
|
}
|
|
729
896
|
|
|
730
897
|
// Schedule the next alarm
|
|
731
|
-
await this
|
|
732
|
-
}
|
|
898
|
+
await this._scheduleNextAlarm();
|
|
899
|
+
};
|
|
733
900
|
|
|
734
901
|
/**
|
|
735
902
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -738,6 +905,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
738
905
|
// drop all tables
|
|
739
906
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
740
907
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
908
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
741
909
|
|
|
742
910
|
// delete all alarms
|
|
743
911
|
await this.ctx.storage.deleteAlarm();
|
|
@@ -748,10 +916,168 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
748
916
|
* Get all methods marked as callable on this Agent
|
|
749
917
|
* @returns A map of method names to their metadata
|
|
750
918
|
*/
|
|
751
|
-
|
|
752
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
919
|
+
private _isCallable(method: string): boolean {
|
|
753
920
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
754
921
|
}
|
|
922
|
+
|
|
923
|
+
/**
|
|
924
|
+
* Connect to a new MCP Server
|
|
925
|
+
*
|
|
926
|
+
* @param url MCP Server SSE URL
|
|
927
|
+
* @param callbackHost Base host for the agent, used for the redirect URI.
|
|
928
|
+
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
929
|
+
* @param options MCP client and transport (header) options
|
|
930
|
+
* @returns authUrl
|
|
931
|
+
*/
|
|
932
|
+
async addMcpServer(
|
|
933
|
+
serverName: string,
|
|
934
|
+
url: string,
|
|
935
|
+
callbackHost: string,
|
|
936
|
+
agentsPrefix = "agents",
|
|
937
|
+
options?: {
|
|
938
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
939
|
+
transport?: {
|
|
940
|
+
headers: HeadersInit;
|
|
941
|
+
};
|
|
942
|
+
}
|
|
943
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
944
|
+
const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
945
|
+
|
|
946
|
+
const result = await this._connectToMcpServerInternal(
|
|
947
|
+
serverName,
|
|
948
|
+
url,
|
|
949
|
+
callbackUrl,
|
|
950
|
+
options
|
|
951
|
+
);
|
|
952
|
+
|
|
953
|
+
this.broadcast(
|
|
954
|
+
JSON.stringify({
|
|
955
|
+
type: "cf_agent_mcp_servers",
|
|
956
|
+
mcp: this._getMcpServerStateInternal(),
|
|
957
|
+
})
|
|
958
|
+
);
|
|
959
|
+
|
|
960
|
+
return result;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
async _connectToMcpServerInternal(
|
|
964
|
+
serverName: string,
|
|
965
|
+
url: string,
|
|
966
|
+
callbackUrl: string,
|
|
967
|
+
// it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
|
|
968
|
+
options?: {
|
|
969
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
970
|
+
/**
|
|
971
|
+
* We don't expose the normal set of transport options because:
|
|
972
|
+
* 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
|
|
973
|
+
* 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
|
|
974
|
+
*
|
|
975
|
+
* 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).
|
|
976
|
+
*/
|
|
977
|
+
transport?: {
|
|
978
|
+
headers?: HeadersInit;
|
|
979
|
+
};
|
|
980
|
+
},
|
|
981
|
+
reconnect?: {
|
|
982
|
+
id: string;
|
|
983
|
+
oauthClientId?: string;
|
|
984
|
+
}
|
|
985
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
986
|
+
const authProvider = new DurableObjectOAuthClientProvider(
|
|
987
|
+
this.ctx.storage,
|
|
988
|
+
this.name,
|
|
989
|
+
callbackUrl
|
|
990
|
+
);
|
|
991
|
+
|
|
992
|
+
if (reconnect) {
|
|
993
|
+
authProvider.serverId = reconnect.id;
|
|
994
|
+
if (reconnect.oauthClientId) {
|
|
995
|
+
authProvider.clientId = reconnect.oauthClientId;
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
// allows passing through transport headers if necessary
|
|
1000
|
+
// this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
|
|
1001
|
+
let headerTransportOpts: SSEClientTransportOptions = {};
|
|
1002
|
+
if (options?.transport?.headers) {
|
|
1003
|
+
headerTransportOpts = {
|
|
1004
|
+
eventSourceInit: {
|
|
1005
|
+
fetch: (url, init) =>
|
|
1006
|
+
fetch(url, {
|
|
1007
|
+
...init,
|
|
1008
|
+
headers: options?.transport?.headers,
|
|
1009
|
+
}),
|
|
1010
|
+
},
|
|
1011
|
+
requestInit: {
|
|
1012
|
+
headers: options?.transport?.headers,
|
|
1013
|
+
},
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
const { id, authUrl, clientId } = await this.mcp.connect(url, {
|
|
1018
|
+
reconnect,
|
|
1019
|
+
transport: {
|
|
1020
|
+
...headerTransportOpts,
|
|
1021
|
+
authProvider,
|
|
1022
|
+
},
|
|
1023
|
+
client: options?.client,
|
|
1024
|
+
});
|
|
1025
|
+
|
|
1026
|
+
this.sql`
|
|
1027
|
+
INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
1028
|
+
VALUES (
|
|
1029
|
+
${id},
|
|
1030
|
+
${serverName},
|
|
1031
|
+
${url},
|
|
1032
|
+
${clientId ?? null},
|
|
1033
|
+
${authUrl ?? null},
|
|
1034
|
+
${callbackUrl},
|
|
1035
|
+
${options ? JSON.stringify(options) : null}
|
|
1036
|
+
);
|
|
1037
|
+
`;
|
|
1038
|
+
|
|
1039
|
+
return {
|
|
1040
|
+
id,
|
|
1041
|
+
authUrl,
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
async removeMcpServer(id: string) {
|
|
1046
|
+
this.mcp.closeConnection(id);
|
|
1047
|
+
this.sql`
|
|
1048
|
+
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
1049
|
+
`;
|
|
1050
|
+
this.broadcast(
|
|
1051
|
+
JSON.stringify({
|
|
1052
|
+
type: "cf_agent_mcp_servers",
|
|
1053
|
+
mcp: this._getMcpServerStateInternal(),
|
|
1054
|
+
})
|
|
1055
|
+
);
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
private _getMcpServerStateInternal(): MCPServersState {
|
|
1059
|
+
const mcpState: MCPServersState = {
|
|
1060
|
+
servers: {},
|
|
1061
|
+
tools: this.mcp.listTools(),
|
|
1062
|
+
prompts: this.mcp.listPrompts(),
|
|
1063
|
+
resources: this.mcp.listResources(),
|
|
1064
|
+
};
|
|
1065
|
+
|
|
1066
|
+
const servers = this.sql<MCPServerRow>`
|
|
1067
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
1068
|
+
`;
|
|
1069
|
+
|
|
1070
|
+
for (const server of servers) {
|
|
1071
|
+
mcpState.servers[server.id] = {
|
|
1072
|
+
name: server.name,
|
|
1073
|
+
server_url: server.server_url,
|
|
1074
|
+
auth_url: server.auth_url,
|
|
1075
|
+
state: this.mcp.mcpConnections[server.id].connectionState,
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
return mcpState;
|
|
1080
|
+
}
|
|
755
1081
|
}
|
|
756
1082
|
|
|
757
1083
|
/**
|
|
@@ -855,7 +1181,7 @@ export async function routeAgentEmail<Env>(
|
|
|
855
1181
|
* @param options Options for Agent creation
|
|
856
1182
|
* @returns Promise resolving to an Agent instance stub
|
|
857
1183
|
*/
|
|
858
|
-
export function getAgentByName<Env, T extends Agent<Env>>(
|
|
1184
|
+
export async function getAgentByName<Env, T extends Agent<Env>>(
|
|
859
1185
|
namespace: AgentNamespace<T>,
|
|
860
1186
|
name: string,
|
|
861
1187
|
options?: {
|
|
@@ -870,13 +1196,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
|
|
|
870
1196
|
* A wrapper for streaming responses in callable methods
|
|
871
1197
|
*/
|
|
872
1198
|
export class StreamingResponse {
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
1199
|
+
private _connection: Connection;
|
|
1200
|
+
private _id: string;
|
|
1201
|
+
private _closed = false;
|
|
876
1202
|
|
|
877
1203
|
constructor(connection: Connection, id: string) {
|
|
878
|
-
this
|
|
879
|
-
this
|
|
1204
|
+
this._connection = connection;
|
|
1205
|
+
this._id = id;
|
|
880
1206
|
}
|
|
881
1207
|
|
|
882
1208
|
/**
|
|
@@ -884,17 +1210,17 @@ export class StreamingResponse {
|
|
|
884
1210
|
* @param chunk The data to send
|
|
885
1211
|
*/
|
|
886
1212
|
send(chunk: unknown) {
|
|
887
|
-
if (this
|
|
1213
|
+
if (this._closed) {
|
|
888
1214
|
throw new Error("StreamingResponse is already closed");
|
|
889
1215
|
}
|
|
890
1216
|
const response: RPCResponse = {
|
|
891
1217
|
type: "rpc",
|
|
892
|
-
id: this
|
|
1218
|
+
id: this._id,
|
|
893
1219
|
success: true,
|
|
894
1220
|
result: chunk,
|
|
895
1221
|
done: false,
|
|
896
1222
|
};
|
|
897
|
-
this
|
|
1223
|
+
this._connection.send(JSON.stringify(response));
|
|
898
1224
|
}
|
|
899
1225
|
|
|
900
1226
|
/**
|
|
@@ -902,17 +1228,17 @@ export class StreamingResponse {
|
|
|
902
1228
|
* @param finalChunk Optional final chunk of data to send
|
|
903
1229
|
*/
|
|
904
1230
|
end(finalChunk?: unknown) {
|
|
905
|
-
if (this
|
|
1231
|
+
if (this._closed) {
|
|
906
1232
|
throw new Error("StreamingResponse is already closed");
|
|
907
1233
|
}
|
|
908
|
-
this
|
|
1234
|
+
this._closed = true;
|
|
909
1235
|
const response: RPCResponse = {
|
|
910
1236
|
type: "rpc",
|
|
911
|
-
id: this
|
|
1237
|
+
id: this._id,
|
|
912
1238
|
success: true,
|
|
913
1239
|
result: finalChunk,
|
|
914
1240
|
done: true,
|
|
915
1241
|
};
|
|
916
|
-
this
|
|
1242
|
+
this._connection.send(JSON.stringify(response));
|
|
917
1243
|
}
|
|
918
1244
|
}
|
package/dist/chunk-HMLY7DHA.js
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
var __typeError = (msg) => {
|
|
2
|
-
throw TypeError(msg);
|
|
3
|
-
};
|
|
4
|
-
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
5
|
-
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
6
|
-
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
7
|
-
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
8
|
-
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
9
|
-
|
|
10
|
-
export {
|
|
11
|
-
__privateGet,
|
|
12
|
-
__privateAdd,
|
|
13
|
-
__privateSet,
|
|
14
|
-
__privateMethod
|
|
15
|
-
};
|
|
16
|
-
//# sourceMappingURL=chunk-HMLY7DHA.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|