agents 0.0.0-d7a460e → 0.0.0-da2bb57
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 +5 -3
- package/dist/ai-chat-agent.d.ts +86 -13
- package/dist/ai-chat-agent.js +340 -74
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/{ai-chat-v5-migration-DBHGW4Hv.js → ai-chat-v5-migration-BSiGZmYU.js} +1 -1
- package/dist/{ai-chat-v5-migration-DBHGW4Hv.js.map → ai-chat-v5-migration-BSiGZmYU.js.map} +1 -1
- package/dist/ai-chat-v5-migration.js +1 -1
- package/dist/ai-react.d.ts +14 -9
- package/dist/ai-react.js +164 -29
- package/dist/ai-react.js.map +1 -1
- package/dist/{ai-types-D5YoPrBZ.d.ts → ai-types-81H_-Uxh.d.ts} +15 -7
- package/dist/{ai-types-B3aQaFv3.js → ai-types-CrMqkwc_.js} +5 -1
- package/dist/ai-types-CrMqkwc_.js.map +1 -0
- package/dist/ai-types.d.ts +1 -1
- package/dist/ai-types.js +1 -1
- package/dist/cli.d.ts +8 -0
- package/dist/cli.js +27 -0
- package/dist/cli.js.map +1 -0
- package/dist/{client-BfiZ3HQd.js → client-B3SR12TQ.js} +2 -2
- package/dist/{client-BfiZ3HQd.js.map → client-B3SR12TQ.js.map} +1 -1
- package/dist/{client-CbWe9FBd.d.ts → client-BAQA84dr.d.ts} +2 -2
- package/dist/client-BZq9qau2.js +1093 -0
- package/dist/client-BZq9qau2.js.map +1 -0
- package/dist/client-DJhQNTez.d.ts +1528 -0
- package/dist/client.d.ts +2 -2
- package/dist/client.js +2 -2
- package/dist/codemode/ai.js +5 -5
- package/dist/{do-oauth-client-provider-DGc5pP0l.d.ts → do-oauth-client-provider-C2CHH5x-.d.ts} +1 -1
- package/dist/{do-oauth-client-provider-CswoD5Lu.js → do-oauth-client-provider-CwqK5SXm.js} +2 -1
- package/dist/do-oauth-client-provider-CwqK5SXm.js.map +1 -0
- package/dist/{index-DhJCaDWd.d.ts → index-BUle9RiP.d.ts} +2 -2
- package/dist/{index-DFqsR7mb.d.ts → index-BvEldExU.d.ts} +53 -26
- package/dist/index.d.ts +6 -6
- package/dist/index.js +5 -5
- package/dist/mcp/client.d.ts +4 -4
- package/dist/mcp/client.js +2 -1
- package/dist/mcp/do-oauth-client-provider.d.ts +1 -1
- package/dist/mcp/do-oauth-client-provider.js +1 -1
- package/dist/mcp/index.d.ts +75 -36
- package/dist/mcp/index.js +99 -21
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/x402.js +10 -6
- package/dist/mcp/x402.js.map +1 -1
- package/dist/{mcp-Dw5vDrY8.d.ts → mcp-BwPscEiF.d.ts} +1 -1
- package/dist/observability/index.d.ts +2 -2
- package/dist/observability/index.js +5 -5
- package/dist/{react-NCPvtyCY.d.ts → react-Ccc1FohP.d.ts} +33 -35
- package/dist/react.d.ts +9 -9
- package/dist/react.js +2 -2
- package/dist/react.js.map +1 -1
- package/dist/{serializable-CymX8ovI.d.ts → serializable-faDkMCai.d.ts} +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/{src-Dz0H9hSU.js → src-D_KKH_4c.js} +123 -139
- package/dist/src-D_KKH_4c.js.map +1 -0
- package/package.json +53 -38
- package/dist/ai-types-B3aQaFv3.js.map +0 -1
- package/dist/client-9Ld2_lnt.js +0 -786
- package/dist/client-9Ld2_lnt.js.map +0 -1
- package/dist/client-Csp_m13H.d.ts +0 -5315
- package/dist/do-oauth-client-provider-CswoD5Lu.js.map +0 -1
- package/dist/src-Dz0H9hSU.js.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { t as MessageType } from "./ai-types-
|
|
2
|
-
import { r as camelCaseToKebabCase } from "./client-
|
|
3
|
-
import {
|
|
4
|
-
import { t as DurableObjectOAuthClientProvider } from "./do-oauth-client-provider-
|
|
1
|
+
import { t as MessageType } from "./ai-types-CrMqkwc_.js";
|
|
2
|
+
import { r as camelCaseToKebabCase } from "./client-B3SR12TQ.js";
|
|
3
|
+
import { i as DisposableStore, r as MCPConnectionState, t as MCPClientManager } from "./client-BZq9qau2.js";
|
|
4
|
+
import { t as DurableObjectOAuthClientProvider } from "./do-oauth-client-provider-CwqK5SXm.js";
|
|
5
5
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
6
|
import { parseCronExpression } from "cron-schedule";
|
|
7
7
|
import { nanoid } from "nanoid";
|
|
@@ -153,9 +153,8 @@ var Agent = class Agent extends Server {
|
|
|
153
153
|
super(ctx, env);
|
|
154
154
|
this._state = DEFAULT_STATE;
|
|
155
155
|
this._disposables = new DisposableStore();
|
|
156
|
-
this.
|
|
156
|
+
this._destroyed = false;
|
|
157
157
|
this._ParentClass = Object.getPrototypeOf(this).constructor;
|
|
158
|
-
this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
159
158
|
this.initialState = DEFAULT_STATE;
|
|
160
159
|
this.observability = genericObservability;
|
|
161
160
|
this._flushingQueue = false;
|
|
@@ -193,27 +192,37 @@ var Agent = class Agent extends Server {
|
|
|
193
192
|
}
|
|
194
193
|
});
|
|
195
194
|
if (row.type === "cron") {
|
|
195
|
+
if (this._destroyed) return;
|
|
196
196
|
const nextExecutionTime = getNextCronTime(row.cron);
|
|
197
197
|
const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
|
|
198
198
|
this.sql`
|
|
199
199
|
UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
|
|
200
200
|
`;
|
|
201
|
-
} else
|
|
201
|
+
} else {
|
|
202
|
+
if (this._destroyed) return;
|
|
203
|
+
this.sql`
|
|
202
204
|
DELETE FROM cf_agents_schedules WHERE id = ${row.id}
|
|
203
205
|
`;
|
|
206
|
+
}
|
|
204
207
|
}
|
|
208
|
+
if (this._destroyed) return;
|
|
205
209
|
await this._scheduleNextAlarm();
|
|
206
210
|
};
|
|
207
211
|
if (!wrappedClasses.has(this.constructor)) {
|
|
208
212
|
this._autoWrapCustomMethods();
|
|
209
213
|
wrappedClasses.add(this.constructor);
|
|
210
214
|
}
|
|
211
|
-
this.
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
215
|
+
this.sql`
|
|
216
|
+
CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
|
|
217
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
218
|
+
name TEXT NOT NULL,
|
|
219
|
+
server_url TEXT NOT NULL,
|
|
220
|
+
callback_url TEXT NOT NULL,
|
|
221
|
+
client_id TEXT,
|
|
222
|
+
auth_url TEXT,
|
|
223
|
+
server_options TEXT
|
|
224
|
+
)
|
|
225
|
+
`;
|
|
217
226
|
this.sql`
|
|
218
227
|
CREATE TABLE IF NOT EXISTS cf_agents_state (
|
|
219
228
|
id TEXT PRIMARY KEY NOT NULL,
|
|
@@ -228,34 +237,25 @@ var Agent = class Agent extends Server {
|
|
|
228
237
|
created_at INTEGER DEFAULT (unixepoch())
|
|
229
238
|
)
|
|
230
239
|
`;
|
|
231
|
-
this.ctx.blockConcurrencyWhile(async () => {
|
|
232
|
-
return this._tryCatch(async () => {
|
|
233
|
-
this.sql`
|
|
234
|
-
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
235
|
-
id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
|
|
236
|
-
callback TEXT,
|
|
237
|
-
payload TEXT,
|
|
238
|
-
type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
|
|
239
|
-
time INTEGER,
|
|
240
|
-
delayInSeconds INTEGER,
|
|
241
|
-
cron TEXT,
|
|
242
|
-
created_at INTEGER DEFAULT (unixepoch())
|
|
243
|
-
)
|
|
244
|
-
`;
|
|
245
|
-
await this.alarm();
|
|
246
|
-
});
|
|
247
|
-
});
|
|
248
240
|
this.sql`
|
|
249
|
-
CREATE TABLE IF NOT EXISTS
|
|
250
|
-
id TEXT PRIMARY KEY NOT NULL,
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
241
|
+
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
242
|
+
id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
|
|
243
|
+
callback TEXT,
|
|
244
|
+
payload TEXT,
|
|
245
|
+
type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
|
|
246
|
+
time INTEGER,
|
|
247
|
+
delayInSeconds INTEGER,
|
|
248
|
+
cron TEXT,
|
|
249
|
+
created_at INTEGER DEFAULT (unixepoch())
|
|
257
250
|
)
|
|
258
251
|
`;
|
|
252
|
+
this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1", { storage: this.ctx.storage });
|
|
253
|
+
this._disposables.add(this.mcp.onServerStateChanged(async () => {
|
|
254
|
+
this.broadcastMcpServers();
|
|
255
|
+
}));
|
|
256
|
+
this._disposables.add(this.mcp.onObservabilityEvent((event) => {
|
|
257
|
+
this.observability?.emit(event);
|
|
258
|
+
}));
|
|
259
259
|
const _onRequest = this.onRequest.bind(this);
|
|
260
260
|
this.onRequest = (request) => {
|
|
261
261
|
return agentContext.run({
|
|
@@ -264,17 +264,9 @@ var Agent = class Agent extends Server {
|
|
|
264
264
|
request,
|
|
265
265
|
email: void 0
|
|
266
266
|
}, async () => {
|
|
267
|
-
await this.
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
this.broadcastMcpServers();
|
|
271
|
-
if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
|
|
272
|
-
console.error("Background connection failed:", error);
|
|
273
|
-
}).finally(() => {
|
|
274
|
-
this.broadcastMcpServers();
|
|
275
|
-
});
|
|
276
|
-
return this.handleOAuthCallbackResponse(result, request);
|
|
277
|
-
}
|
|
267
|
+
await this.mcp.ensureJsonSchema();
|
|
268
|
+
const oauthResponse = await this.handleMcpOAuthCallback(request);
|
|
269
|
+
if (oauthResponse) return oauthResponse;
|
|
278
270
|
return this._tryCatch(() => _onRequest(request));
|
|
279
271
|
});
|
|
280
272
|
};
|
|
@@ -286,6 +278,7 @@ var Agent = class Agent extends Server {
|
|
|
286
278
|
request: void 0,
|
|
287
279
|
email: void 0
|
|
288
280
|
}, async () => {
|
|
281
|
+
await this.mcp.ensureJsonSchema();
|
|
289
282
|
if (typeof message !== "string") return this._tryCatch(() => _onMessage(connection, message));
|
|
290
283
|
let parsed;
|
|
291
284
|
try {
|
|
@@ -350,7 +343,7 @@ var Agent = class Agent extends Server {
|
|
|
350
343
|
connection,
|
|
351
344
|
request: ctx$1.request,
|
|
352
345
|
email: void 0
|
|
353
|
-
}, () => {
|
|
346
|
+
}, async () => {
|
|
354
347
|
if (this.state) connection.send(JSON.stringify({
|
|
355
348
|
state: this.state,
|
|
356
349
|
type: MessageType.CF_AGENT_STATE
|
|
@@ -378,7 +371,7 @@ var Agent = class Agent extends Server {
|
|
|
378
371
|
email: void 0
|
|
379
372
|
}, async () => {
|
|
380
373
|
await this._tryCatch(async () => {
|
|
381
|
-
await this.
|
|
374
|
+
await this.mcp.restoreConnectionsFromStorage(this.name);
|
|
382
375
|
this.broadcastMcpServers();
|
|
383
376
|
return _onStart(props);
|
|
384
377
|
});
|
|
@@ -785,7 +778,7 @@ var Agent = class Agent extends Server {
|
|
|
785
778
|
async _scheduleNextAlarm() {
|
|
786
779
|
const result = this.sql`
|
|
787
780
|
SELECT time FROM cf_agents_schedules
|
|
788
|
-
WHERE time
|
|
781
|
+
WHERE time >= ${Math.floor(Date.now() / 1e3)}
|
|
789
782
|
ORDER BY time ASC
|
|
790
783
|
LIMIT 1
|
|
791
784
|
`;
|
|
@@ -799,15 +792,18 @@ var Agent = class Agent extends Server {
|
|
|
799
792
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
800
793
|
*/
|
|
801
794
|
async destroy() {
|
|
795
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
802
796
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
803
797
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
804
|
-
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
805
798
|
this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
|
|
806
799
|
await this.ctx.storage.deleteAlarm();
|
|
807
800
|
await this.ctx.storage.deleteAll();
|
|
808
801
|
this._disposables.dispose();
|
|
809
|
-
await this.mcp.dispose
|
|
810
|
-
this.
|
|
802
|
+
await this.mcp.dispose();
|
|
803
|
+
this._destroyed = true;
|
|
804
|
+
setTimeout(() => {
|
|
805
|
+
this.ctx.abort("destroyed");
|
|
806
|
+
}, 0);
|
|
811
807
|
this.observability?.emit({
|
|
812
808
|
displayMessage: "Agent destroyed",
|
|
813
809
|
id: nanoid(),
|
|
@@ -823,43 +819,6 @@ var Agent = class Agent extends Server {
|
|
|
823
819
|
_isCallable(method) {
|
|
824
820
|
return callableMetadata.has(this[method]);
|
|
825
821
|
}
|
|
826
|
-
async _ensureMcpStateRestored() {
|
|
827
|
-
if (this._mcpStateRestored) return;
|
|
828
|
-
this._mcpStateRestored = true;
|
|
829
|
-
const servers = this.sql`
|
|
830
|
-
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options
|
|
831
|
-
FROM cf_agents_mcp_servers
|
|
832
|
-
`;
|
|
833
|
-
if (!servers || !Array.isArray(servers) || servers.length === 0) return;
|
|
834
|
-
for (const server of servers) if (server.callback_url) this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);
|
|
835
|
-
for (const server of servers) if (!!server.auth_url) {
|
|
836
|
-
const authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, server.callback_url);
|
|
837
|
-
authProvider.serverId = server.id;
|
|
838
|
-
if (server.client_id) authProvider.clientId = server.client_id;
|
|
839
|
-
const parsedOptions = server.server_options ? JSON.parse(server.server_options) : void 0;
|
|
840
|
-
const conn = new MCPClientConnection(new URL(server.server_url), {
|
|
841
|
-
name: this.name,
|
|
842
|
-
version: "1.0.0"
|
|
843
|
-
}, {
|
|
844
|
-
client: parsedOptions?.client ?? {},
|
|
845
|
-
transport: {
|
|
846
|
-
...parsedOptions?.transport ?? {},
|
|
847
|
-
type: parsedOptions?.transport?.type ?? "auto",
|
|
848
|
-
authProvider
|
|
849
|
-
}
|
|
850
|
-
});
|
|
851
|
-
conn.connectionState = "authenticating";
|
|
852
|
-
this.mcp.mcpConnections[server.id] = conn;
|
|
853
|
-
} else {
|
|
854
|
-
const parsedOptions = server.server_options ? JSON.parse(server.server_options) : void 0;
|
|
855
|
-
this._connectToMcpServerInternal(server.name, server.server_url, server.callback_url, parsedOptions, {
|
|
856
|
-
id: server.id,
|
|
857
|
-
oauthClientId: server.client_id ?? void 0
|
|
858
|
-
}).catch((error) => {
|
|
859
|
-
console.error(`Error restoring ${server.id}:`, error);
|
|
860
|
-
});
|
|
861
|
-
}
|
|
862
|
-
}
|
|
863
822
|
/**
|
|
864
823
|
* Connect to a new MCP Server
|
|
865
824
|
*
|
|
@@ -868,7 +827,8 @@ var Agent = class Agent extends Server {
|
|
|
868
827
|
* @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
|
|
869
828
|
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
870
829
|
* @param options MCP client and transport options
|
|
871
|
-
* @returns authUrl
|
|
830
|
+
* @returns Server id and state - either "authenticating" with authUrl, or "ready"
|
|
831
|
+
* @throws If connection or discovery fails
|
|
872
832
|
*/
|
|
873
833
|
async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
|
|
874
834
|
let resolvedCallbackHost = callbackHost;
|
|
@@ -879,29 +839,10 @@ var Agent = class Agent extends Server {
|
|
|
879
839
|
resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
|
|
880
840
|
}
|
|
881
841
|
const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
INSERT
|
|
885
|
-
OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
886
|
-
VALUES (
|
|
887
|
-
${result.id},
|
|
888
|
-
${serverName},
|
|
889
|
-
${url},
|
|
890
|
-
${result.clientId ?? null},
|
|
891
|
-
${result.authUrl ?? null},
|
|
892
|
-
${callbackUrl},
|
|
893
|
-
${options ? JSON.stringify(options) : null}
|
|
894
|
-
);
|
|
895
|
-
`;
|
|
896
|
-
this.broadcastMcpServers();
|
|
897
|
-
return result;
|
|
898
|
-
}
|
|
899
|
-
async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
|
|
842
|
+
await this.mcp.ensureJsonSchema();
|
|
843
|
+
const id = nanoid(8);
|
|
900
844
|
const authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);
|
|
901
|
-
|
|
902
|
-
authProvider.serverId = reconnect.id;
|
|
903
|
-
if (reconnect.oauthClientId) authProvider.clientId = reconnect.oauthClientId;
|
|
904
|
-
}
|
|
845
|
+
authProvider.serverId = id;
|
|
905
846
|
const transportType = options?.transport?.type ?? "auto";
|
|
906
847
|
let headerTransportOpts = {};
|
|
907
848
|
if (options?.transport?.headers) headerTransportOpts = {
|
|
@@ -911,28 +852,33 @@ var Agent = class Agent extends Server {
|
|
|
911
852
|
}) },
|
|
912
853
|
requestInit: { headers: options?.transport?.headers }
|
|
913
854
|
};
|
|
914
|
-
|
|
855
|
+
await this.mcp.registerServer(id, {
|
|
856
|
+
url,
|
|
857
|
+
name: serverName,
|
|
858
|
+
callbackUrl,
|
|
915
859
|
client: options?.client,
|
|
916
|
-
reconnect,
|
|
917
860
|
transport: {
|
|
918
861
|
...headerTransportOpts,
|
|
919
862
|
authProvider,
|
|
920
863
|
type: transportType
|
|
921
864
|
}
|
|
922
865
|
});
|
|
866
|
+
const result = await this.mcp.connectToServer(id);
|
|
867
|
+
if (result.state === MCPConnectionState.FAILED) throw new Error(`Failed to connect to MCP server at ${url}: ${result.error}`);
|
|
868
|
+
if (result.state === MCPConnectionState.AUTHENTICATING) return {
|
|
869
|
+
id,
|
|
870
|
+
state: result.state,
|
|
871
|
+
authUrl: result.authUrl
|
|
872
|
+
};
|
|
873
|
+
const discoverResult = await this.mcp.discoverIfConnected(id);
|
|
874
|
+
if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover MCP server capabilities: ${discoverResult.error}`);
|
|
923
875
|
return {
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
id
|
|
876
|
+
id,
|
|
877
|
+
state: MCPConnectionState.READY
|
|
927
878
|
};
|
|
928
879
|
}
|
|
929
880
|
async removeMcpServer(id) {
|
|
930
|
-
this.mcp.
|
|
931
|
-
this.mcp.unregisterCallbackUrl(id);
|
|
932
|
-
this.sql`
|
|
933
|
-
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
934
|
-
`;
|
|
935
|
-
this.broadcastMcpServers();
|
|
881
|
+
await this.mcp.removeServer(id);
|
|
936
882
|
}
|
|
937
883
|
getMcpServers() {
|
|
938
884
|
const mcpState = {
|
|
@@ -941,18 +887,18 @@ var Agent = class Agent extends Server {
|
|
|
941
887
|
servers: {},
|
|
942
888
|
tools: this.mcp.listTools()
|
|
943
889
|
};
|
|
944
|
-
const servers = this.
|
|
945
|
-
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
946
|
-
`;
|
|
890
|
+
const servers = this.mcp.listServers();
|
|
947
891
|
if (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {
|
|
948
892
|
const serverConn = this.mcp.mcpConnections[server.id];
|
|
893
|
+
let defaultState = "not-connected";
|
|
894
|
+
if (!serverConn && server.auth_url) defaultState = "authenticating";
|
|
949
895
|
mcpState.servers[server.id] = {
|
|
950
896
|
auth_url: server.auth_url,
|
|
951
897
|
capabilities: serverConn?.serverCapabilities ?? null,
|
|
952
898
|
instructions: serverConn?.instructions ?? null,
|
|
953
899
|
name: server.name,
|
|
954
900
|
server_url: server.server_url,
|
|
955
|
-
state: serverConn?.connectionState ??
|
|
901
|
+
state: serverConn?.connectionState ?? defaultState
|
|
956
902
|
};
|
|
957
903
|
}
|
|
958
904
|
return mcpState;
|
|
@@ -964,6 +910,28 @@ var Agent = class Agent extends Server {
|
|
|
964
910
|
}));
|
|
965
911
|
}
|
|
966
912
|
/**
|
|
913
|
+
* Handle MCP OAuth callback request if it's an OAuth callback.
|
|
914
|
+
*
|
|
915
|
+
* This method encapsulates the entire OAuth callback flow:
|
|
916
|
+
* 1. Checks if the request is an MCP OAuth callback
|
|
917
|
+
* 2. Processes the OAuth code exchange
|
|
918
|
+
* 3. Establishes the connection if successful
|
|
919
|
+
* 4. Broadcasts MCP server state updates
|
|
920
|
+
* 5. Returns the appropriate HTTP response
|
|
921
|
+
*
|
|
922
|
+
* @param request The incoming HTTP request
|
|
923
|
+
* @returns Response if this was an OAuth callback, null otherwise
|
|
924
|
+
*/
|
|
925
|
+
async handleMcpOAuthCallback(request) {
|
|
926
|
+
if (!this.mcp.isCallbackRequest(request)) return null;
|
|
927
|
+
const result = await this.mcp.handleCallbackRequest(request);
|
|
928
|
+
if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
|
|
929
|
+
console.error("[Agent handleMcpOAuthCallback] Connection establishment failed:", error);
|
|
930
|
+
});
|
|
931
|
+
this.broadcastMcpServers();
|
|
932
|
+
return this.handleOAuthCallbackResponse(result, request);
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
967
935
|
* Handle OAuth callback response using MCPClientManager configuration
|
|
968
936
|
* @param result OAuth callback result
|
|
969
937
|
* @param request The original request (needed for base URL)
|
|
@@ -972,10 +940,21 @@ var Agent = class Agent extends Server {
|
|
|
972
940
|
handleOAuthCallbackResponse(result, request) {
|
|
973
941
|
const config = this.mcp.getOAuthCallbackConfig();
|
|
974
942
|
if (config?.customHandler) return config.customHandler(result);
|
|
975
|
-
|
|
976
|
-
if (config?.
|
|
977
|
-
|
|
978
|
-
|
|
943
|
+
const baseOrigin = new URL(request.url).origin;
|
|
944
|
+
if (config?.successRedirect && result.authSuccess) try {
|
|
945
|
+
return Response.redirect(new URL(config.successRedirect, baseOrigin).href);
|
|
946
|
+
} catch (e) {
|
|
947
|
+
console.error("Invalid successRedirect URL:", config.successRedirect, e);
|
|
948
|
+
return Response.redirect(baseOrigin);
|
|
949
|
+
}
|
|
950
|
+
if (config?.errorRedirect && !result.authSuccess) try {
|
|
951
|
+
const errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`;
|
|
952
|
+
return Response.redirect(new URL(errorUrl, baseOrigin).href);
|
|
953
|
+
} catch (e) {
|
|
954
|
+
console.error("Invalid errorRedirect URL:", config.errorRedirect, e);
|
|
955
|
+
return Response.redirect(baseOrigin);
|
|
956
|
+
}
|
|
957
|
+
return Response.redirect(baseOrigin);
|
|
979
958
|
}
|
|
980
959
|
};
|
|
981
960
|
const wrappedClasses = /* @__PURE__ */ new Set();
|
|
@@ -1001,10 +980,15 @@ async function routeAgentRequest(request, env, options) {
|
|
|
1001
980
|
prefix: "agents",
|
|
1002
981
|
...options
|
|
1003
982
|
});
|
|
1004
|
-
if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket")
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
983
|
+
if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
|
|
984
|
+
const newHeaders = new Headers(response.headers);
|
|
985
|
+
for (const [key, value] of Object.entries(corsHeaders)) newHeaders.set(key, value);
|
|
986
|
+
response = new Response(response.body, {
|
|
987
|
+
status: response.status,
|
|
988
|
+
statusText: response.statusText,
|
|
989
|
+
headers: newHeaders
|
|
990
|
+
});
|
|
991
|
+
}
|
|
1008
992
|
return response;
|
|
1009
993
|
}
|
|
1010
994
|
/**
|
|
@@ -1197,4 +1181,4 @@ var StreamingResponse = class {
|
|
|
1197
1181
|
|
|
1198
1182
|
//#endregion
|
|
1199
1183
|
export { createCatchAllEmailResolver as a, getCurrentAgent as c, unstable_callable as d, genericObservability as f, createAddressBasedEmailResolver as i, routeAgentEmail as l, StreamingResponse as n, createHeaderBasedEmailResolver as o, callable as r, getAgentByName as s, Agent as t, routeAgentRequest as u };
|
|
1200
|
-
//# sourceMappingURL=src-
|
|
1184
|
+
//# sourceMappingURL=src-D_KKH_4c.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-D_KKH_4c.js","names":["genericObservability: Observability","parsed: unknown","response: RPCResponse","ctx","proto","theError: unknown","schedule: Schedule<T>","transportType: TransportType","headerTransportOpts: SSEClientTransportOptions","url","mcpState: MCPServersState","defaultState: \"authenticating\" | \"not-connected\"","agentId","map: Record<string, unknown>","serialisableEmail: AgentEmail","chunks: Uint8Array[]","options"],"sources":["../src/observability/index.ts","../src/index.ts"],"sourcesContent":["import { getCurrentAgent } from \"../index\";\nimport type { AgentObservabilityEvent } from \"./agent\";\nimport type { MCPObservabilityEvent } from \"./mcp\";\n\n/**\n * Union of all observability event types from different domains\n */\nexport type ObservabilityEvent =\n | AgentObservabilityEvent\n | MCPObservabilityEvent;\n\nexport interface Observability {\n /**\n * Emit an event for the Agent's observability implementation to handle.\n * @param event - The event to emit\n * @param ctx - The execution context of the invocation (optional)\n */\n emit(event: ObservabilityEvent, ctx?: DurableObjectState): void;\n}\n\n/**\n * A generic observability implementation that logs events to the console.\n */\nexport const genericObservability: Observability = {\n emit(event) {\n // In local mode, we display a pretty-print version of the event for easier debugging.\n if (isLocalMode()) {\n console.log(event.displayMessage);\n return;\n }\n\n console.log(event);\n }\n};\n\nlet localMode = false;\n\nfunction isLocalMode() {\n if (localMode) {\n return true;\n }\n const { request } = getCurrentAgent();\n if (!request) {\n return false;\n }\n\n const url = new URL(request.url);\n localMode = url.hostname === \"localhost\";\n return localMode;\n}\n","import type { env } from \"cloudflare:workers\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nimport type {\n Prompt,\n Resource,\n ServerCapabilities,\n Tool\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { parseCronExpression } from \"cron-schedule\";\nimport { nanoid } from \"nanoid\";\nimport { EmailMessage } from \"cloudflare:email\";\nimport {\n type Connection,\n type ConnectionContext,\n type PartyServerOptions,\n Server,\n type WSMessage,\n getServerByName,\n routePartykitRequest\n} from \"partyserver\";\nimport { camelCaseToKebabCase } from \"./client\";\nimport { MCPClientManager, type MCPClientOAuthResult } from \"./mcp/client\";\nimport { MCPConnectionState } from \"./mcp/client-connection\";\nimport { DurableObjectOAuthClientProvider } from \"./mcp/do-oauth-client-provider\";\nimport type { TransportType } from \"./mcp/types\";\nimport { genericObservability, type Observability } from \"./observability\";\nimport { DisposableStore } from \"./core/events\";\nimport { MessageType } from \"./ai-types\";\n\nexport type { Connection, ConnectionContext, WSMessage } from \"partyserver\";\n\n/**\n * RPC request message from client\n */\nexport type RPCRequest = {\n type: \"rpc\";\n id: string;\n method: string;\n args: unknown[];\n};\n\n/**\n * State update message from client\n */\nexport type StateUpdateMessage = {\n type: MessageType.CF_AGENT_STATE;\n state: unknown;\n};\n\n/**\n * RPC response message to client\n */\nexport type RPCResponse = {\n type: MessageType.RPC;\n id: string;\n} & (\n | {\n success: true;\n result: unknown;\n done?: false;\n }\n | {\n success: true;\n result: unknown;\n done: true;\n }\n | {\n success: false;\n error: string;\n }\n);\n\n/**\n * Type guard for RPC request messages\n */\nfunction isRPCRequest(msg: unknown): msg is RPCRequest {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === MessageType.RPC &&\n \"id\" in msg &&\n typeof msg.id === \"string\" &&\n \"method\" in msg &&\n typeof msg.method === \"string\" &&\n \"args\" in msg &&\n Array.isArray((msg as RPCRequest).args)\n );\n}\n\n/**\n * Type guard for state update messages\n */\nfunction isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === MessageType.CF_AGENT_STATE &&\n \"state\" in msg\n );\n}\n\n/**\n * Metadata for a callable method\n */\nexport type CallableMetadata = {\n /** Optional description of what the method does */\n description?: string;\n /** Whether the method supports streaming responses */\n streaming?: boolean;\n};\n\nconst callableMetadata = new Map<Function, CallableMetadata>();\n\n/**\n * Decorator that marks a method as callable by clients\n * @param metadata Optional metadata about the callable method\n */\nexport function callable(metadata: CallableMetadata = {}) {\n return function callableDecorator<This, Args extends unknown[], Return>(\n target: (this: This, ...args: Args) => Return,\n // biome-ignore lint/correctness/noUnusedFunctionParameters: later\n context: ClassMethodDecoratorContext\n ) {\n if (!callableMetadata.has(target)) {\n callableMetadata.set(target, metadata);\n }\n\n return target;\n };\n}\n\nlet didWarnAboutUnstableCallable = false;\n\n/**\n * Decorator that marks a method as callable by clients\n * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version\n * @param metadata Optional metadata about the callable method\n */\nexport const unstable_callable = (metadata: CallableMetadata = {}) => {\n if (!didWarnAboutUnstableCallable) {\n didWarnAboutUnstableCallable = true;\n console.warn(\n \"unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version.\"\n );\n }\n callable(metadata);\n};\n\nexport type QueueItem<T = string> = {\n id: string;\n payload: T;\n callback: keyof Agent<unknown>;\n created_at: number;\n};\n\n/**\n * Represents a scheduled task within an Agent\n * @template T Type of the payload data\n */\nexport type Schedule<T = string> = {\n /** Unique identifier for the schedule */\n id: string;\n /** Name of the method to be called */\n callback: string;\n /** Data to be passed to the callback */\n payload: T;\n} & (\n | {\n /** Type of schedule for one-time execution at a specific time */\n type: \"scheduled\";\n /** Timestamp when the task should execute */\n time: number;\n }\n | {\n /** Type of schedule for delayed execution */\n type: \"delayed\";\n /** Timestamp when the task should execute */\n time: number;\n /** Number of seconds to delay execution */\n delayInSeconds: number;\n }\n | {\n /** Type of schedule for recurring execution based on cron expression */\n type: \"cron\";\n /** Timestamp for the next execution */\n time: number;\n /** Cron expression defining the schedule */\n cron: string;\n }\n);\n\nfunction getNextCronTime(cron: string) {\n const interval = parseCronExpression(cron);\n return interval.getNextDate();\n}\n\nexport type { TransportType } from \"./mcp/types\";\n\n/**\n * MCP Server state update message from server -> Client\n */\nexport type MCPServerMessage = {\n type: MessageType.CF_AGENT_MCP_SERVERS;\n mcp: MCPServersState;\n};\n\nexport type MCPServersState = {\n servers: {\n [id: string]: MCPServer;\n };\n tools: (Tool & { serverId: string })[];\n prompts: (Prompt & { serverId: string })[];\n resources: (Resource & { serverId: string })[];\n};\n\nexport type MCPServer = {\n name: string;\n server_url: string;\n auth_url: string | null;\n // This state is specifically about the temporary process of getting a token (if needed).\n // Scope outside of that can't be relied upon because when the DO sleeps, there's no way\n // to communicate a change to a non-ready state.\n state: MCPConnectionState;\n instructions: string | null;\n capabilities: ServerCapabilities | null;\n};\nconst STATE_ROW_ID = \"cf_state_row_id\";\nconst STATE_WAS_CHANGED = \"cf_state_was_changed\";\n\nconst DEFAULT_STATE = {} as unknown;\n\nconst agentContext = new AsyncLocalStorage<{\n agent: Agent<unknown, unknown>;\n connection: Connection | undefined;\n request: Request | undefined;\n email: AgentEmail | undefined;\n}>();\n\nexport function getCurrentAgent<\n T extends Agent<unknown, unknown> = Agent<unknown, unknown>\n>(): {\n agent: T | undefined;\n connection: Connection | undefined;\n request: Request | undefined;\n email: AgentEmail | undefined;\n} {\n const store = agentContext.getStore() as\n | {\n agent: T;\n connection: Connection | undefined;\n request: Request | undefined;\n email: AgentEmail | undefined;\n }\n | undefined;\n if (!store) {\n return {\n agent: undefined,\n connection: undefined,\n request: undefined,\n email: undefined\n };\n }\n return store;\n}\n\n/**\n * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly\n * @param agent The agent instance\n * @param method The method to wrap\n * @returns A wrapped method that runs within the agent context\n */\n\n// biome-ignore lint/suspicious/noExplicitAny: I can't typescript\nfunction withAgentContext<T extends (...args: any[]) => any>(\n method: T\n): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {\n return function (...args: Parameters<T>): ReturnType<T> {\n const { connection, request, email, agent } = getCurrentAgent();\n\n if (agent === this) {\n // already wrapped, so we can just call the method\n return method.apply(this, args);\n }\n // not wrapped, so we need to wrap it\n return agentContext.run({ agent: this, connection, request, email }, () => {\n return method.apply(this, args);\n });\n };\n}\n\n/**\n * Base class for creating Agent implementations\n * @template Env Environment type containing bindings\n * @template State State type to store within the Agent\n */\nexport class Agent<\n Env = typeof env,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>\n> extends Server<Env, Props> {\n private _state = DEFAULT_STATE as State;\n private _disposables = new DisposableStore();\n private _destroyed = false;\n\n private _ParentClass: typeof Agent<Env, State> =\n Object.getPrototypeOf(this).constructor;\n\n readonly mcp: MCPClientManager;\n\n /**\n * Initial state for the Agent\n * Override to provide default state values\n */\n initialState: State = DEFAULT_STATE as State;\n\n /**\n * Current state of the Agent\n */\n get state(): State {\n if (this._state !== DEFAULT_STATE) {\n // state was previously set, and populated internal state\n return this._state;\n }\n // looks like this is the first time the state is being accessed\n // check if the state was set in a previous life\n const wasChanged = this.sql<{ state: \"true\" | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}\n `;\n\n // ok, let's pick up the actual state from the db\n const result = this.sql<{ state: State | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}\n `;\n\n if (\n wasChanged[0]?.state === \"true\" ||\n // we do this check for people who updated their code before we shipped wasChanged\n result[0]?.state\n ) {\n const state = result[0]?.state as string; // could be null?\n\n this._state = JSON.parse(state);\n return this._state;\n }\n\n // ok, this is the first time the state is being accessed\n // and the state was not set in a previous life\n // so we need to set the initial state (if provided)\n if (this.initialState === DEFAULT_STATE) {\n // no initial state provided, so we return undefined\n return undefined as State;\n }\n // initial state provided, so we set the state,\n // update db and return the initial state\n this.setState(this.initialState);\n return this.initialState;\n }\n\n /**\n * Agent configuration options\n */\n static options = {\n /** Whether the Agent should hibernate when inactive */\n hibernate: true // default to hibernate\n };\n\n /**\n * The observability implementation to use for the Agent\n */\n observability?: Observability = genericObservability;\n\n /**\n * Execute SQL queries against the Agent's database\n * @template T Type of the returned rows\n * @param strings SQL query template strings\n * @param values Values to be inserted into the query\n * @returns Array of query results\n */\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ) {\n let query = \"\";\n try {\n // Construct the SQL query with placeholders\n query = strings.reduce(\n (acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"),\n \"\"\n );\n\n // Execute the SQL query with the provided values\n return [...this.ctx.storage.sql.exec(query, ...values)] as T[];\n } catch (e) {\n console.error(`failed to execute sql query: ${query}`, e);\n throw this.onError(e);\n }\n }\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n\n if (!wrappedClasses.has(this.constructor)) {\n // Auto-wrap custom methods with agent context\n this._autoWrapCustomMethods();\n wrappedClasses.add(this.constructor);\n }\n\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (\n id TEXT PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n server_url TEXT NOT NULL,\n callback_url TEXT NOT NULL,\n client_id TEXT,\n auth_url TEXT,\n server_options TEXT\n )\n `;\n\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_state (\n id TEXT PRIMARY KEY NOT NULL,\n state TEXT\n )\n `;\n\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_queues (\n id TEXT PRIMARY KEY NOT NULL,\n payload TEXT,\n callback TEXT,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_schedules (\n id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),\n callback TEXT,\n payload TEXT,\n type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),\n time INTEGER,\n delayInSeconds INTEGER,\n cron TEXT,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\n // Initialize MCPClientManager AFTER tables are created\n this.mcp = new MCPClientManager(this._ParentClass.name, \"0.0.1\", {\n storage: this.ctx.storage\n });\n\n // Broadcast server state whenever MCP state changes (register, connect, OAuth, remove, etc.)\n this._disposables.add(\n this.mcp.onServerStateChanged(async () => {\n this.broadcastMcpServers();\n })\n );\n\n // Emit MCP observability events\n this._disposables.add(\n this.mcp.onObservabilityEvent((event) => {\n this.observability?.emit(event);\n })\n );\n\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = (request: Request) => {\n return agentContext.run(\n { agent: this, connection: undefined, request, email: undefined },\n async () => {\n // TODO: make zod/ai sdk more performant and remove this\n // Late initialization of jsonSchemaFn (needed for getAITools)\n await this.mcp.ensureJsonSchema();\n\n // Handle MCP OAuth callback if this is one\n const oauthResponse = await this.handleMcpOAuthCallback(request);\n if (oauthResponse) {\n return oauthResponse;\n }\n\n return this._tryCatch(() => _onRequest(request));\n }\n );\n };\n\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n return agentContext.run(\n { agent: this, connection, request: undefined, email: undefined },\n async () => {\n // TODO: make zod/ai sdk more performant and remove this\n // Late initialization of jsonSchemaFn (needed for getAITools)\n await this.mcp.ensureJsonSchema();\n if (typeof message !== \"string\") {\n return this._tryCatch(() => _onMessage(connection, message));\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(message);\n } catch (_e) {\n // silently fail and let the onMessage handler handle it\n return this._tryCatch(() => _onMessage(connection, message));\n }\n\n if (isStateUpdateMessage(parsed)) {\n this._setStateInternal(parsed.state as State, connection);\n return;\n }\n\n if (isRPCRequest(parsed)) {\n try {\n const { id, method, args } = parsed;\n\n // Check if method exists and is callable\n const methodFn = this[method as keyof this];\n if (typeof methodFn !== \"function\") {\n throw new Error(`Method ${method} does not exist`);\n }\n\n if (!this._isCallable(method)) {\n throw new Error(`Method ${method} is not callable`);\n }\n\n const metadata = callableMetadata.get(methodFn as Function);\n\n // For streaming methods, pass a StreamingResponse object\n if (metadata?.streaming) {\n const stream = new StreamingResponse(connection, id);\n await methodFn.apply(this, [stream, ...args]);\n return;\n }\n\n // For regular methods, execute and send response\n const result = await methodFn.apply(this, args);\n\n this.observability?.emit(\n {\n displayMessage: `RPC call to ${method}`,\n id: nanoid(),\n payload: {\n method,\n streaming: metadata?.streaming\n },\n timestamp: Date.now(),\n type: \"rpc\"\n },\n this.ctx\n );\n\n const response: RPCResponse = {\n done: true,\n id,\n result,\n success: true,\n type: MessageType.RPC\n };\n connection.send(JSON.stringify(response));\n } catch (e) {\n // Send error response\n const response: RPCResponse = {\n error:\n e instanceof Error ? e.message : \"Unknown error occurred\",\n id: parsed.id,\n success: false,\n type: MessageType.RPC\n };\n connection.send(JSON.stringify(response));\n console.error(\"RPC error:\", e);\n }\n return;\n }\n\n return this._tryCatch(() => _onMessage(connection, message));\n }\n );\n };\n\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = (connection: Connection, ctx: ConnectionContext) => {\n // TODO: This is a hack to ensure the state is sent after the connection is established\n // must fix this\n return agentContext.run(\n { agent: this, connection, request: ctx.request, email: undefined },\n async () => {\n if (this.state) {\n connection.send(\n JSON.stringify({\n state: this.state,\n type: MessageType.CF_AGENT_STATE\n })\n );\n }\n\n connection.send(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: MessageType.CF_AGENT_MCP_SERVERS\n })\n );\n\n this.observability?.emit(\n {\n displayMessage: \"Connection established\",\n id: nanoid(),\n payload: {\n connectionId: connection.id\n },\n timestamp: Date.now(),\n type: \"connect\"\n },\n this.ctx\n );\n return this._tryCatch(() => _onConnect(connection, ctx));\n }\n );\n };\n\n const _onStart = this.onStart.bind(this);\n this.onStart = async (props?: Props) => {\n return agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n await this._tryCatch(async () => {\n await this.mcp.restoreConnectionsFromStorage(this.name);\n this.broadcastMcpServers();\n return _onStart(props);\n });\n }\n );\n };\n }\n\n private _setStateInternal(\n state: State,\n source: Connection | \"server\" = \"server\"\n ) {\n this._state = state;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})\n `;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})\n `;\n this.broadcast(\n JSON.stringify({\n state: state,\n type: MessageType.CF_AGENT_STATE\n }),\n source !== \"server\" ? [source.id] : []\n );\n return this._tryCatch(() => {\n const { connection, request, email } = agentContext.getStore() || {};\n return agentContext.run(\n { agent: this, connection, request, email },\n async () => {\n this.observability?.emit(\n {\n displayMessage: \"State updated\",\n id: nanoid(),\n payload: {},\n timestamp: Date.now(),\n type: \"state:update\"\n },\n this.ctx\n );\n return this.onStateUpdate(state, source);\n }\n );\n });\n }\n\n /**\n * Update the Agent's state\n * @param state New state to set\n */\n setState(state: State) {\n this._setStateInternal(state, \"server\");\n }\n\n /**\n * Called when the Agent's state is updated\n * @param state Updated state\n * @param source Source of the state update (\"server\" or a client connection)\n */\n // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates\n }\n\n /**\n * Called when the Agent receives an email via routeAgentEmail()\n * Override this method to handle incoming emails\n * @param email Email message to process\n */\n async _onEmail(email: AgentEmail) {\n // nb: we use this roundabout way of getting to onEmail\n // because of https://github.com/cloudflare/workerd/issues/4499\n return agentContext.run(\n { agent: this, connection: undefined, request: undefined, email: email },\n async () => {\n if (\"onEmail\" in this && typeof this.onEmail === \"function\") {\n return this._tryCatch(() =>\n (this.onEmail as (email: AgentEmail) => Promise<void>)(email)\n );\n } else {\n console.log(\"Received email from:\", email.from, \"to:\", email.to);\n console.log(\"Subject:\", email.headers.get(\"subject\"));\n console.log(\n \"Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails\"\n );\n }\n }\n );\n }\n\n /**\n * Reply to an email\n * @param email The email to reply to\n * @param options Options for the reply\n * @returns void\n */\n async replyToEmail(\n email: AgentEmail,\n options: {\n fromName: string;\n subject?: string | undefined;\n body: string;\n contentType?: string;\n headers?: Record<string, string>;\n }\n ): Promise<void> {\n return this._tryCatch(async () => {\n const agentName = camelCaseToKebabCase(this._ParentClass.name);\n const agentId = this.name;\n\n const { createMimeMessage } = await import(\"mimetext\");\n const msg = createMimeMessage();\n msg.setSender({ addr: email.to, name: options.fromName });\n msg.setRecipient(email.from);\n msg.setSubject(\n options.subject || `Re: ${email.headers.get(\"subject\")}` || \"No subject\"\n );\n msg.addMessage({\n contentType: options.contentType || \"text/plain\",\n data: options.body\n });\n\n const domain = email.from.split(\"@\")[1];\n const messageId = `<${agentId}@${domain}>`;\n msg.setHeader(\"In-Reply-To\", email.headers.get(\"Message-ID\")!);\n msg.setHeader(\"Message-ID\", messageId);\n msg.setHeader(\"X-Agent-Name\", agentName);\n msg.setHeader(\"X-Agent-ID\", agentId);\n\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n msg.setHeader(key, value);\n }\n }\n await email.reply({\n from: email.to,\n raw: msg.asRaw(),\n to: email.from\n });\n });\n }\n\n private async _tryCatch<T>(fn: () => T | Promise<T>) {\n try {\n return await fn();\n } catch (e) {\n throw this.onError(e);\n }\n }\n\n /**\n * Automatically wrap custom methods with agent context\n * This ensures getCurrentAgent() works in all custom methods without decorators\n */\n private _autoWrapCustomMethods() {\n // Collect all methods from base prototypes (Agent and Server)\n const basePrototypes = [Agent.prototype, Server.prototype];\n const baseMethods = new Set<string>();\n for (const baseProto of basePrototypes) {\n let proto = baseProto;\n while (proto && proto !== Object.prototype) {\n const methodNames = Object.getOwnPropertyNames(proto);\n for (const methodName of methodNames) {\n baseMethods.add(methodName);\n }\n proto = Object.getPrototypeOf(proto);\n }\n }\n // Get all methods from the current instance's prototype chain\n let proto = Object.getPrototypeOf(this);\n let depth = 0;\n while (proto && proto !== Object.prototype && depth < 10) {\n const methodNames = Object.getOwnPropertyNames(proto);\n for (const methodName of methodNames) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);\n\n // Skip if it's a private method, a base method, a getter, or not a function,\n if (\n baseMethods.has(methodName) ||\n methodName.startsWith(\"_\") ||\n !descriptor ||\n !!descriptor.get ||\n typeof descriptor.value !== \"function\"\n ) {\n continue;\n }\n\n // Now, methodName is confirmed to be a custom method/function\n // Wrap the custom method with context\n const wrappedFunction = withAgentContext(\n // biome-ignore lint/suspicious/noExplicitAny: I can't typescript\n this[methodName as keyof this] as (...args: any[]) => any\n // biome-ignore lint/suspicious/noExplicitAny: I can't typescript\n ) as any;\n\n // if the method is callable, copy the metadata from the original method\n if (this._isCallable(methodName)) {\n callableMetadata.set(\n wrappedFunction,\n callableMetadata.get(this[methodName as keyof this] as Function)!\n );\n }\n\n // set the wrapped function on the prototype\n this.constructor.prototype[methodName as keyof this] = wrappedFunction;\n }\n\n proto = Object.getPrototypeOf(proto);\n depth++;\n }\n }\n\n override onError(\n connection: Connection,\n error: unknown\n ): void | Promise<void>;\n override onError(error: unknown): void | Promise<void>;\n override onError(connectionOrError: Connection | unknown, error?: unknown) {\n let theError: unknown;\n if (connectionOrError && error) {\n theError = error;\n // this is a websocket connection error\n console.error(\n \"Error on websocket connection:\",\n (connectionOrError as Connection).id,\n theError\n );\n console.error(\n \"Override onError(connection, error) to handle websocket connection errors\"\n );\n } else {\n theError = connectionOrError;\n // this is a server error\n console.error(\"Error on server:\", theError);\n console.error(\"Override onError(error) to handle server errors\");\n }\n throw theError;\n }\n\n /**\n * Render content (not implemented in base class)\n */\n render() {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Queue a task to be executed in the future\n * @param payload Payload to pass to the callback\n * @param callback Name of the method to call\n * @returns The ID of the queued task\n */\n async queue<T = unknown>(callback: keyof this, payload: T): Promise<string> {\n const id = nanoid(9);\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n\n if (typeof this[callback] !== \"function\") {\n throw new Error(`this.${callback} is not a function`);\n }\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)\n VALUES (${id}, ${JSON.stringify(payload)}, ${callback})\n `;\n\n void this._flushQueue().catch((e) => {\n console.error(\"Error flushing queue:\", e);\n });\n\n return id;\n }\n\n private _flushingQueue = false;\n\n private async _flushQueue() {\n if (this._flushingQueue) {\n return;\n }\n this._flushingQueue = true;\n while (true) {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues\n ORDER BY created_at ASC\n `;\n\n if (!result || result.length === 0) {\n break;\n }\n\n for (const row of result || []) {\n const callback = this[row.callback as keyof Agent<Env>];\n if (!callback) {\n console.error(`callback ${row.callback} not found`);\n continue;\n }\n const { connection, request, email } = agentContext.getStore() || {};\n await agentContext.run(\n {\n agent: this,\n connection,\n request,\n email\n },\n async () => {\n // TODO: add retries and backoff\n await (\n callback as (\n payload: unknown,\n queueItem: QueueItem<string>\n ) => Promise<void>\n ).bind(this)(JSON.parse(row.payload as string), row);\n await this.dequeue(row.id);\n }\n );\n }\n }\n this._flushingQueue = false;\n }\n\n /**\n * Dequeue a task by ID\n * @param id ID of the task to dequeue\n */\n async dequeue(id: string) {\n this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;\n }\n\n /**\n * Dequeue all tasks\n */\n async dequeueAll() {\n this.sql`DELETE FROM cf_agents_queues`;\n }\n\n /**\n * Dequeue all tasks by callback\n * @param callback Name of the callback to dequeue\n */\n async dequeueAllByCallback(callback: string) {\n this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;\n }\n\n /**\n * Get a queued task by ID\n * @param id ID of the task to get\n * @returns The task or undefined if not found\n */\n async getQueue(id: string): Promise<QueueItem<string> | undefined> {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues WHERE id = ${id}\n `;\n return result\n ? { ...result[0], payload: JSON.parse(result[0].payload) }\n : undefined;\n }\n\n /**\n * Get all queues by key and value\n * @param key Key to filter by\n * @param value Value to filter by\n * @returns Array of matching QueueItem objects\n */\n async getQueues(key: string, value: string): Promise<QueueItem<string>[]> {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues\n `;\n return result.filter((row) => JSON.parse(row.payload)[key] === value);\n }\n\n /**\n * Schedule a task to be executed in the future\n * @template T Type of the payload data\n * @param when When to execute the task (Date, seconds delay, or cron expression)\n * @param callback Name of the method to call\n * @param payload Data to pass to the callback\n * @returns Schedule object representing the scheduled task\n */\n async schedule<T = string>(\n when: Date | string | number,\n callback: keyof this,\n payload?: T\n ): Promise<Schedule<T>> {\n const id = nanoid(9);\n\n const emitScheduleCreate = (schedule: Schedule<T>) =>\n this.observability?.emit(\n {\n displayMessage: `Schedule ${schedule.id} created`,\n id: nanoid(),\n payload: {\n callback: callback as string,\n id: id\n },\n timestamp: Date.now(),\n type: \"schedule:create\"\n },\n this.ctx\n );\n\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n\n if (typeof this[callback] !== \"function\") {\n throw new Error(`this.${callback} is not a function`);\n }\n\n if (when instanceof Date) {\n const timestamp = Math.floor(when.getTime() / 1000);\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'scheduled', ${timestamp})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n id,\n payload: payload as T,\n time: timestamp,\n type: \"scheduled\"\n };\n\n emitScheduleCreate(schedule);\n\n return schedule;\n }\n if (typeof when === \"number\") {\n const time = new Date(Date.now() + when * 1000);\n const timestamp = Math.floor(time.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'delayed', ${when}, ${timestamp})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n delayInSeconds: when,\n id,\n payload: payload as T,\n time: timestamp,\n type: \"delayed\"\n };\n\n emitScheduleCreate(schedule);\n\n return schedule;\n }\n if (typeof when === \"string\") {\n const nextExecutionTime = getNextCronTime(when);\n const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'cron', ${when}, ${timestamp})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n cron: when,\n id,\n payload: payload as T,\n time: timestamp,\n type: \"cron\"\n };\n\n emitScheduleCreate(schedule);\n\n return schedule;\n }\n throw new Error(\"Invalid schedule type\");\n }\n\n /**\n * Get a scheduled task by ID\n * @template T Type of the payload data\n * @param id ID of the scheduled task\n * @returns The Schedule object or undefined if not found\n */\n async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE id = ${id}\n `;\n if (!result) {\n console.error(`schedule ${id} not found`);\n return undefined;\n }\n\n return { ...result[0], payload: JSON.parse(result[0].payload) as T };\n }\n\n /**\n * Get scheduled tasks matching the given criteria\n * @template T Type of the payload data\n * @param criteria Criteria to filter schedules\n * @returns Array of matching Schedule objects\n */\n getSchedules<T = string>(\n criteria: {\n id?: string;\n type?: \"scheduled\" | \"delayed\" | \"cron\";\n timeRange?: { start?: Date; end?: Date };\n } = {}\n ): Schedule<T>[] {\n let query = \"SELECT * FROM cf_agents_schedules WHERE 1=1\";\n const params = [];\n\n if (criteria.id) {\n query += \" AND id = ?\";\n params.push(criteria.id);\n }\n\n if (criteria.type) {\n query += \" AND type = ?\";\n params.push(criteria.type);\n }\n\n if (criteria.timeRange) {\n query += \" AND time >= ? AND time <= ?\";\n const start = criteria.timeRange.start || new Date(0);\n const end = criteria.timeRange.end || new Date(999999999999999);\n params.push(\n Math.floor(start.getTime() / 1000),\n Math.floor(end.getTime() / 1000)\n );\n }\n\n const result = this.ctx.storage.sql\n .exec(query, ...params)\n .toArray()\n .map((row) => ({\n ...row,\n payload: JSON.parse(row.payload as string) as T\n })) as Schedule<T>[];\n\n return result;\n }\n\n /**\n * Cancel a scheduled task\n * @param id ID of the task to cancel\n * @returns true if the task was cancelled, false otherwise\n */\n async cancelSchedule(id: string): Promise<boolean> {\n const schedule = await this.getSchedule(id);\n if (schedule) {\n this.observability?.emit(\n {\n displayMessage: `Schedule ${id} cancelled`,\n id: nanoid(),\n payload: {\n callback: schedule.callback,\n id: schedule.id\n },\n timestamp: Date.now(),\n type: \"schedule:cancel\"\n },\n this.ctx\n );\n }\n this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;\n\n await this._scheduleNextAlarm();\n return true;\n }\n\n private async _scheduleNextAlarm() {\n // Find the next schedule that needs to be executed\n const result = this.sql`\n SELECT time FROM cf_agents_schedules\n WHERE time >= ${Math.floor(Date.now() / 1000)}\n ORDER BY time ASC\n LIMIT 1\n `;\n if (!result) return;\n\n if (result.length > 0 && \"time\" in result[0]) {\n const nextTime = (result[0].time as number) * 1000;\n await this.ctx.storage.setAlarm(nextTime);\n }\n }\n\n /**\n * Method called when an alarm fires.\n * Executes any scheduled tasks that are due.\n *\n * @remarks\n * To schedule a task, please use the `this.schedule` method instead.\n * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}\n */\n public readonly alarm = async () => {\n const now = Math.floor(Date.now() / 1000);\n\n // Get all schedules that should be executed now\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE time <= ${now}\n `;\n\n if (result && Array.isArray(result)) {\n for (const row of result) {\n const callback = this[row.callback as keyof Agent<Env>];\n if (!callback) {\n console.error(`callback ${row.callback} not found`);\n continue;\n }\n await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n try {\n this.observability?.emit(\n {\n displayMessage: `Schedule ${row.id} executed`,\n id: nanoid(),\n payload: {\n callback: row.callback,\n id: row.id\n },\n timestamp: Date.now(),\n type: \"schedule:execute\"\n },\n this.ctx\n );\n\n await (\n callback as (\n payload: unknown,\n schedule: Schedule<unknown>\n ) => Promise<void>\n ).bind(this)(JSON.parse(row.payload as string), row);\n } catch (e) {\n console.error(`error executing callback \"${row.callback}\"`, e);\n }\n }\n );\n if (row.type === \"cron\") {\n if (this._destroyed) return;\n // Update next execution time for cron schedules\n const nextExecutionTime = getNextCronTime(row.cron);\n const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}\n `;\n } else {\n if (this._destroyed) return;\n // Delete one-time schedules after execution\n this.sql`\n DELETE FROM cf_agents_schedules WHERE id = ${row.id}\n `;\n }\n }\n }\n if (this._destroyed) return;\n\n // Schedule the next alarm\n await this._scheduleNextAlarm();\n };\n\n /**\n * Destroy the Agent, removing all state and scheduled tasks\n */\n async destroy() {\n // drop all tables\n this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;\n this.sql`DROP TABLE IF EXISTS cf_agents_state`;\n this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;\n this.sql`DROP TABLE IF EXISTS cf_agents_queues`;\n\n // delete all alarms\n await this.ctx.storage.deleteAlarm();\n await this.ctx.storage.deleteAll();\n\n this._disposables.dispose();\n await this.mcp.dispose();\n\n this._destroyed = true;\n\n // `ctx.abort` throws an uncatchable error, so we yield to the event loop\n // to avoid capturing it and let handlers finish cleaning up\n setTimeout(() => {\n this.ctx.abort(\"destroyed\");\n }, 0);\n\n this.observability?.emit(\n {\n displayMessage: \"Agent destroyed\",\n id: nanoid(),\n payload: {},\n timestamp: Date.now(),\n type: \"destroy\"\n },\n this.ctx\n );\n }\n\n /**\n * Get all methods marked as callable on this Agent\n * @returns A map of method names to their metadata\n */\n private _isCallable(method: string): boolean {\n return callableMetadata.has(this[method as keyof this] as Function);\n }\n\n /**\n * Connect to a new MCP Server\n *\n * @param serverName Name of the MCP server\n * @param url MCP Server SSE URL\n * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.\n * @param agentsPrefix agents routing prefix if not using `agents`\n * @param options MCP client and transport options\n * @returns Server id and state - either \"authenticating\" with authUrl, or \"ready\"\n * @throws If connection or discovery fails\n */\n async addMcpServer(\n serverName: string,\n url: string,\n callbackHost?: string,\n agentsPrefix = \"agents\",\n options?: {\n client?: ConstructorParameters<typeof Client>[1];\n transport?: {\n headers?: HeadersInit;\n type?: TransportType;\n };\n }\n ): Promise<\n | {\n id: string;\n state: typeof MCPConnectionState.AUTHENTICATING;\n authUrl: string;\n }\n | {\n id: string;\n state: typeof MCPConnectionState.READY;\n authUrl?: undefined;\n }\n > {\n // If callbackHost is not provided, derive it from the current request\n let resolvedCallbackHost = callbackHost;\n if (!resolvedCallbackHost) {\n const { request } = getCurrentAgent();\n if (!request) {\n throw new Error(\n \"callbackHost is required when not called within a request context\"\n );\n }\n\n // Extract the origin from the request\n const requestUrl = new URL(request.url);\n resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;\n }\n\n const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;\n\n // TODO: make zod/ai sdk more performant and remove this\n // Late initialization of jsonSchemaFn (needed for getAITools)\n await this.mcp.ensureJsonSchema();\n\n const id = nanoid(8);\n\n const authProvider = new DurableObjectOAuthClientProvider(\n this.ctx.storage,\n this.name,\n callbackUrl\n );\n authProvider.serverId = id;\n\n // Use the transport type specified in options, or default to \"auto\"\n const transportType: TransportType = options?.transport?.type ?? \"auto\";\n\n // allows passing through transport headers if necessary\n // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)\n let headerTransportOpts: SSEClientTransportOptions = {};\n if (options?.transport?.headers) {\n headerTransportOpts = {\n eventSourceInit: {\n fetch: (url, init) =>\n fetch(url, {\n ...init,\n headers: options?.transport?.headers\n })\n },\n requestInit: {\n headers: options?.transport?.headers\n }\n };\n }\n\n // Register server (also saves to storage)\n await this.mcp.registerServer(id, {\n url,\n name: serverName,\n callbackUrl,\n client: options?.client,\n transport: {\n ...headerTransportOpts,\n authProvider,\n type: transportType\n }\n });\n\n const result = await this.mcp.connectToServer(id);\n\n if (result.state === MCPConnectionState.FAILED) {\n // Server stays in storage so user can retry via connectToServer(id)\n throw new Error(\n `Failed to connect to MCP server at ${url}: ${result.error}`\n );\n }\n\n if (result.state === MCPConnectionState.AUTHENTICATING) {\n return { id, state: result.state, authUrl: result.authUrl };\n }\n\n // State is CONNECTED - discover capabilities\n const discoverResult = await this.mcp.discoverIfConnected(id);\n\n if (discoverResult && !discoverResult.success) {\n // Server stays in storage - connection is still valid, user can retry discovery\n throw new Error(\n `Failed to discover MCP server capabilities: ${discoverResult.error}`\n );\n }\n\n return { id, state: MCPConnectionState.READY };\n }\n\n async removeMcpServer(id: string) {\n await this.mcp.removeServer(id);\n }\n\n getMcpServers(): MCPServersState {\n const mcpState: MCPServersState = {\n prompts: this.mcp.listPrompts(),\n resources: this.mcp.listResources(),\n servers: {},\n tools: this.mcp.listTools()\n };\n\n const servers = this.mcp.listServers();\n\n if (servers && Array.isArray(servers) && servers.length > 0) {\n for (const server of servers) {\n const serverConn = this.mcp.mcpConnections[server.id];\n\n // Determine the default state when no connection exists\n let defaultState: \"authenticating\" | \"not-connected\" = \"not-connected\";\n if (!serverConn && server.auth_url) {\n // If there's an auth_url but no connection, it's waiting for OAuth\n defaultState = \"authenticating\";\n }\n\n mcpState.servers[server.id] = {\n auth_url: server.auth_url,\n capabilities: serverConn?.serverCapabilities ?? null,\n instructions: serverConn?.instructions ?? null,\n name: server.name,\n server_url: server.server_url,\n state: serverConn?.connectionState ?? defaultState\n };\n }\n }\n\n return mcpState;\n }\n\n private broadcastMcpServers() {\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: MessageType.CF_AGENT_MCP_SERVERS\n })\n );\n }\n\n /**\n * Handle MCP OAuth callback request if it's an OAuth callback.\n *\n * This method encapsulates the entire OAuth callback flow:\n * 1. Checks if the request is an MCP OAuth callback\n * 2. Processes the OAuth code exchange\n * 3. Establishes the connection if successful\n * 4. Broadcasts MCP server state updates\n * 5. Returns the appropriate HTTP response\n *\n * @param request The incoming HTTP request\n * @returns Response if this was an OAuth callback, null otherwise\n */\n private async handleMcpOAuthCallback(\n request: Request\n ): Promise<Response | null> {\n // Check if this is an OAuth callback request\n const isCallback = this.mcp.isCallbackRequest(request);\n if (!isCallback) {\n return null;\n }\n\n // Handle the OAuth callback (exchanges code for token, clears OAuth credentials from storage)\n // This fires onServerStateChanged event which triggers broadcast\n const result = await this.mcp.handleCallbackRequest(request);\n\n // If auth was successful, establish the connection in the background\n if (result.authSuccess) {\n this.mcp.establishConnection(result.serverId).catch((error) => {\n console.error(\n \"[Agent handleMcpOAuthCallback] Connection establishment failed:\",\n error\n );\n });\n }\n\n this.broadcastMcpServers();\n\n // Return the HTTP response for the OAuth callback\n return this.handleOAuthCallbackResponse(result, request);\n }\n\n /**\n * Handle OAuth callback response using MCPClientManager configuration\n * @param result OAuth callback result\n * @param request The original request (needed for base URL)\n * @returns Response for the OAuth callback\n */\n private handleOAuthCallbackResponse(\n result: MCPClientOAuthResult,\n request: Request\n ): Response {\n const config = this.mcp.getOAuthCallbackConfig();\n\n // Use custom handler if configured\n if (config?.customHandler) {\n return config.customHandler(result);\n }\n\n const baseOrigin = new URL(request.url).origin;\n\n // Redirect to success URL if configured\n if (config?.successRedirect && result.authSuccess) {\n try {\n return Response.redirect(\n new URL(config.successRedirect, baseOrigin).href\n );\n } catch (e) {\n console.error(\n \"Invalid successRedirect URL:\",\n config.successRedirect,\n e\n );\n return Response.redirect(baseOrigin);\n }\n }\n\n // Redirect to error URL if configured\n if (config?.errorRedirect && !result.authSuccess) {\n try {\n const errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(\n result.authError || \"Unknown error\"\n )}`;\n return Response.redirect(new URL(errorUrl, baseOrigin).href);\n } catch (e) {\n console.error(\"Invalid errorRedirect URL:\", config.errorRedirect, e);\n return Response.redirect(baseOrigin);\n }\n }\n\n // Default: redirect to base URL\n return Response.redirect(baseOrigin);\n }\n}\n\n// A set of classes that have been wrapped with agent context\nconst wrappedClasses = new Set<typeof Agent.prototype.constructor>();\n\n/**\n * Namespace for creating Agent instances\n * @template Agentic Type of the Agent class\n */\nexport type AgentNamespace<Agentic extends Agent<unknown>> =\n DurableObjectNamespace<Agentic>;\n\n/**\n * Agent's durable context\n */\nexport type AgentContext = DurableObjectState;\n\n/**\n * Configuration options for Agent routing\n */\nexport type AgentOptions<Env> = PartyServerOptions<Env> & {\n /**\n * Whether to enable CORS for the Agent\n */\n cors?: boolean | HeadersInit | undefined;\n};\n\n/**\n * Route a request to the appropriate Agent\n * @param request Request to route\n * @param env Environment containing Agent bindings\n * @param options Routing options\n * @returns Response from the Agent or undefined if no route matched\n */\nexport async function routeAgentRequest<Env>(\n request: Request,\n env: Env,\n options?: AgentOptions<Env>\n) {\n const corsHeaders =\n options?.cors === true\n ? {\n \"Access-Control-Allow-Credentials\": \"true\",\n \"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Max-Age\": \"86400\"\n }\n : options?.cors;\n\n if (request.method === \"OPTIONS\") {\n if (corsHeaders) {\n return new Response(null, {\n headers: corsHeaders\n });\n }\n console.warn(\n \"Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.\"\n );\n }\n\n let response = await routePartykitRequest(\n request,\n env as Record<string, unknown>,\n {\n prefix: \"agents\",\n ...(options as PartyServerOptions<Record<string, unknown>>)\n }\n );\n\n if (\n response &&\n corsHeaders &&\n request.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\" &&\n request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\"\n ) {\n const newHeaders = new Headers(response.headers);\n\n // Add CORS headers\n for (const [key, value] of Object.entries(corsHeaders)) {\n newHeaders.set(key, value);\n }\n\n response = new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: newHeaders\n });\n }\n return response;\n}\n\nexport type EmailResolver<Env> = (\n email: ForwardableEmailMessage,\n env: Env\n) => Promise<{\n agentName: string;\n agentId: string;\n} | null>;\n\n/**\n * Create a resolver that uses the message-id header to determine the agent to route the email to\n * @returns A function that resolves the agent to route the email to\n */\nexport function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {\n return async (email: ForwardableEmailMessage, _env: Env) => {\n const messageId = email.headers.get(\"message-id\");\n if (messageId) {\n const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);\n if (messageIdMatch) {\n const [, agentId, domain] = messageIdMatch;\n const agentName = domain.split(\".\")[0];\n return { agentName, agentId };\n }\n }\n\n const references = email.headers.get(\"references\");\n if (references) {\n const referencesMatch = references.match(\n /<([A-Za-z0-9+/]{43}=)@([^>]+)>/\n );\n if (referencesMatch) {\n const [, base64Id, domain] = referencesMatch;\n const agentId = Buffer.from(base64Id, \"base64\").toString(\"hex\");\n const agentName = domain.split(\".\")[0];\n return { agentName, agentId };\n }\n }\n\n const agentName = email.headers.get(\"x-agent-name\");\n const agentId = email.headers.get(\"x-agent-id\");\n if (agentName && agentId) {\n return { agentName, agentId };\n }\n\n return null;\n };\n}\n\n/**\n * Create a resolver that uses the email address to determine the agent to route the email to\n * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address\n * @returns A function that resolves the agent to route the email to\n */\nexport function createAddressBasedEmailResolver<Env>(\n defaultAgentName: string\n): EmailResolver<Env> {\n return async (email: ForwardableEmailMessage, _env: Env) => {\n const emailMatch = email.to.match(/^([^+@]+)(?:\\+([^@]+))?@(.+)$/);\n if (!emailMatch) {\n return null;\n }\n\n const [, localPart, subAddress] = emailMatch;\n\n if (subAddress) {\n return {\n agentName: localPart,\n agentId: subAddress\n };\n }\n\n // Option 2: Use defaultAgentName namespace, localPart as agentId\n // Common for catch-all email routing to a single EmailAgent namespace\n return {\n agentName: defaultAgentName,\n agentId: localPart\n };\n };\n}\n\n/**\n * Create a resolver that uses the agentName and agentId to determine the agent to route the email to\n * @param agentName The name of the agent to route the email to\n * @param agentId The id of the agent to route the email to\n * @returns A function that resolves the agent to route the email to\n */\nexport function createCatchAllEmailResolver<Env>(\n agentName: string,\n agentId: string\n): EmailResolver<Env> {\n return async () => ({ agentName, agentId });\n}\n\nexport type EmailRoutingOptions<Env> = AgentOptions<Env> & {\n resolver: EmailResolver<Env>;\n};\n\n// Cache the agent namespace map for email routing\n// This maps both kebab-case and original names to namespaces\nconst agentMapCache = new WeakMap<\n Record<string, unknown>,\n Record<string, unknown>\n>();\n\n/**\n * Route an email to the appropriate Agent\n * @param email The email to route\n * @param env The environment containing the Agent bindings\n * @param options The options for routing the email\n * @returns A promise that resolves when the email has been routed\n */\nexport async function routeAgentEmail<Env>(\n email: ForwardableEmailMessage,\n env: Env,\n options: EmailRoutingOptions<Env>\n): Promise<void> {\n const routingInfo = await options.resolver(email, env);\n\n if (!routingInfo) {\n console.warn(\"No routing information found for email, dropping message\");\n return;\n }\n\n // Build a map that includes both original names and kebab-case versions\n if (!agentMapCache.has(env as Record<string, unknown>)) {\n const map: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(env as Record<string, unknown>)) {\n if (\n value &&\n typeof value === \"object\" &&\n \"idFromName\" in value &&\n typeof value.idFromName === \"function\"\n ) {\n // Add both the original name and kebab-case version\n map[key] = value;\n map[camelCaseToKebabCase(key)] = value;\n }\n }\n agentMapCache.set(env as Record<string, unknown>, map);\n }\n\n const agentMap = agentMapCache.get(env as Record<string, unknown>)!;\n const namespace = agentMap[routingInfo.agentName];\n\n if (!namespace) {\n // Provide helpful error message listing available agents\n const availableAgents = Object.keys(agentMap)\n .filter((key) => !key.includes(\"-\")) // Show only original names, not kebab-case duplicates\n .join(\", \");\n throw new Error(\n `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`\n );\n }\n\n const agent = await getAgentByName(\n namespace as unknown as AgentNamespace<Agent<Env>>,\n routingInfo.agentId\n );\n\n // let's make a serialisable version of the email\n const serialisableEmail: AgentEmail = {\n getRaw: async () => {\n const reader = email.raw.getReader();\n const chunks: Uint8Array[] = [];\n\n let done = false;\n while (!done) {\n const { value, done: readerDone } = await reader.read();\n done = readerDone;\n if (value) {\n chunks.push(value);\n }\n }\n\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const combined = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n combined.set(chunk, offset);\n offset += chunk.length;\n }\n\n return combined;\n },\n headers: email.headers,\n rawSize: email.rawSize,\n setReject: (reason: string) => {\n email.setReject(reason);\n },\n forward: (rcptTo: string, headers?: Headers) => {\n return email.forward(rcptTo, headers);\n },\n reply: (options: { from: string; to: string; raw: string }) => {\n return email.reply(\n new EmailMessage(options.from, options.to, options.raw)\n );\n },\n from: email.from,\n to: email.to\n };\n\n await agent._onEmail(serialisableEmail);\n}\n\nexport type AgentEmail = {\n from: string;\n to: string;\n getRaw: () => Promise<Uint8Array>;\n headers: Headers;\n rawSize: number;\n setReject: (reason: string) => void;\n forward: (rcptTo: string, headers?: Headers) => Promise<void>;\n reply: (options: { from: string; to: string; raw: string }) => Promise<void>;\n};\n\nexport type EmailSendOptions = {\n to: string;\n subject: string;\n body: string;\n contentType?: string;\n headers?: Record<string, string>;\n includeRoutingHeaders?: boolean;\n agentName?: string;\n agentId?: string;\n domain?: string;\n};\n\n/**\n * Get or create an Agent by name\n * @template Env Environment type containing bindings\n * @template T Type of the Agent class\n * @param namespace Agent namespace\n * @param name Name of the Agent instance\n * @param options Options for Agent creation\n * @returns Promise resolving to an Agent instance stub\n */\nexport async function getAgentByName<\n Env,\n T extends Agent<Env>,\n Props extends Record<string, unknown> = Record<string, unknown>\n>(\n namespace: AgentNamespace<T>,\n name: string,\n options?: {\n jurisdiction?: DurableObjectJurisdiction;\n locationHint?: DurableObjectLocationHint;\n props?: Props;\n }\n) {\n return getServerByName<Env, T>(namespace, name, options);\n}\n\n/**\n * A wrapper for streaming responses in callable methods\n */\nexport class StreamingResponse {\n private _connection: Connection;\n private _id: string;\n private _closed = false;\n\n constructor(connection: Connection, id: string) {\n this._connection = connection;\n this._id = id;\n }\n\n /**\n * Send a chunk of data to the client\n * @param chunk The data to send\n */\n send(chunk: unknown) {\n if (this._closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n const response: RPCResponse = {\n done: false,\n id: this._id,\n result: chunk,\n success: true,\n type: MessageType.RPC\n };\n this._connection.send(JSON.stringify(response));\n }\n\n /**\n * End the stream and send the final chunk (if any)\n * @param finalChunk Optional final chunk of data to send\n */\n end(finalChunk?: unknown) {\n if (this._closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n this._closed = true;\n const response: RPCResponse = {\n done: true,\n id: this._id,\n result: finalChunk,\n success: true,\n type: MessageType.RPC\n };\n this._connection.send(JSON.stringify(response));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAuBA,MAAaA,uBAAsC,EACjD,KAAK,OAAO;AAEV,KAAI,aAAa,EAAE;AACjB,UAAQ,IAAI,MAAM,eAAe;AACjC;;AAGF,SAAQ,IAAI,MAAM;GAErB;AAED,IAAI,YAAY;AAEhB,SAAS,cAAc;AACrB,KAAI,UACF,QAAO;CAET,MAAM,EAAE,YAAY,iBAAiB;AACrC,KAAI,CAAC,QACH,QAAO;AAIT,aADY,IAAI,IAAI,QAAQ,IAAI,CAChB,aAAa;AAC7B,QAAO;;;;;;;;AC8BT,SAAS,aAAa,KAAiC;AACrD,QACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,SAAS,YAAY,O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