agents 0.0.0-ecf8926 → 0.0.0-ed3f94d
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 +126 -4
- package/dist/_esm-LV5FJ3HK.js +3922 -0
- package/dist/_esm-LV5FJ3HK.js.map +1 -0
- package/dist/ai-chat-agent.d.ts +2 -1
- package/dist/ai-chat-agent.js +391 -76
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-chat-v5-migration.js +1 -0
- package/dist/ai-react.d.ts +8 -1
- package/dist/ai-react.js +157 -111
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types.d.ts +1 -0
- package/dist/ai-types.js +2 -1
- package/dist/ccip-CMBYN64O.js +15 -0
- package/dist/ccip-CMBYN64O.js.map +1 -0
- package/dist/{chunk-EGCWEPQL.js → chunk-254F4GDT.js} +151 -98
- package/dist/chunk-254F4GDT.js.map +1 -0
- package/dist/{chunk-DS7BJNPH.js → chunk-3OT2NNEW.js} +411 -68
- package/dist/chunk-3OT2NNEW.js.map +1 -0
- package/dist/chunk-5Y6BEZDY.js +276 -0
- package/dist/chunk-5Y6BEZDY.js.map +1 -0
- package/dist/{chunk-AVYJQSLW.js → chunk-BER7KXUJ.js} +2 -1
- package/dist/chunk-BER7KXUJ.js.map +1 -0
- package/dist/chunk-JJBFIGUC.js +5202 -0
- package/dist/chunk-JJBFIGUC.js.map +1 -0
- package/dist/chunk-PR4QN5HX.js +43 -0
- package/dist/chunk-PR4QN5HX.js.map +1 -0
- package/dist/chunk-TYAY6AU6.js +159 -0
- package/dist/chunk-TYAY6AU6.js.map +1 -0
- package/dist/{chunk-PVQZBKN7.js → chunk-Z44WASMA.js} +11 -3
- package/dist/chunk-Z44WASMA.js.map +1 -0
- package/dist/{client-BAqDHqAV.d.ts → client-DVoPb3-C.d.ts} +549 -30
- package/dist/client.js +2 -1
- package/dist/codemode/ai.d.ts +25 -0
- package/dist/codemode/ai.js +5112 -0
- package/dist/codemode/ai.js.map +1 -0
- package/dist/index.d.ts +44 -35
- package/dist/index.js +7 -4
- package/dist/mcp/client.d.ts +2 -1
- package/dist/mcp/client.js +2 -1
- package/dist/mcp/do-oauth-client-provider.d.ts +1 -0
- package/dist/mcp/do-oauth-client-provider.js +2 -1
- package/dist/mcp/index.d.ts +50 -83
- package/dist/mcp/index.js +903 -760
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/x402.d.ts +39 -0
- package/dist/mcp/x402.js +3195 -0
- package/dist/mcp/x402.js.map +1 -0
- package/dist/mcp-BH1fJeiU.d.ts +58 -0
- package/dist/observability/index.d.ts +12 -24
- package/dist/observability/index.js +5 -4
- package/dist/react.d.ts +10 -6
- package/dist/react.js +101 -3
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +76 -2
- package/dist/schedule.js +17 -2
- package/dist/schedule.js.map +1 -1
- package/dist/secp256k1-M22GZP2U.js +2193 -0
- package/dist/secp256k1-M22GZP2U.js.map +1 -0
- package/package.json +22 -7
- package/src/index.ts +226 -116
- package/dist/chunk-AVYJQSLW.js.map +0 -1
- package/dist/chunk-DS7BJNPH.js.map +0 -1
- package/dist/chunk-EGCWEPQL.js.map +0 -1
- package/dist/chunk-PVQZBKN7.js.map +0 -1
package/src/index.ts
CHANGED
|
@@ -22,10 +22,12 @@ import {
|
|
|
22
22
|
routePartykitRequest
|
|
23
23
|
} from "partyserver";
|
|
24
24
|
import { camelCaseToKebabCase } from "./client";
|
|
25
|
-
import { MCPClientManager } from "./mcp/client";
|
|
26
|
-
|
|
25
|
+
import { MCPClientManager, type MCPClientOAuthResult } from "./mcp/client";
|
|
26
|
+
import type { MCPConnectionState } from "./mcp/client-connection";
|
|
27
27
|
import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
|
|
28
|
+
import type { TransportType } from "./mcp/types";
|
|
28
29
|
import { genericObservability, type Observability } from "./observability";
|
|
30
|
+
import { DisposableStore } from "./core/events";
|
|
29
31
|
import { MessageType } from "./ai-types";
|
|
30
32
|
|
|
31
33
|
export type { Connection, ConnectionContext, WSMessage } from "partyserver";
|
|
@@ -118,7 +120,7 @@ const callableMetadata = new Map<Function, CallableMetadata>();
|
|
|
118
120
|
* Decorator that marks a method as callable by clients
|
|
119
121
|
* @param metadata Optional metadata about the callable method
|
|
120
122
|
*/
|
|
121
|
-
export function
|
|
123
|
+
export function callable(metadata: CallableMetadata = {}) {
|
|
122
124
|
return function callableDecorator<This, Args extends unknown[], Return>(
|
|
123
125
|
target: (this: This, ...args: Args) => Return,
|
|
124
126
|
// biome-ignore lint/correctness/noUnusedFunctionParameters: later
|
|
@@ -132,6 +134,23 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
|
|
|
132
134
|
};
|
|
133
135
|
}
|
|
134
136
|
|
|
137
|
+
let didWarnAboutUnstableCallable = false;
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Decorator that marks a method as callable by clients
|
|
141
|
+
* @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
|
|
142
|
+
* @param metadata Optional metadata about the callable method
|
|
143
|
+
*/
|
|
144
|
+
export const unstable_callable = (metadata: CallableMetadata = {}) => {
|
|
145
|
+
if (!didWarnAboutUnstableCallable) {
|
|
146
|
+
didWarnAboutUnstableCallable = true;
|
|
147
|
+
console.warn(
|
|
148
|
+
"unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version."
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
callable(metadata);
|
|
152
|
+
};
|
|
153
|
+
|
|
135
154
|
export type QueueItem<T = string> = {
|
|
136
155
|
id: string;
|
|
137
156
|
payload: T;
|
|
@@ -180,6 +199,8 @@ function getNextCronTime(cron: string) {
|
|
|
180
199
|
return interval.getNextDate();
|
|
181
200
|
}
|
|
182
201
|
|
|
202
|
+
export type { TransportType } from "./mcp/types";
|
|
203
|
+
|
|
183
204
|
/**
|
|
184
205
|
* MCP Server state update message from server -> Client
|
|
185
206
|
*/
|
|
@@ -204,7 +225,7 @@ export type MCPServer = {
|
|
|
204
225
|
// This state is specifically about the temporary process of getting a token (if needed).
|
|
205
226
|
// Scope outside of that can't be relied upon because when the DO sleeps, there's no way
|
|
206
227
|
// to communicate a change to a non-ready state.
|
|
207
|
-
state:
|
|
228
|
+
state: MCPConnectionState;
|
|
208
229
|
instructions: string | null;
|
|
209
230
|
capabilities: ServerCapabilities | null;
|
|
210
231
|
};
|
|
@@ -273,7 +294,13 @@ function withAgentContext<T extends (...args: any[]) => any>(
|
|
|
273
294
|
method: T
|
|
274
295
|
): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {
|
|
275
296
|
return function (...args: Parameters<T>): ReturnType<T> {
|
|
276
|
-
const { connection, request, email } = getCurrentAgent();
|
|
297
|
+
const { connection, request, email, agent } = getCurrentAgent();
|
|
298
|
+
|
|
299
|
+
if (agent === this) {
|
|
300
|
+
// already wrapped, so we can just call the method
|
|
301
|
+
return method.apply(this, args);
|
|
302
|
+
}
|
|
303
|
+
// not wrapped, so we need to wrap it
|
|
277
304
|
return agentContext.run({ agent: this, connection, request, email }, () => {
|
|
278
305
|
return method.apply(this, args);
|
|
279
306
|
});
|
|
@@ -285,13 +312,21 @@ function withAgentContext<T extends (...args: any[]) => any>(
|
|
|
285
312
|
* @template Env Environment type containing bindings
|
|
286
313
|
* @template State State type to store within the Agent
|
|
287
314
|
*/
|
|
288
|
-
export class Agent<
|
|
315
|
+
export class Agent<
|
|
316
|
+
Env = typeof env,
|
|
317
|
+
State = unknown,
|
|
318
|
+
Props extends Record<string, unknown> = Record<string, unknown>
|
|
319
|
+
> extends Server<Env, Props> {
|
|
289
320
|
private _state = DEFAULT_STATE as State;
|
|
321
|
+
private _disposables = new DisposableStore();
|
|
290
322
|
|
|
291
323
|
private _ParentClass: typeof Agent<Env, State> =
|
|
292
324
|
Object.getPrototypeOf(this).constructor;
|
|
293
325
|
|
|
294
|
-
mcp: MCPClientManager = new MCPClientManager(
|
|
326
|
+
readonly mcp: MCPClientManager = new MCPClientManager(
|
|
327
|
+
this._ParentClass.name,
|
|
328
|
+
"0.0.1"
|
|
329
|
+
);
|
|
295
330
|
|
|
296
331
|
/**
|
|
297
332
|
* Initial state for the Agent
|
|
@@ -384,8 +419,25 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
384
419
|
constructor(ctx: AgentContext, env: Env) {
|
|
385
420
|
super(ctx, env);
|
|
386
421
|
|
|
387
|
-
|
|
388
|
-
|
|
422
|
+
if (!wrappedClasses.has(this.constructor)) {
|
|
423
|
+
// Auto-wrap custom methods with agent context
|
|
424
|
+
this._autoWrapCustomMethods();
|
|
425
|
+
wrappedClasses.add(this.constructor);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// Broadcast server state after background connects (for OAuth servers)
|
|
429
|
+
this._disposables.add(
|
|
430
|
+
this.mcp.onConnected(async () => {
|
|
431
|
+
this.broadcastMcpServers();
|
|
432
|
+
})
|
|
433
|
+
);
|
|
434
|
+
|
|
435
|
+
// Emit MCP observability events
|
|
436
|
+
this._disposables.add(
|
|
437
|
+
this.mcp.onObservabilityEvent((event) => {
|
|
438
|
+
this.observability?.emit(event);
|
|
439
|
+
})
|
|
440
|
+
);
|
|
389
441
|
|
|
390
442
|
this.sql`
|
|
391
443
|
CREATE TABLE IF NOT EXISTS cf_agents_state (
|
|
@@ -442,21 +494,24 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
442
494
|
{ agent: this, connection: undefined, request, email: undefined },
|
|
443
495
|
async () => {
|
|
444
496
|
if (this.mcp.isCallbackRequest(request)) {
|
|
445
|
-
await this.mcp.handleCallbackRequest(request);
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
497
|
+
const result = await this.mcp.handleCallbackRequest(request);
|
|
498
|
+
this.broadcastMcpServers();
|
|
499
|
+
|
|
500
|
+
if (result.authSuccess) {
|
|
501
|
+
// Start background connection if auth was successful
|
|
502
|
+
this.mcp
|
|
503
|
+
.establishConnection(result.serverId)
|
|
504
|
+
.catch((error) => {
|
|
505
|
+
console.error("Background connection failed:", error);
|
|
506
|
+
})
|
|
507
|
+
.finally(() => {
|
|
508
|
+
// Broadcast after background connection resolves (success/failure)
|
|
509
|
+
this.broadcastMcpServers();
|
|
510
|
+
});
|
|
511
|
+
}
|
|
454
512
|
|
|
455
|
-
//
|
|
456
|
-
return
|
|
457
|
-
headers: { "content-type": "text/html" },
|
|
458
|
-
status: 200
|
|
459
|
-
});
|
|
513
|
+
// Handle OAuth callback response using MCPClientManager configuration
|
|
514
|
+
return this.handleOAuthCallbackResponse(result, request);
|
|
460
515
|
}
|
|
461
516
|
|
|
462
517
|
return this._tryCatch(() => _onRequest(request));
|
|
@@ -560,44 +615,42 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
560
615
|
// must fix this
|
|
561
616
|
return agentContext.run(
|
|
562
617
|
{ agent: this, connection, request: ctx.request, email: undefined },
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
if (this.state) {
|
|
566
|
-
connection.send(
|
|
567
|
-
JSON.stringify({
|
|
568
|
-
state: this.state,
|
|
569
|
-
type: MessageType.CF_AGENT_STATE
|
|
570
|
-
})
|
|
571
|
-
);
|
|
572
|
-
}
|
|
573
|
-
|
|
618
|
+
() => {
|
|
619
|
+
if (this.state) {
|
|
574
620
|
connection.send(
|
|
575
621
|
JSON.stringify({
|
|
576
|
-
|
|
577
|
-
type: MessageType.
|
|
622
|
+
state: this.state,
|
|
623
|
+
type: MessageType.CF_AGENT_STATE
|
|
578
624
|
})
|
|
579
625
|
);
|
|
626
|
+
}
|
|
580
627
|
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
628
|
+
connection.send(
|
|
629
|
+
JSON.stringify({
|
|
630
|
+
mcp: this.getMcpServers(),
|
|
631
|
+
type: MessageType.CF_AGENT_MCP_SERVERS
|
|
632
|
+
})
|
|
633
|
+
);
|
|
634
|
+
|
|
635
|
+
this.observability?.emit(
|
|
636
|
+
{
|
|
637
|
+
displayMessage: "Connection established",
|
|
638
|
+
id: nanoid(),
|
|
639
|
+
payload: {
|
|
640
|
+
connectionId: connection.id
|
|
590
641
|
},
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
642
|
+
timestamp: Date.now(),
|
|
643
|
+
type: "connect"
|
|
644
|
+
},
|
|
645
|
+
this.ctx
|
|
646
|
+
);
|
|
647
|
+
return this._tryCatch(() => _onConnect(connection, ctx));
|
|
595
648
|
}
|
|
596
649
|
);
|
|
597
650
|
};
|
|
598
651
|
|
|
599
652
|
const _onStart = this.onStart.bind(this);
|
|
600
|
-
this.onStart = async () => {
|
|
653
|
+
this.onStart = async (props?: Props) => {
|
|
601
654
|
return agentContext.run(
|
|
602
655
|
{
|
|
603
656
|
agent: this,
|
|
@@ -611,15 +664,20 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
611
664
|
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
612
665
|
`;
|
|
613
666
|
|
|
614
|
-
this.
|
|
615
|
-
JSON.stringify({
|
|
616
|
-
mcp: this.getMcpServers(),
|
|
617
|
-
type: MessageType.CF_AGENT_MCP_SERVERS
|
|
618
|
-
})
|
|
619
|
-
);
|
|
667
|
+
this.broadcastMcpServers();
|
|
620
668
|
|
|
621
669
|
// from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
|
|
622
670
|
if (servers && Array.isArray(servers) && servers.length > 0) {
|
|
671
|
+
// Restore callback URLs for OAuth-enabled servers
|
|
672
|
+
servers.forEach((server) => {
|
|
673
|
+
if (server.callback_url) {
|
|
674
|
+
// Register the full redirect URL including serverId to avoid ambiguous matches
|
|
675
|
+
this.mcp.registerCallbackUrl(
|
|
676
|
+
`${server.callback_url}/${server.id}`
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
});
|
|
680
|
+
|
|
623
681
|
servers.forEach((server) => {
|
|
624
682
|
this._connectToMcpServerInternal(
|
|
625
683
|
server.name,
|
|
@@ -635,12 +693,7 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
635
693
|
)
|
|
636
694
|
.then(() => {
|
|
637
695
|
// Broadcast updated MCP servers state after each server connects
|
|
638
|
-
this.
|
|
639
|
-
JSON.stringify({
|
|
640
|
-
mcp: this.getMcpServers(),
|
|
641
|
-
type: MessageType.CF_AGENT_MCP_SERVERS
|
|
642
|
-
})
|
|
643
|
-
);
|
|
696
|
+
this.broadcastMcpServers();
|
|
644
697
|
})
|
|
645
698
|
.catch((error) => {
|
|
646
699
|
console.error(
|
|
@@ -648,16 +701,11 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
648
701
|
error
|
|
649
702
|
);
|
|
650
703
|
// Still broadcast even if connection fails, so clients know about the failure
|
|
651
|
-
this.
|
|
652
|
-
JSON.stringify({
|
|
653
|
-
mcp: this.getMcpServers(),
|
|
654
|
-
type: MessageType.CF_AGENT_MCP_SERVERS
|
|
655
|
-
})
|
|
656
|
-
);
|
|
704
|
+
this.broadcastMcpServers();
|
|
657
705
|
});
|
|
658
706
|
});
|
|
659
707
|
}
|
|
660
|
-
return _onStart();
|
|
708
|
+
return _onStart(props);
|
|
661
709
|
});
|
|
662
710
|
}
|
|
663
711
|
);
|
|
@@ -833,41 +881,37 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
833
881
|
while (proto && proto !== Object.prototype && depth < 10) {
|
|
834
882
|
const methodNames = Object.getOwnPropertyNames(proto);
|
|
835
883
|
for (const methodName of methodNames) {
|
|
836
|
-
|
|
884
|
+
const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
|
|
885
|
+
|
|
886
|
+
// Skip if it's a private method, a base method, a getter, or not a function,
|
|
837
887
|
if (
|
|
838
888
|
baseMethods.has(methodName) ||
|
|
839
889
|
methodName.startsWith("_") ||
|
|
840
|
-
|
|
890
|
+
!descriptor ||
|
|
891
|
+
!!descriptor.get ||
|
|
892
|
+
typeof descriptor.value !== "function"
|
|
841
893
|
) {
|
|
842
894
|
continue;
|
|
843
895
|
}
|
|
844
|
-
// If the method doesn't exist in base prototypes, it's a custom method
|
|
845
|
-
if (!baseMethods.has(methodName)) {
|
|
846
|
-
const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
|
|
847
|
-
if (descriptor && typeof descriptor.value === "function") {
|
|
848
|
-
// Wrap the custom method with context
|
|
849
|
-
|
|
850
|
-
const wrappedFunction = withAgentContext(
|
|
851
|
-
// biome-ignore lint/suspicious/noExplicitAny: I can't typescript
|
|
852
|
-
this[methodName as keyof this] as (...args: any[]) => any
|
|
853
|
-
// biome-ignore lint/suspicious/noExplicitAny: I can't typescript
|
|
854
|
-
) as any;
|
|
855
|
-
|
|
856
|
-
// if the method is callable, copy the metadata from the original method
|
|
857
|
-
if (this._isCallable(methodName)) {
|
|
858
|
-
callableMetadata.set(
|
|
859
|
-
wrappedFunction,
|
|
860
|
-
callableMetadata.get(
|
|
861
|
-
this[methodName as keyof this] as Function
|
|
862
|
-
)!
|
|
863
|
-
);
|
|
864
|
-
}
|
|
865
896
|
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
897
|
+
// Now, methodName is confirmed to be a custom method/function
|
|
898
|
+
// Wrap the custom method with context
|
|
899
|
+
const wrappedFunction = withAgentContext(
|
|
900
|
+
// biome-ignore lint/suspicious/noExplicitAny: I can't typescript
|
|
901
|
+
this[methodName as keyof this] as (...args: any[]) => any
|
|
902
|
+
// biome-ignore lint/suspicious/noExplicitAny: I can't typescript
|
|
903
|
+
) as any;
|
|
904
|
+
|
|
905
|
+
// if the method is callable, copy the metadata from the original method
|
|
906
|
+
if (this._isCallable(methodName)) {
|
|
907
|
+
callableMetadata.set(
|
|
908
|
+
wrappedFunction,
|
|
909
|
+
callableMetadata.get(this[methodName as keyof this] as Function)!
|
|
910
|
+
);
|
|
870
911
|
}
|
|
912
|
+
|
|
913
|
+
// set the wrapped function on the prototype
|
|
914
|
+
this.constructor.prototype[methodName as keyof this] = wrappedFunction;
|
|
871
915
|
}
|
|
872
916
|
|
|
873
917
|
proto = Object.getPrototypeOf(proto);
|
|
@@ -1350,6 +1394,8 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
1350
1394
|
// delete all alarms
|
|
1351
1395
|
await this.ctx.storage.deleteAlarm();
|
|
1352
1396
|
await this.ctx.storage.deleteAll();
|
|
1397
|
+
this._disposables.dispose();
|
|
1398
|
+
await this.mcp.dispose?.();
|
|
1353
1399
|
this.ctx.abort("destroyed"); // enforce that the agent is evicted
|
|
1354
1400
|
|
|
1355
1401
|
this.observability?.emit(
|
|
@@ -1375,25 +1421,42 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
1375
1421
|
/**
|
|
1376
1422
|
* Connect to a new MCP Server
|
|
1377
1423
|
*
|
|
1424
|
+
* @param serverName Name of the MCP server
|
|
1378
1425
|
* @param url MCP Server SSE URL
|
|
1379
|
-
* @param callbackHost Base host for the agent, used for the redirect URI.
|
|
1426
|
+
* @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
|
|
1380
1427
|
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
1381
|
-
* @param options MCP client and transport
|
|
1428
|
+
* @param options MCP client and transport options
|
|
1382
1429
|
* @returns authUrl
|
|
1383
1430
|
*/
|
|
1384
1431
|
async addMcpServer(
|
|
1385
1432
|
serverName: string,
|
|
1386
1433
|
url: string,
|
|
1387
|
-
callbackHost
|
|
1434
|
+
callbackHost?: string,
|
|
1388
1435
|
agentsPrefix = "agents",
|
|
1389
1436
|
options?: {
|
|
1390
1437
|
client?: ConstructorParameters<typeof Client>[1];
|
|
1391
1438
|
transport?: {
|
|
1392
|
-
headers
|
|
1439
|
+
headers?: HeadersInit;
|
|
1440
|
+
type?: TransportType;
|
|
1393
1441
|
};
|
|
1394
1442
|
}
|
|
1395
1443
|
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
1396
|
-
|
|
1444
|
+
// If callbackHost is not provided, derive it from the current request
|
|
1445
|
+
let resolvedCallbackHost = callbackHost;
|
|
1446
|
+
if (!resolvedCallbackHost) {
|
|
1447
|
+
const { request } = getCurrentAgent();
|
|
1448
|
+
if (!request) {
|
|
1449
|
+
throw new Error(
|
|
1450
|
+
"callbackHost is required when not called within a request context"
|
|
1451
|
+
);
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
// Extract the origin from the request
|
|
1455
|
+
const requestUrl = new URL(request.url);
|
|
1456
|
+
resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
1397
1460
|
|
|
1398
1461
|
const result = await this._connectToMcpServerInternal(
|
|
1399
1462
|
serverName,
|
|
@@ -1401,6 +1464,7 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
1401
1464
|
callbackUrl,
|
|
1402
1465
|
options
|
|
1403
1466
|
);
|
|
1467
|
+
|
|
1404
1468
|
this.sql`
|
|
1405
1469
|
INSERT
|
|
1406
1470
|
OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
@@ -1415,17 +1479,12 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
1415
1479
|
);
|
|
1416
1480
|
`;
|
|
1417
1481
|
|
|
1418
|
-
this.
|
|
1419
|
-
JSON.stringify({
|
|
1420
|
-
mcp: this.getMcpServers(),
|
|
1421
|
-
type: MessageType.CF_AGENT_MCP_SERVERS
|
|
1422
|
-
})
|
|
1423
|
-
);
|
|
1482
|
+
this.broadcastMcpServers();
|
|
1424
1483
|
|
|
1425
1484
|
return result;
|
|
1426
1485
|
}
|
|
1427
1486
|
|
|
1428
|
-
async _connectToMcpServerInternal(
|
|
1487
|
+
private async _connectToMcpServerInternal(
|
|
1429
1488
|
_serverName: string,
|
|
1430
1489
|
url: string,
|
|
1431
1490
|
callbackUrl: string,
|
|
@@ -1441,6 +1500,7 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
1441
1500
|
*/
|
|
1442
1501
|
transport?: {
|
|
1443
1502
|
headers?: HeadersInit;
|
|
1503
|
+
type?: TransportType;
|
|
1444
1504
|
};
|
|
1445
1505
|
},
|
|
1446
1506
|
reconnect?: {
|
|
@@ -1465,6 +1525,9 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
1465
1525
|
}
|
|
1466
1526
|
}
|
|
1467
1527
|
|
|
1528
|
+
// Use the transport type specified in options, or default to "auto"
|
|
1529
|
+
const transportType: TransportType = options?.transport?.type ?? "auto";
|
|
1530
|
+
|
|
1468
1531
|
// allows passing through transport headers if necessary
|
|
1469
1532
|
// this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
|
|
1470
1533
|
let headerTransportOpts: SSEClientTransportOptions = {};
|
|
@@ -1488,7 +1551,8 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
1488
1551
|
reconnect,
|
|
1489
1552
|
transport: {
|
|
1490
1553
|
...headerTransportOpts,
|
|
1491
|
-
authProvider
|
|
1554
|
+
authProvider,
|
|
1555
|
+
type: transportType
|
|
1492
1556
|
}
|
|
1493
1557
|
});
|
|
1494
1558
|
|
|
@@ -1501,15 +1565,11 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
1501
1565
|
|
|
1502
1566
|
async removeMcpServer(id: string) {
|
|
1503
1567
|
this.mcp.closeConnection(id);
|
|
1568
|
+
this.mcp.unregisterCallbackUrl(id);
|
|
1504
1569
|
this.sql`
|
|
1505
1570
|
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
1506
1571
|
`;
|
|
1507
|
-
this.
|
|
1508
|
-
JSON.stringify({
|
|
1509
|
-
mcp: this.getMcpServers(),
|
|
1510
|
-
type: MessageType.CF_AGENT_MCP_SERVERS
|
|
1511
|
-
})
|
|
1512
|
-
);
|
|
1572
|
+
this.broadcastMcpServers();
|
|
1513
1573
|
}
|
|
1514
1574
|
|
|
1515
1575
|
getMcpServers(): MCPServersState {
|
|
@@ -1541,8 +1601,53 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
|
1541
1601
|
|
|
1542
1602
|
return mcpState;
|
|
1543
1603
|
}
|
|
1604
|
+
|
|
1605
|
+
private broadcastMcpServers() {
|
|
1606
|
+
this.broadcast(
|
|
1607
|
+
JSON.stringify({
|
|
1608
|
+
mcp: this.getMcpServers(),
|
|
1609
|
+
type: MessageType.CF_AGENT_MCP_SERVERS
|
|
1610
|
+
})
|
|
1611
|
+
);
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
/**
|
|
1615
|
+
* Handle OAuth callback response using MCPClientManager configuration
|
|
1616
|
+
* @param result OAuth callback result
|
|
1617
|
+
* @param request The original request (needed for base URL)
|
|
1618
|
+
* @returns Response for the OAuth callback
|
|
1619
|
+
*/
|
|
1620
|
+
private handleOAuthCallbackResponse(
|
|
1621
|
+
result: MCPClientOAuthResult,
|
|
1622
|
+
request: Request
|
|
1623
|
+
): Response {
|
|
1624
|
+
const config = this.mcp.getOAuthCallbackConfig();
|
|
1625
|
+
|
|
1626
|
+
// Use custom handler if configured
|
|
1627
|
+
if (config?.customHandler) {
|
|
1628
|
+
return config.customHandler(result);
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
// Use redirect URLs if configured
|
|
1632
|
+
if (config?.successRedirect && result.authSuccess) {
|
|
1633
|
+
return Response.redirect(config.successRedirect);
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
if (config?.errorRedirect && !result.authSuccess) {
|
|
1637
|
+
return Response.redirect(
|
|
1638
|
+
`${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`
|
|
1639
|
+
);
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
// Default behavior - redirect to base URL
|
|
1643
|
+
const baseUrl = new URL(request.url).origin;
|
|
1644
|
+
return Response.redirect(baseUrl);
|
|
1645
|
+
}
|
|
1544
1646
|
}
|
|
1545
1647
|
|
|
1648
|
+
// A set of classes that have been wrapped with agent context
|
|
1649
|
+
const wrappedClasses = new Set<typeof Agent.prototype.constructor>();
|
|
1650
|
+
|
|
1546
1651
|
/**
|
|
1547
1652
|
* Namespace for creating Agent instances
|
|
1548
1653
|
* @template Agentic Type of the Agent class
|
|
@@ -1858,12 +1963,17 @@ export type EmailSendOptions = {
|
|
|
1858
1963
|
* @param options Options for Agent creation
|
|
1859
1964
|
* @returns Promise resolving to an Agent instance stub
|
|
1860
1965
|
*/
|
|
1861
|
-
export async function getAgentByName<
|
|
1966
|
+
export async function getAgentByName<
|
|
1967
|
+
Env,
|
|
1968
|
+
T extends Agent<Env>,
|
|
1969
|
+
Props extends Record<string, unknown> = Record<string, unknown>
|
|
1970
|
+
>(
|
|
1862
1971
|
namespace: AgentNamespace<T>,
|
|
1863
1972
|
name: string,
|
|
1864
1973
|
options?: {
|
|
1865
1974
|
jurisdiction?: DurableObjectJurisdiction;
|
|
1866
1975
|
locationHint?: DurableObjectLocationHint;
|
|
1976
|
+
props?: Props;
|
|
1867
1977
|
}
|
|
1868
1978
|
) {
|
|
1869
1979
|
return getServerByName<Env, T>(namespace, name, options);
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ai-types.ts"],"sourcesContent":["import type { UIMessage } from \"ai\";\n\n/**\n * Enum for message types to improve type safety and maintainability\n */\nexport enum MessageType {\n CF_AGENT_CHAT_MESSAGES = \"cf_agent_chat_messages\",\n CF_AGENT_USE_CHAT_REQUEST = \"cf_agent_use_chat_request\",\n CF_AGENT_USE_CHAT_RESPONSE = \"cf_agent_use_chat_response\",\n CF_AGENT_CHAT_CLEAR = \"cf_agent_chat_clear\",\n CF_AGENT_CHAT_REQUEST_CANCEL = \"cf_agent_chat_request_cancel\",\n\n CF_AGENT_MCP_SERVERS = \"cf_agent_mcp_servers\",\n CF_AGENT_STATE = \"cf_agent_state\",\n RPC = \"rpc\"\n}\n\n/**\n * Types of messages sent from the Agent to clients\n */\nexport type OutgoingMessage<ChatMessage extends UIMessage = UIMessage> =\n | {\n /** Indicates this message is a command to clear chat history */\n type: MessageType.CF_AGENT_CHAT_CLEAR;\n }\n | {\n /** Indicates this message contains updated chat messages */\n type: MessageType.CF_AGENT_CHAT_MESSAGES;\n /** Array of chat messages */\n messages: ChatMessage[];\n }\n | {\n /** Indicates this message is a response to a chat request */\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE;\n /** Unique ID of the request this response corresponds to */\n id: string;\n /** Content body of the response */\n body: string;\n /** Whether this is the final chunk of the response */\n done: boolean;\n /** Whether this response contains an error */\n error?: boolean;\n }\n | {\n /** Indicates this message is a command to clear chat history */\n type: MessageType.CF_AGENT_CHAT_CLEAR;\n };\n\n/**\n * Types of messages sent from clients to the Agent\n */\nexport type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =\n | {\n /** Indicates this message is a command to clear chat history */\n type: MessageType.CF_AGENT_CHAT_CLEAR;\n }\n | {\n /** Indicates this message is a request to the chat API */\n type: MessageType.CF_AGENT_USE_CHAT_REQUEST;\n /** Unique ID for this request */\n id: string;\n /** Request initialization options */\n init: Pick<\n RequestInit,\n | \"method\"\n | \"keepalive\"\n | \"headers\"\n | \"body\"\n | \"redirect\"\n | \"integrity\"\n | \"credentials\"\n | \"mode\"\n | \"referrer\"\n | \"referrerPolicy\"\n | \"window\"\n >;\n }\n | {\n /** Indicates this message is a command to clear chat history */\n type: MessageType.CF_AGENT_CHAT_CLEAR;\n }\n | {\n /** Indicates this message contains updated chat messages */\n type: MessageType.CF_AGENT_CHAT_MESSAGES;\n /** Array of chat messages */\n messages: ChatMessage[];\n }\n | {\n /** Indicates the user wants to stop generation of this message */\n type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL;\n id: string;\n };\n"],"mappings":";AAKO,IAAK,cAAL,kBAAKA,iBAAL;AACL,EAAAA,aAAA,4BAAyB;AACzB,EAAAA,aAAA,+BAA4B;AAC5B,EAAAA,aAAA,gCAA6B;AAC7B,EAAAA,aAAA,yBAAsB;AACtB,EAAAA,aAAA,kCAA+B;AAE/B,EAAAA,aAAA,0BAAuB;AACvB,EAAAA,aAAA,oBAAiB;AACjB,EAAAA,aAAA,SAAM;AATI,SAAAA;AAAA,GAAA;","names":["MessageType"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/client.ts","../src/mcp/client-connection.ts","../src/mcp/sse-edge.ts","../src/mcp/streamable-http-edge.ts"],"sourcesContent":["import type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n CallToolRequest,\n CallToolResultSchema,\n CompatibilityCallToolResultSchema,\n GetPromptRequest,\n Prompt,\n ReadResourceRequest,\n Resource,\n ResourceTemplate,\n Tool\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { type ToolSet, jsonSchema } from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport {\n MCPClientConnection,\n type MCPTransportOptions\n} from \"./client-connection\";\n\n/**\n * Utility class that aggregates multiple MCP clients into one\n */\nexport class MCPClientManager {\n public mcpConnections: Record<string, MCPClientConnection> = {};\n private _callbackUrls: string[] = [];\n\n /**\n * @param _name Name of the MCP client\n * @param _version Version of the MCP Client\n * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider\n */\n constructor(\n private _name: string,\n private _version: string\n ) {}\n\n /**\n * Connect to and register an MCP server\n *\n * @param transportConfig Transport config\n * @param clientConfig Client config\n * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)\n */\n async connect(\n url: string,\n options: {\n // Allows you to reconnect to a server (in the case of an auth reconnect)\n reconnect?: {\n // server id\n id: string;\n oauthClientId?: string;\n oauthCode?: string;\n };\n // we're overriding authProvider here because we want to be able to access the auth URL\n transport?: MCPTransportOptions;\n client?: ConstructorParameters<typeof Client>[1];\n } = {}\n ): Promise<{\n id: string;\n authUrl?: string;\n clientId?: string;\n }> {\n const id = options.reconnect?.id ?? nanoid(8);\n\n if (!options.transport?.authProvider) {\n console.warn(\n \"No authProvider provided in the transport options. This client will only support unauthenticated remote MCP Servers\"\n );\n } else {\n options.transport.authProvider.serverId = id;\n // reconnect with auth\n if (options.reconnect?.oauthClientId) {\n options.transport.authProvider.clientId =\n options.reconnect?.oauthClientId;\n }\n }\n\n this.mcpConnections[id] = new MCPClientConnection(\n new URL(url),\n {\n name: this._name,\n version: this._version\n },\n {\n client: options.client ?? {},\n transport: options.transport ?? {}\n }\n );\n\n await this.mcpConnections[id].init(options.reconnect?.oauthCode);\n\n const authUrl = options.transport?.authProvider?.authUrl;\n if (authUrl && options.transport?.authProvider?.redirectUrl) {\n this._callbackUrls.push(\n options.transport.authProvider.redirectUrl.toString()\n );\n return {\n authUrl,\n clientId: options.transport?.authProvider?.clientId,\n id\n };\n }\n\n return {\n id\n };\n }\n\n isCallbackRequest(req: Request): boolean {\n return (\n req.method === \"GET\" &&\n !!this._callbackUrls.find((url) => {\n return req.url.startsWith(url);\n })\n );\n }\n\n async handleCallbackRequest(req: Request) {\n const url = new URL(req.url);\n const urlMatch = this._callbackUrls.find((url) => {\n return req.url.startsWith(url);\n });\n if (!urlMatch) {\n throw new Error(\n `No callback URI match found for the request url: ${req.url}. Was the request matched with \\`isCallbackRequest()\\`?`\n );\n }\n const code = url.searchParams.get(\"code\");\n const clientId = url.searchParams.get(\"state\");\n const urlParams = urlMatch.split(\"/\");\n const serverId = urlParams[urlParams.length - 1];\n if (!code) {\n throw new Error(\"Unauthorized: no code provided\");\n }\n if (!clientId) {\n throw new Error(\"Unauthorized: no state provided\");\n }\n\n if (this.mcpConnections[serverId] === undefined) {\n throw new Error(`Could not find serverId: ${serverId}`);\n }\n\n if (this.mcpConnections[serverId].connectionState !== \"authenticating\") {\n throw new Error(\n \"Failed to authenticate: the client isn't in the `authenticating` state\"\n );\n }\n\n const conn = this.mcpConnections[serverId];\n if (!conn.options.transport.authProvider) {\n throw new Error(\n \"Trying to finalize authentication for a server connection without an authProvider\"\n );\n }\n\n conn.options.transport.authProvider.clientId = clientId;\n conn.options.transport.authProvider.serverId = serverId;\n\n // reconnect to server with authorization\n const serverUrl = conn.url.toString();\n await this.connect(serverUrl, {\n reconnect: {\n id: serverId,\n oauthClientId: clientId,\n oauthCode: code\n },\n ...conn.options\n });\n\n if (this.mcpConnections[serverId].connectionState === \"authenticating\") {\n throw new Error(\"Failed to authenticate: client failed to initialize\");\n }\n\n return { serverId };\n }\n\n /**\n * @returns namespaced list of tools\n */\n listTools(): NamespacedData[\"tools\"] {\n return getNamespacedData(this.mcpConnections, \"tools\");\n }\n\n /**\n * @returns a set of tools that you can use with the AI SDK\n */\n unstable_getAITools(): ToolSet {\n return Object.fromEntries(\n getNamespacedData(this.mcpConnections, \"tools\").map((tool) => {\n return [\n `tool_${tool.serverId}_${tool.name}`,\n {\n description: tool.description,\n execute: async (args) => {\n const result = await this.callTool({\n arguments: args,\n name: tool.name,\n serverId: tool.serverId\n });\n if (result.isError) {\n // @ts-expect-error TODO we should fix this\n throw new Error(result.content[0].text);\n }\n return result;\n },\n inputSchema: jsonSchema(tool.inputSchema)\n }\n ];\n })\n );\n }\n\n /**\n * Closes all connections to MCP servers\n */\n async closeAllConnections() {\n return Promise.all(\n Object.values(this.mcpConnections).map(async (connection) => {\n await connection.client.close();\n })\n );\n }\n\n /**\n * Closes a connection to an MCP server\n * @param id The id of the connection to close\n */\n async closeConnection(id: string) {\n if (!this.mcpConnections[id]) {\n throw new Error(`Connection with id \"${id}\" does not exist.`);\n }\n await this.mcpConnections[id].client.close();\n delete this.mcpConnections[id];\n }\n\n /**\n * @returns namespaced list of prompts\n */\n listPrompts(): NamespacedData[\"prompts\"] {\n return getNamespacedData(this.mcpConnections, \"prompts\");\n }\n\n /**\n * @returns namespaced list of tools\n */\n listResources(): NamespacedData[\"resources\"] {\n return getNamespacedData(this.mcpConnections, \"resources\");\n }\n\n /**\n * @returns namespaced list of resource templates\n */\n listResourceTemplates(): NamespacedData[\"resourceTemplates\"] {\n return getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n }\n\n /**\n * Namespaced version of callTool\n */\n callTool(\n params: CallToolRequest[\"params\"] & { serverId: string },\n resultSchema?:\n | typeof CallToolResultSchema\n | typeof CompatibilityCallToolResultSchema,\n options?: RequestOptions\n ) {\n const unqualifiedName = params.name.replace(`${params.serverId}.`, \"\");\n return this.mcpConnections[params.serverId].client.callTool(\n {\n ...params,\n name: unqualifiedName\n },\n resultSchema,\n options\n );\n }\n\n /**\n * Namespaced version of readResource\n */\n readResource(\n params: ReadResourceRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.readResource(\n params,\n options\n );\n }\n\n /**\n * Namespaced version of getPrompt\n */\n getPrompt(\n params: GetPromptRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.getPrompt(\n params,\n options\n );\n }\n}\n\ntype NamespacedData = {\n tools: (Tool & { serverId: string })[];\n prompts: (Prompt & { serverId: string })[];\n resources: (Resource & { serverId: string })[];\n resourceTemplates: (ResourceTemplate & { serverId: string })[];\n};\n\nexport function getNamespacedData<T extends keyof NamespacedData>(\n mcpClients: Record<string, MCPClientConnection>,\n type: T\n): NamespacedData[T] {\n const sets = Object.entries(mcpClients).map(([name, conn]) => {\n return { data: conn[type], name };\n });\n\n const namespacedData = sets.flatMap(({ name: serverId, data }) => {\n return data.map((item) => {\n return {\n ...item,\n // we add a serverId so we can easily pull it out and send the tool call to the right server\n serverId\n };\n });\n });\n\n return namespacedData as NamespacedData[T]; // Type assertion needed due to TS limitations with conditional return types\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { StreamableHTTPClientTransportOptions } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport {\n type ClientCapabilities,\n type ListPromptsResult,\n type ListResourceTemplatesResult,\n type ListResourcesResult,\n type ListToolsResult,\n type Prompt,\n PromptListChangedNotificationSchema,\n type Resource,\n ResourceListChangedNotificationSchema,\n type ResourceTemplate,\n type ServerCapabilities,\n type Tool,\n ToolListChangedNotificationSchema,\n ElicitRequestSchema,\n type ElicitRequest,\n type ElicitResult\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\nimport { SSEEdgeClientTransport } from \"./sse-edge\";\nimport { StreamableHTTPEdgeClientTransport } from \"./streamable-http-edge\";\n\nexport type MCPTransportOptions = (\n | SSEClientTransportOptions\n | StreamableHTTPClientTransportOptions\n) & {\n authProvider?: AgentsOAuthProvider;\n type?: \"sse\" | \"streamable-http\" | \"auto\";\n};\n\ntype TransportType = Exclude<MCPTransportOptions[\"type\"], \"auto\">;\n\nexport class MCPClientConnection {\n client: Client;\n connectionState:\n | \"authenticating\"\n | \"connecting\"\n | \"ready\"\n | \"discovering\"\n | \"failed\" = \"connecting\";\n instructions?: string;\n tools: Tool[] = [];\n prompts: Prompt[] = [];\n resources: Resource[] = [];\n resourceTemplates: ResourceTemplate[] = [];\n serverCapabilities: ServerCapabilities | undefined;\n\n constructor(\n public url: URL,\n info: ConstructorParameters<typeof Client>[0],\n public options: {\n transport: MCPTransportOptions;\n client: ConstructorParameters<typeof Client>[1];\n } = { client: {}, transport: {} }\n ) {\n const clientOptions = {\n ...options.client,\n capabilities: {\n ...options.client?.capabilities,\n elicitation: {}\n } as ClientCapabilities\n };\n\n this.client = new Client(info, clientOptions);\n }\n\n /**\n * Initialize a client connection\n *\n * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized\n * @returns\n */\n async init(code?: string) {\n try {\n const transportType = this.options.transport.type || \"streamable-http\";\n await this.tryConnect(transportType, code);\n // biome-ignore lint/suspicious/noExplicitAny: allow for the error check here\n } catch (e: any) {\n if (e.toString().includes(\"Unauthorized\")) {\n // unauthorized, we should wait for the user to authenticate\n this.connectionState = \"authenticating\";\n return;\n }\n this.connectionState = \"failed\";\n throw e;\n }\n\n this.connectionState = \"discovering\";\n\n this.serverCapabilities = await this.client.getServerCapabilities();\n if (!this.serverCapabilities) {\n throw new Error(\"The MCP Server failed to return server capabilities\");\n }\n\n const [\n instructionsResult,\n toolsResult,\n resourcesResult,\n promptsResult,\n resourceTemplatesResult\n ] = await Promise.allSettled([\n this.client.getInstructions(),\n this.registerTools(),\n this.registerResources(),\n this.registerPrompts(),\n this.registerResourceTemplates()\n ]);\n\n const operations = [\n { name: \"instructions\", result: instructionsResult },\n { name: \"tools\", result: toolsResult },\n { name: \"resources\", result: resourcesResult },\n { name: \"prompts\", result: promptsResult },\n { name: \"resource templates\", result: resourceTemplatesResult }\n ];\n\n for (const { name, result } of operations) {\n if (result.status === \"rejected\") {\n console.error(`Failed to initialize ${name}:`, result.reason);\n }\n }\n\n this.instructions =\n instructionsResult.status === \"fulfilled\"\n ? instructionsResult.value\n : undefined;\n this.tools = toolsResult.status === \"fulfilled\" ? toolsResult.value : [];\n this.resources =\n resourcesResult.status === \"fulfilled\" ? resourcesResult.value : [];\n this.prompts =\n promptsResult.status === \"fulfilled\" ? promptsResult.value : [];\n this.resourceTemplates =\n resourceTemplatesResult.status === \"fulfilled\"\n ? resourceTemplatesResult.value\n : [];\n\n this.connectionState = \"ready\";\n }\n\n /**\n * Notification handler registration\n */\n async registerTools(): Promise<Tool[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.tools) {\n return [];\n }\n\n if (this.serverCapabilities.tools.listChanged) {\n this.client.setNotificationHandler(\n ToolListChangedNotificationSchema,\n async (_notification) => {\n this.tools = await this.fetchTools();\n }\n );\n }\n\n return this.fetchTools();\n }\n\n async registerResources(): Promise<Resource[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n if (this.serverCapabilities.resources.listChanged) {\n this.client.setNotificationHandler(\n ResourceListChangedNotificationSchema,\n async (_notification) => {\n this.resources = await this.fetchResources();\n }\n );\n }\n\n return this.fetchResources();\n }\n\n async registerPrompts(): Promise<Prompt[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.prompts) {\n return [];\n }\n\n if (this.serverCapabilities.prompts.listChanged) {\n this.client.setNotificationHandler(\n PromptListChangedNotificationSchema,\n async (_notification) => {\n this.prompts = await this.fetchPrompts();\n }\n );\n }\n\n return this.fetchPrompts();\n }\n\n async registerResourceTemplates(): Promise<ResourceTemplate[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n return this.fetchResourceTemplates();\n }\n\n async fetchTools() {\n let toolsAgg: Tool[] = [];\n let toolsResult: ListToolsResult = { tools: [] };\n do {\n toolsResult = await this.client\n .listTools({\n cursor: toolsResult.nextCursor\n })\n .catch(capabilityErrorHandler({ tools: [] }, \"tools/list\"));\n toolsAgg = toolsAgg.concat(toolsResult.tools);\n } while (toolsResult.nextCursor);\n return toolsAgg;\n }\n\n async fetchResources() {\n let resourcesAgg: Resource[] = [];\n let resourcesResult: ListResourcesResult = { resources: [] };\n do {\n resourcesResult = await this.client\n .listResources({\n cursor: resourcesResult.nextCursor\n })\n .catch(capabilityErrorHandler({ resources: [] }, \"resources/list\"));\n resourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n } while (resourcesResult.nextCursor);\n return resourcesAgg;\n }\n\n async fetchPrompts() {\n let promptsAgg: Prompt[] = [];\n let promptsResult: ListPromptsResult = { prompts: [] };\n do {\n promptsResult = await this.client\n .listPrompts({\n cursor: promptsResult.nextCursor\n })\n .catch(capabilityErrorHandler({ prompts: [] }, \"prompts/list\"));\n promptsAgg = promptsAgg.concat(promptsResult.prompts);\n } while (promptsResult.nextCursor);\n return promptsAgg;\n }\n\n async fetchResourceTemplates() {\n let templatesAgg: ResourceTemplate[] = [];\n let templatesResult: ListResourceTemplatesResult = {\n resourceTemplates: []\n };\n do {\n templatesResult = await this.client\n .listResourceTemplates({\n cursor: templatesResult.nextCursor\n })\n .catch(\n capabilityErrorHandler(\n { resourceTemplates: [] },\n \"resources/templates/list\"\n )\n );\n templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n } while (templatesResult.nextCursor);\n return templatesAgg;\n }\n\n /**\n * Handle elicitation request from server\n * Automatically uses the Agent's built-in elicitation handling if available\n */\n async handleElicitationRequest(\n _request: ElicitRequest\n ): Promise<ElicitResult> {\n // Elicitation handling must be implemented by the platform\n // For MCP servers, this should be handled by McpAgent.elicitInput()\n throw new Error(\n \"Elicitation handler must be implemented for your platform. Override handleElicitationRequest method.\"\n );\n }\n /**\n * Get the transport for the client\n * @param transportType - The transport type to get\n * @returns The transport for the client\n */\n getTransport(transportType: TransportType) {\n switch (transportType) {\n case \"streamable-http\":\n return new StreamableHTTPEdgeClientTransport(\n this.url,\n this.options.transport as StreamableHTTPClientTransportOptions\n );\n case \"sse\":\n return new SSEEdgeClientTransport(\n this.url,\n this.options.transport as SSEClientTransportOptions\n );\n default:\n throw new Error(`Unsupported transport type: ${transportType}`);\n }\n }\n\n async tryConnect(transportType: MCPTransportOptions[\"type\"], code?: string) {\n const transports: TransportType[] =\n transportType === \"auto\" ? [\"streamable-http\", \"sse\"] : [transportType];\n\n for (const currentTransportType of transports) {\n const isLastTransport =\n currentTransportType === transports[transports.length - 1];\n const hasFallback =\n transportType === \"auto\" &&\n currentTransportType === \"streamable-http\" &&\n !isLastTransport;\n\n const transport = await this.getTransport(currentTransportType);\n\n if (code) {\n await transport.finishAuth(code);\n }\n\n try {\n await this.client.connect(transport);\n break;\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e));\n\n if (\n hasFallback &&\n (error.message.includes(\"404\") || error.message.includes(\"405\"))\n ) {\n // try the next transport if we have a fallback\n continue;\n }\n\n throw e;\n }\n }\n\n // Set up elicitation request handler\n this.client.setRequestHandler(\n ElicitRequestSchema,\n async (request: ElicitRequest) => {\n return await this.handleElicitationRequest(request);\n }\n );\n }\n}\n\nfunction capabilityErrorHandler<T>(empty: T, method: string) {\n return (e: { code: number }) => {\n // server is badly behaved and returning invalid capabilities. This commonly occurs for resource templates\n if (e.code === -32601) {\n console.error(\n `The server advertised support for the capability ${method.split(\"/\")[0]}, but returned \"Method not found\" for '${method}'.`\n );\n return empty;\n }\n throw e;\n };\n}\n","import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport {\n SSEClientTransport,\n type SSEClientTransportOptions\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nexport class SSEEdgeClientTransport extends SSEClientTransport {\n private authProvider: OAuthClientProvider | undefined;\n /**\n * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment\n */\n constructor(url: URL, options: SSEClientTransportOptions) {\n const fetchOverride: typeof fetch = async (\n fetchUrl: RequestInfo | URL,\n fetchInit: RequestInit = {}\n ) => {\n // add auth headers\n const headers = await this.authHeaders();\n const workerOptions = {\n ...fetchInit,\n headers: {\n ...options.requestInit?.headers,\n ...fetchInit?.headers,\n ...headers\n }\n };\n\n // Remove unsupported properties\n delete workerOptions.mode;\n\n // Call the original fetch with fixed options\n return (\n (options.eventSourceInit?.fetch?.(\n fetchUrl as URL | string,\n // @ts-expect-error Expects FetchLikeInit from EventSource but is compatible with RequestInit\n workerOptions\n ) as Promise<Response>) || fetch(fetchUrl, workerOptions)\n );\n };\n\n super(url, {\n ...options,\n eventSourceInit: {\n ...options.eventSourceInit,\n fetch: fetchOverride\n }\n });\n this.authProvider = options.authProvider;\n }\n\n async authHeaders() {\n if (this.authProvider) {\n const tokens = await this.authProvider.tokens();\n if (tokens) {\n return {\n Authorization: `Bearer ${tokens.access_token}`\n };\n }\n }\n }\n}\n","import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport {\n StreamableHTTPClientTransport,\n type StreamableHTTPClientTransportOptions\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\nexport class StreamableHTTPEdgeClientTransport extends StreamableHTTPClientTransport {\n private authProvider: OAuthClientProvider | undefined;\n\n /**\n * Creates a new StreamableHTTPEdgeClientTransport, which overrides fetch to be compatible with the CF workers environment\n */\n constructor(url: URL, options: StreamableHTTPClientTransportOptions) {\n const fetchOverride: typeof fetch = async (\n fetchUrl: RequestInfo | URL,\n fetchInit: RequestInit = {}\n ) => {\n // add auth headers\n const headers = await this.authHeaders();\n const workerOptions = {\n ...fetchInit,\n headers: {\n ...options.requestInit?.headers,\n ...fetchInit?.headers,\n ...headers\n }\n };\n\n // Remove unsupported properties\n delete workerOptions.mode;\n\n // Call the original fetch with fixed options\n return (\n // @ts-expect-error Custom fetch function for Cloudflare Workers compatibility\n (options.requestInit?.fetch?.(\n fetchUrl as URL | string,\n workerOptions\n ) as Promise<Response>) || fetch(fetchUrl, workerOptions)\n );\n };\n\n super(url, {\n ...options,\n requestInit: {\n ...options.requestInit,\n // @ts-expect-error Custom fetch override for Cloudflare Workers\n fetch: fetchOverride\n }\n });\n this.authProvider = options.authProvider;\n }\n\n async authHeaders() {\n if (this.authProvider) {\n const tokens = await this.authProvider.tokens();\n if (tokens) {\n return {\n Authorization: `Bearer ${tokens.access_token}`\n };\n }\n }\n }\n}\n"],"mappings":";AAaA,SAAuB,kBAAkB;AACzC,SAAS,cAAc;;;ACdvB,SAAS,cAAc;AAGvB;AAAA,EAOE;AAAA,EAEA;AAAA,EAIA;AAAA,EACA;AAAA,OAGK;;;ACnBP;AAAA,EACE;AAAA,OAEK;AAEA,IAAM,yBAAN,cAAqC,mBAAmB;AAAA;AAAA;AAAA;AAAA,EAK7D,YAAY,KAAU,SAAoC;AACxD,UAAM,gBAA8B,OACl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