agents 0.0.0-3f532ba → 0.0.0-4100b67
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 +12 -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-XG52S6YY.js → chunk-4ARKO5R4.js} +323 -133
- 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-Y67CHZBI.js +464 -0
- 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 +113 -11
- package/dist/index.js +8 -6
- package/dist/mcp/client.d.ts +32 -12
- 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 +27 -5
- package/dist/mcp/index.js +139 -138
- 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 +16 -9
- package/src/index.ts +383 -51
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-HMLY7DHA.js.map +0 -1
- package/dist/chunk-XG52S6YY.js.map +0 -1
package/src/index.ts
CHANGED
|
@@ -12,6 +12,21 @@ import { parseCronExpression } from "cron-schedule";
|
|
|
12
12
|
import { nanoid } from "nanoid";
|
|
13
13
|
|
|
14
14
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
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";
|
|
15
30
|
|
|
16
31
|
export type { Connection, WSMessage, ConnectionContext } from "partyserver";
|
|
17
32
|
|
|
@@ -97,7 +112,6 @@ export type CallableMetadata = {
|
|
|
97
112
|
streaming?: boolean;
|
|
98
113
|
};
|
|
99
114
|
|
|
100
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
101
115
|
const callableMetadata = new Map<Function, CallableMetadata>();
|
|
102
116
|
|
|
103
117
|
/**
|
|
@@ -158,24 +172,90 @@ function getNextCronTime(cron: string) {
|
|
|
158
172
|
return interval.getNextDate();
|
|
159
173
|
}
|
|
160
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
|
+
|
|
161
212
|
const STATE_ROW_ID = "cf_state_row_id";
|
|
162
213
|
const STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
163
214
|
|
|
164
215
|
const DEFAULT_STATE = {} as unknown;
|
|
165
216
|
|
|
166
|
-
|
|
217
|
+
const agentContext = new AsyncLocalStorage<{
|
|
167
218
|
agent: Agent<unknown>;
|
|
168
219
|
connection: Connection | undefined;
|
|
169
220
|
request: Request | undefined;
|
|
170
221
|
}>();
|
|
171
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
|
+
|
|
172
247
|
/**
|
|
173
248
|
* Base class for creating Agent implementations
|
|
174
249
|
* @template Env Environment type containing bindings
|
|
175
250
|
* @template State State type to store within the Agent
|
|
176
251
|
*/
|
|
177
252
|
export class Agent<Env, State = unknown> extends Server<Env> {
|
|
178
|
-
|
|
253
|
+
private _state = DEFAULT_STATE as State;
|
|
254
|
+
|
|
255
|
+
private _ParentClass: typeof Agent<Env, State> =
|
|
256
|
+
Object.getPrototypeOf(this).constructor;
|
|
257
|
+
|
|
258
|
+
mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
179
259
|
|
|
180
260
|
/**
|
|
181
261
|
* Initial state for the Agent
|
|
@@ -187,9 +267,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
187
267
|
* Current state of the Agent
|
|
188
268
|
*/
|
|
189
269
|
get state(): State {
|
|
190
|
-
if (this
|
|
270
|
+
if (this._state !== DEFAULT_STATE) {
|
|
191
271
|
// state was previously set, and populated internal state
|
|
192
|
-
return this
|
|
272
|
+
return this._state;
|
|
193
273
|
}
|
|
194
274
|
// looks like this is the first time the state is being accessed
|
|
195
275
|
// check if the state was set in a previous life
|
|
@@ -209,8 +289,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
209
289
|
) {
|
|
210
290
|
const state = result[0]?.state as string; // could be null?
|
|
211
291
|
|
|
212
|
-
this
|
|
213
|
-
return this
|
|
292
|
+
this._state = JSON.parse(state);
|
|
293
|
+
return this._state;
|
|
214
294
|
}
|
|
215
295
|
|
|
216
296
|
// ok, this is the first time the state is being accessed
|
|
@@ -271,7 +351,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
271
351
|
`;
|
|
272
352
|
|
|
273
353
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
274
|
-
return this
|
|
354
|
+
return this._tryCatch(async () => {
|
|
275
355
|
// Create alarms table if it doesn't exist
|
|
276
356
|
this.sql`
|
|
277
357
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
@@ -291,13 +371,53 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
291
371
|
});
|
|
292
372
|
});
|
|
293
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
|
+
|
|
294
414
|
const _onMessage = this.onMessage.bind(this);
|
|
295
415
|
this.onMessage = async (connection: Connection, message: WSMessage) => {
|
|
296
|
-
return
|
|
416
|
+
return agentContext.run(
|
|
297
417
|
{ agent: this, connection, request: undefined },
|
|
298
418
|
async () => {
|
|
299
419
|
if (typeof message !== "string") {
|
|
300
|
-
return this
|
|
420
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
301
421
|
}
|
|
302
422
|
|
|
303
423
|
let parsed: unknown;
|
|
@@ -305,11 +425,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
305
425
|
parsed = JSON.parse(message);
|
|
306
426
|
} catch (e) {
|
|
307
427
|
// silently fail and let the onMessage handler handle it
|
|
308
|
-
return this
|
|
428
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
309
429
|
}
|
|
310
430
|
|
|
311
431
|
if (isStateUpdateMessage(parsed)) {
|
|
312
|
-
this
|
|
432
|
+
this._setStateInternal(parsed.state as State, connection);
|
|
313
433
|
return;
|
|
314
434
|
}
|
|
315
435
|
|
|
@@ -323,11 +443,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
323
443
|
throw new Error(`Method ${method} does not exist`);
|
|
324
444
|
}
|
|
325
445
|
|
|
326
|
-
if (!this
|
|
446
|
+
if (!this._isCallable(method)) {
|
|
327
447
|
throw new Error(`Method ${method} is not callable`);
|
|
328
448
|
}
|
|
329
449
|
|
|
330
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
331
450
|
const metadata = callableMetadata.get(methodFn as Function);
|
|
332
451
|
|
|
333
452
|
// For streaming methods, pass a StreamingResponse object
|
|
@@ -362,7 +481,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
362
481
|
return;
|
|
363
482
|
}
|
|
364
483
|
|
|
365
|
-
return this
|
|
484
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
366
485
|
}
|
|
367
486
|
);
|
|
368
487
|
};
|
|
@@ -371,7 +490,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
371
490
|
this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
|
|
372
491
|
// TODO: This is a hack to ensure the state is sent after the connection is established
|
|
373
492
|
// must fix this
|
|
374
|
-
return
|
|
493
|
+
return agentContext.run(
|
|
375
494
|
{ agent: this, connection, request: ctx.request },
|
|
376
495
|
async () => {
|
|
377
496
|
setTimeout(() => {
|
|
@@ -383,15 +502,65 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
383
502
|
})
|
|
384
503
|
);
|
|
385
504
|
}
|
|
386
|
-
|
|
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));
|
|
387
514
|
}, 20);
|
|
388
515
|
}
|
|
389
516
|
);
|
|
390
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
|
+
};
|
|
391
557
|
}
|
|
392
558
|
|
|
393
|
-
|
|
394
|
-
|
|
559
|
+
private _setStateInternal(
|
|
560
|
+
state: State,
|
|
561
|
+
source: Connection | "server" = "server"
|
|
562
|
+
) {
|
|
563
|
+
this._state = state;
|
|
395
564
|
this.sql`
|
|
396
565
|
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
397
566
|
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
@@ -407,9 +576,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
407
576
|
}),
|
|
408
577
|
source !== "server" ? [source.id] : []
|
|
409
578
|
);
|
|
410
|
-
return this
|
|
411
|
-
const { connection, request } =
|
|
412
|
-
return
|
|
579
|
+
return this._tryCatch(() => {
|
|
580
|
+
const { connection, request } = agentContext.getStore() || {};
|
|
581
|
+
return agentContext.run(
|
|
413
582
|
{ agent: this, connection, request },
|
|
414
583
|
async () => {
|
|
415
584
|
return this.onStateUpdate(state, source);
|
|
@@ -423,7 +592,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
423
592
|
* @param state New state to set
|
|
424
593
|
*/
|
|
425
594
|
setState(state: State) {
|
|
426
|
-
this
|
|
595
|
+
this._setStateInternal(state, "server");
|
|
427
596
|
}
|
|
428
597
|
|
|
429
598
|
/**
|
|
@@ -440,7 +609,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
440
609
|
* @param email Email message to process
|
|
441
610
|
*/
|
|
442
611
|
onEmail(email: ForwardableEmailMessage) {
|
|
443
|
-
return
|
|
612
|
+
return agentContext.run(
|
|
444
613
|
{ agent: this, connection: undefined, request: undefined },
|
|
445
614
|
async () => {
|
|
446
615
|
console.error("onEmail not implemented");
|
|
@@ -448,7 +617,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
448
617
|
);
|
|
449
618
|
}
|
|
450
619
|
|
|
451
|
-
async
|
|
620
|
+
private async _tryCatch<T>(fn: () => T | Promise<T>) {
|
|
452
621
|
try {
|
|
453
622
|
return await fn();
|
|
454
623
|
} catch (e) {
|
|
@@ -522,7 +691,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
522
691
|
)}, 'scheduled', ${timestamp})
|
|
523
692
|
`;
|
|
524
693
|
|
|
525
|
-
await this
|
|
694
|
+
await this._scheduleNextAlarm();
|
|
526
695
|
|
|
527
696
|
return {
|
|
528
697
|
id,
|
|
@@ -543,7 +712,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
543
712
|
)}, 'delayed', ${when}, ${timestamp})
|
|
544
713
|
`;
|
|
545
714
|
|
|
546
|
-
await this
|
|
715
|
+
await this._scheduleNextAlarm();
|
|
547
716
|
|
|
548
717
|
return {
|
|
549
718
|
id,
|
|
@@ -565,7 +734,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
565
734
|
)}, 'cron', ${when}, ${timestamp})
|
|
566
735
|
`;
|
|
567
736
|
|
|
568
|
-
await this
|
|
737
|
+
await this._scheduleNextAlarm();
|
|
569
738
|
|
|
570
739
|
return {
|
|
571
740
|
id,
|
|
@@ -652,11 +821,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
652
821
|
async cancelSchedule(id: string): Promise<boolean> {
|
|
653
822
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
654
823
|
|
|
655
|
-
await this
|
|
824
|
+
await this._scheduleNextAlarm();
|
|
656
825
|
return true;
|
|
657
826
|
}
|
|
658
827
|
|
|
659
|
-
async
|
|
828
|
+
private async _scheduleNextAlarm() {
|
|
660
829
|
// Find the next schedule that needs to be executed
|
|
661
830
|
const result = this.sql`
|
|
662
831
|
SELECT time FROM cf_agents_schedules
|
|
@@ -673,10 +842,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
673
842
|
}
|
|
674
843
|
|
|
675
844
|
/**
|
|
676
|
-
* Method called when an alarm fires
|
|
677
|
-
* 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/}
|
|
678
851
|
*/
|
|
679
|
-
async
|
|
852
|
+
public readonly alarm = async () => {
|
|
680
853
|
const now = Math.floor(Date.now() / 1000);
|
|
681
854
|
|
|
682
855
|
// Get all schedules that should be executed now
|
|
@@ -690,7 +863,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
690
863
|
console.error(`callback ${row.callback} not found`);
|
|
691
864
|
continue;
|
|
692
865
|
}
|
|
693
|
-
await
|
|
866
|
+
await agentContext.run(
|
|
694
867
|
{ agent: this, connection: undefined, request: undefined },
|
|
695
868
|
async () => {
|
|
696
869
|
try {
|
|
@@ -722,8 +895,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
722
895
|
}
|
|
723
896
|
|
|
724
897
|
// Schedule the next alarm
|
|
725
|
-
await this
|
|
726
|
-
}
|
|
898
|
+
await this._scheduleNextAlarm();
|
|
899
|
+
};
|
|
727
900
|
|
|
728
901
|
/**
|
|
729
902
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -732,6 +905,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
732
905
|
// drop all tables
|
|
733
906
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
734
907
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
908
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
735
909
|
|
|
736
910
|
// delete all alarms
|
|
737
911
|
await this.ctx.storage.deleteAlarm();
|
|
@@ -742,10 +916,168 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
742
916
|
* Get all methods marked as callable on this Agent
|
|
743
917
|
* @returns A map of method names to their metadata
|
|
744
918
|
*/
|
|
745
|
-
|
|
746
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
919
|
+
private _isCallable(method: string): boolean {
|
|
747
920
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
748
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
|
+
}
|
|
749
1081
|
}
|
|
750
1082
|
|
|
751
1083
|
/**
|
|
@@ -849,7 +1181,7 @@ export async function routeAgentEmail<Env>(
|
|
|
849
1181
|
* @param options Options for Agent creation
|
|
850
1182
|
* @returns Promise resolving to an Agent instance stub
|
|
851
1183
|
*/
|
|
852
|
-
export function getAgentByName<Env, T extends Agent<Env>>(
|
|
1184
|
+
export async function getAgentByName<Env, T extends Agent<Env>>(
|
|
853
1185
|
namespace: AgentNamespace<T>,
|
|
854
1186
|
name: string,
|
|
855
1187
|
options?: {
|
|
@@ -864,13 +1196,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
|
|
|
864
1196
|
* A wrapper for streaming responses in callable methods
|
|
865
1197
|
*/
|
|
866
1198
|
export class StreamingResponse {
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
1199
|
+
private _connection: Connection;
|
|
1200
|
+
private _id: string;
|
|
1201
|
+
private _closed = false;
|
|
870
1202
|
|
|
871
1203
|
constructor(connection: Connection, id: string) {
|
|
872
|
-
this
|
|
873
|
-
this
|
|
1204
|
+
this._connection = connection;
|
|
1205
|
+
this._id = id;
|
|
874
1206
|
}
|
|
875
1207
|
|
|
876
1208
|
/**
|
|
@@ -878,17 +1210,17 @@ export class StreamingResponse {
|
|
|
878
1210
|
* @param chunk The data to send
|
|
879
1211
|
*/
|
|
880
1212
|
send(chunk: unknown) {
|
|
881
|
-
if (this
|
|
1213
|
+
if (this._closed) {
|
|
882
1214
|
throw new Error("StreamingResponse is already closed");
|
|
883
1215
|
}
|
|
884
1216
|
const response: RPCResponse = {
|
|
885
1217
|
type: "rpc",
|
|
886
|
-
id: this
|
|
1218
|
+
id: this._id,
|
|
887
1219
|
success: true,
|
|
888
1220
|
result: chunk,
|
|
889
1221
|
done: false,
|
|
890
1222
|
};
|
|
891
|
-
this
|
|
1223
|
+
this._connection.send(JSON.stringify(response));
|
|
892
1224
|
}
|
|
893
1225
|
|
|
894
1226
|
/**
|
|
@@ -896,17 +1228,17 @@ export class StreamingResponse {
|
|
|
896
1228
|
* @param finalChunk Optional final chunk of data to send
|
|
897
1229
|
*/
|
|
898
1230
|
end(finalChunk?: unknown) {
|
|
899
|
-
if (this
|
|
1231
|
+
if (this._closed) {
|
|
900
1232
|
throw new Error("StreamingResponse is already closed");
|
|
901
1233
|
}
|
|
902
|
-
this
|
|
1234
|
+
this._closed = true;
|
|
903
1235
|
const response: RPCResponse = {
|
|
904
1236
|
type: "rpc",
|
|
905
|
-
id: this
|
|
1237
|
+
id: this._id,
|
|
906
1238
|
success: true,
|
|
907
1239
|
result: finalChunk,
|
|
908
1240
|
done: true,
|
|
909
1241
|
};
|
|
910
|
-
this
|
|
1242
|
+
this._connection.send(JSON.stringify(response));
|
|
911
1243
|
}
|
|
912
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":[]}
|