agents 0.0.0-fbf5181 → 0.0.0-fce47ef

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.
Files changed (42) hide show
  1. package/dist/ai-chat-agent.d.ts +46 -4
  2. package/dist/ai-chat-agent.js +138 -68
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-react.d.ts +17 -4
  5. package/dist/ai-react.js +48 -37
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/ai-types.d.ts +5 -0
  8. package/dist/chunk-767EASBA.js +106 -0
  9. package/dist/chunk-767EASBA.js.map +1 -0
  10. package/dist/chunk-E3LCYPCB.js +469 -0
  11. package/dist/chunk-E3LCYPCB.js.map +1 -0
  12. package/dist/chunk-NKZZ66QY.js +116 -0
  13. package/dist/chunk-NKZZ66QY.js.map +1 -0
  14. package/dist/{chunk-XG52S6YY.js → chunk-ZRRXJUAA.js} +357 -160
  15. package/dist/chunk-ZRRXJUAA.js.map +1 -0
  16. package/dist/client.d.ts +15 -1
  17. package/dist/client.js +6 -126
  18. package/dist/client.js.map +1 -1
  19. package/dist/index.d.ts +123 -14
  20. package/dist/index.js +8 -6
  21. package/dist/mcp/client.d.ts +33 -13
  22. package/dist/mcp/client.js +3 -402
  23. package/dist/mcp/client.js.map +1 -1
  24. package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
  25. package/dist/mcp/do-oauth-client-provider.js +3 -103
  26. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  27. package/dist/mcp/index.d.ts +30 -7
  28. package/dist/mcp/index.js +179 -174
  29. package/dist/mcp/index.js.map +1 -1
  30. package/dist/react.d.ts +85 -5
  31. package/dist/react.js +20 -8
  32. package/dist/react.js.map +1 -1
  33. package/dist/schedule.d.ts +2 -2
  34. package/dist/schedule.js +4 -6
  35. package/dist/schedule.js.map +1 -1
  36. package/dist/serializable.d.ts +32 -0
  37. package/dist/serializable.js +1 -0
  38. package/package.json +71 -65
  39. package/src/index.ts +429 -86
  40. package/dist/chunk-HMLY7DHA.js +0 -16
  41. package/dist/chunk-XG52S6YY.js.map +0 -1
  42. /package/dist/{chunk-HMLY7DHA.js.map → serializable.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ai-react.tsx"],"sourcesContent":["import { useChat } from \"@ai-sdk/react\";\nimport type { Message } from \"ai\";\nimport type { useAgent } from \"./react\";\nimport { useEffect, use } from \"react\";\nimport type { OutgoingMessage } from \"./ai-types\";\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions<State> = Omit<\n Parameters<typeof useChat>[0] & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent<State>>;\n getInitialMessages?:\n | undefined\n | null\n // | (() => Message[])\n | ((options: GetInitialMessagesOptions) => Promise<Message[]>);\n },\n \"fetch\"\n>;\n\n// TODO: clear cache when the agent is unmounted?\nconst requestCache = new Map<string, Promise<Message[]>>();\n\n/**\n * React hook for building AI chat interfaces using an Agent\n * @param options Chat options including the agent connection\n * @returns Chat interface controls and state with added clearHistory method\n */\nexport function useAgentChat<State = unknown>(\n options: UseAgentChatOptions<State>\n) {\n const { agent, getInitialMessages, ...rest } = options;\n\n const agentUrl = new URL(\n `${// @ts-expect-error we're using a protected _url property that includes query params\n ((agent._url as string | null) || agent._pkurl)\n ?.replace(\"ws://\", \"http://\")\n .replace(\"wss://\", \"https://\")}`\n );\n\n // delete the _pk query param\n agentUrl.searchParams.delete(\"_pk\");\n const agentUrlString = agentUrl.toString();\n\n async function defaultGetInitialMessagesFetch({\n url,\n }: GetInitialMessagesOptions) {\n const getMessagesUrl = new URL(url);\n getMessagesUrl.pathname += \"/get-messages\";\n const response = await fetch(getMessagesUrl.toString(), {\n headers: options.headers,\n credentials: options.credentials,\n });\n return response.json<Message[]>();\n }\n\n const getInitialMessagesFetch =\n getInitialMessages || defaultGetInitialMessagesFetch;\n\n function doGetInitialMessages(\n getInitialMessagesOptions: GetInitialMessagesOptions\n ) {\n if (requestCache.has(agentUrlString)) {\n return requestCache.get(agentUrlString)!;\n }\n const promise = getInitialMessagesFetch(getInitialMessagesOptions);\n requestCache.set(agentUrlString, promise);\n return promise;\n }\n\n const initialMessages =\n getInitialMessages !== null\n ? use(\n doGetInitialMessages({\n agent: agent.agent,\n name: agent.name,\n url: agentUrlString,\n })\n )\n : rest.initialMessages;\n\n useEffect(() => {\n return () => {\n requestCache.delete(agentUrlString);\n };\n }, [agentUrlString]);\n\n async function aiFetch(\n request: RequestInfo | URL,\n options: RequestInit = {}\n ) {\n // we're going to use a websocket to do the actual \"fetching\"\n // but still satisfy the type signature of the fetch function\n // so we'll return a promise that resolves to a response\n\n const {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n signal,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher, duplex\n } = options;\n const id = crypto.randomUUID();\n const abortController = new AbortController();\n\n signal?.addEventListener(\"abort\", () => {\n abortController.abort();\n });\n\n agent.addEventListener(\n \"message\",\n (event) => {\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_use_chat_response\") {\n if (data.id === id) {\n controller.enqueue(new TextEncoder().encode(data.body));\n if (data.done) {\n controller.close();\n abortController.abort();\n }\n }\n }\n },\n { signal: abortController.signal }\n );\n\n let controller: ReadableStreamDefaultController;\n\n const stream = new ReadableStream({\n start(c) {\n controller = c;\n },\n });\n\n agent.send(\n JSON.stringify({\n type: \"cf_agent_use_chat_request\",\n id,\n url: request.toString(),\n init: {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher,\n // duplex\n },\n })\n );\n\n return new Response(stream);\n }\n const useChatHelpers = useChat({\n initialMessages,\n sendExtraMessageFields: true,\n fetch: aiFetch,\n ...rest,\n });\n\n useEffect(() => {\n function onClearHistory(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_clear\") {\n useChatHelpers.setMessages([]);\n }\n }\n\n function onMessages(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_messages\") {\n useChatHelpers.setMessages(data.messages);\n }\n }\n\n agent.addEventListener(\"message\", onClearHistory);\n agent.addEventListener(\"message\", onMessages);\n\n return () => {\n agent.removeEventListener(\"message\", onClearHistory);\n agent.removeEventListener(\"message\", onMessages);\n };\n }, [agent, useChatHelpers.setMessages]);\n\n return {\n ...useChatHelpers,\n /**\n * Set the chat messages and synchronize with the Agent\n * @param messages New messages to set\n */\n setMessages: (messages: Message[]) => {\n useChatHelpers.setMessages(messages);\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_messages\",\n messages,\n })\n );\n },\n /**\n * Clear chat history on both client and Agent\n */\n clearHistory: () => {\n useChatHelpers.setMessages([]);\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_clear\",\n })\n );\n },\n };\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AAGxB,SAAS,WAAW,WAAW;AA0B/B,IAAM,eAAe,oBAAI,IAAgC;AAOlD,SAAS,aACd,SACA;AACA,QAAM,EAAE,OAAO,oBAAoB,GAAG,KAAK,IAAI;AAE/C,QAAM,WAAW,IAAI;AAAA,IACnB;AAAA,KACE,MAAM,QAA0B,MAAM,SACpC,QAAQ,SAAS,SAAS,EAC3B,QAAQ,UAAU,UAAU,CAAC;AAAA,EAClC;AAGA,WAAS,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AAU;AAClC;AAAA,MACF;AACA,UAAI;AACJ,UAAI;AACF,eAAO,KAAK,MAAM,MAAM,IAAI;AAAA,MAC9B,SAAS,OAAO;AAGd;AAAA,MACF;AACA,UAAI,KAAK,SAAS,0BAA0B;AAC1C,uBAAe,YAAY,KAAK,QAAQ;AAAA,MAC1C;AAAA,IACF;AAEA,UAAM,iBAAiB,WAAW,cAAc;AAChD,UAAM,iBAAiB,WAAW,UAAU;AAE5C,WAAO,MAAM;AACX,YAAM,oBAAoB,WAAW,cAAc;AACnD,YAAM,oBAAoB,WAAW,UAAU;AAAA,IACjD;AAAA,EACF,GAAG,CAAC,OAAO,eAAe,WAAW,CAAC;AAEtC,SAAO;AAAA,IACL,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA,IAKH,aAAa,CAAC,aAAwB;AACpC,qBAAe,YAAY,QAAQ;AACnC,YAAM;AAAA,QACJ,KAAK,UAAU;AAAA,UACb,MAAM;AAAA,UACN;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA;AAAA;AAAA;AAAA,IAIA,cAAc,MAAM;AAClB,qBAAe,YAAY,CAAC,CAAC;AAC7B,YAAM;AAAA,QACJ,KAAK,UAAU;AAAA,UACb,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;","names":["options"]}
1
+ {"version":3,"sources":["../src/ai-react.tsx"],"sourcesContent":["import { useChat } from \"@ai-sdk/react\";\nimport type { Message } from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport { use, useEffect } from \"react\";\nimport type { OutgoingMessage } from \"./ai-types\";\nimport type { useAgent } from \"./react\";\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions<State> = Omit<\n Parameters<typeof useChat>[0] & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent<State>>;\n getInitialMessages?:\n | undefined\n | null\n // | (() => Message[])\n | ((options: GetInitialMessagesOptions) => Promise<Message[]>);\n },\n \"fetch\"\n>;\n\nconst requestCache = new Map<string, Promise<Message[]>>();\n\n/**\n * React hook for building AI chat interfaces using an Agent\n * @param options Chat options including the agent connection\n * @returns Chat interface controls and state with added clearHistory method\n */\nexport function useAgentChat<State = unknown>(\n options: UseAgentChatOptions<State>\n) {\n const { agent, getInitialMessages, ...rest } = options;\n\n const agentUrl = new URL(\n `${// @ts-expect-error we're using a protected _url property that includes query params\n ((agent._url as string | null) || agent._pkurl)\n ?.replace(\"ws://\", \"http://\")\n .replace(\"wss://\", \"https://\")}`\n );\n\n // delete the _pk query param\n agentUrl.searchParams.delete(\"_pk\");\n const agentUrlString = agentUrl.toString();\n\n async function defaultGetInitialMessagesFetch({\n url,\n }: GetInitialMessagesOptions) {\n const getMessagesUrl = new URL(url);\n getMessagesUrl.pathname += \"/get-messages\";\n const response = await fetch(getMessagesUrl.toString(), {\n credentials: options.credentials,\n headers: options.headers,\n });\n return response.json<Message[]>();\n }\n\n const getInitialMessagesFetch =\n getInitialMessages || defaultGetInitialMessagesFetch;\n\n function doGetInitialMessages(\n getInitialMessagesOptions: GetInitialMessagesOptions\n ) {\n if (requestCache.has(agentUrlString)) {\n return requestCache.get(agentUrlString)!;\n }\n const promise = getInitialMessagesFetch(getInitialMessagesOptions);\n // immediately cache the promise so that we don't\n // create multiple requests for the same agent during multiple\n // concurrent renders\n requestCache.set(agentUrlString, promise);\n return promise;\n }\n\n const initialMessagesPromise =\n getInitialMessages === null\n ? null\n : doGetInitialMessages({\n agent: agent.agent,\n name: agent.name,\n url: agentUrlString,\n });\n const initialMessages = initialMessagesPromise\n ? use(initialMessagesPromise)\n : (rest.initialMessages ?? []);\n\n // manages adding and removing the promise from the cache\n useEffect(() => {\n if (!initialMessagesPromise) {\n return;\n }\n // this effect is responsible for removing the promise from the cache\n // when the component unmounts or the promise changes,\n // but that means it also must add the promise to the cache\n // so that multiple arbitrary effect runs produce the expected state\n // when resolved.\n requestCache.set(agentUrlString, initialMessagesPromise!);\n return () => {\n if (requestCache.get(agentUrlString) === initialMessagesPromise) {\n requestCache.delete(agentUrlString);\n }\n };\n }, [agentUrlString, initialMessagesPromise]);\n\n async function aiFetch(\n request: RequestInfo | URL,\n options: RequestInit = {}\n ) {\n // we're going to use a websocket to do the actual \"fetching\"\n // but still satisfy the type signature of the fetch function\n // so we'll return a promise that resolves to a response\n\n const {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n signal,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher, duplex\n } = options;\n const id = nanoid(8);\n const abortController = new AbortController();\n\n signal?.addEventListener(\"abort\", () => {\n // Propagate request cancellation to the Agent\n // We need to communciate cancellation as a websocket message, instead of a request signal\n agent.send(\n JSON.stringify({\n id,\n type: \"cf_agent_chat_request_cancel\",\n })\n );\n\n // NOTE - If we wanted to, we could preserve the \"interrupted\" message here, with the code below\n // However, I think it might be the responsibility of the library user to implement that behavior manually?\n // Reasoning: This code could be subject to collisions, as it \"force saves\" the messages we have locally\n //\n // agent.send(JSON.stringify({\n // type: \"cf_agent_chat_messages\",\n // messages: ... /* some way of getting current messages ref? */\n // }))\n\n abortController.abort();\n // Make sure to also close the stream (cf. https://github.com/cloudflare/agents-starter/issues/69)\n controller.close();\n });\n\n agent.addEventListener(\n \"message\",\n (event) => {\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_use_chat_response\") {\n if (data.id === id) {\n controller.enqueue(new TextEncoder().encode(data.body));\n if (data.done) {\n controller.close();\n abortController.abort();\n }\n }\n }\n },\n { signal: abortController.signal }\n );\n\n let controller: ReadableStreamDefaultController;\n\n const stream = new ReadableStream({\n start(c) {\n controller = c;\n },\n });\n\n agent.send(\n JSON.stringify({\n id,\n init: {\n body,\n credentials,\n headers,\n integrity,\n keepalive,\n method,\n mode,\n redirect,\n referrer,\n referrerPolicy,\n window,\n // dispatcher,\n // duplex\n },\n type: \"cf_agent_use_chat_request\",\n url: request.toString(),\n })\n );\n\n return new Response(stream);\n }\n const useChatHelpers = useChat({\n fetch: aiFetch,\n initialMessages,\n sendExtraMessageFields: true,\n ...rest,\n });\n\n useEffect(() => {\n function onClearHistory(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_clear\") {\n useChatHelpers.setMessages([]);\n }\n }\n\n function onMessages(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_messages\") {\n useChatHelpers.setMessages(data.messages);\n }\n }\n\n agent.addEventListener(\"message\", onClearHistory);\n agent.addEventListener(\"message\", onMessages);\n\n return () => {\n agent.removeEventListener(\"message\", onClearHistory);\n agent.removeEventListener(\"message\", onMessages);\n };\n }, [agent, useChatHelpers.setMessages]);\n\n return {\n ...useChatHelpers,\n /**\n * Clear chat history on both client and Agent\n */\n clearHistory: () => {\n useChatHelpers.setMessages([]);\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_clear\",\n })\n );\n },\n /**\n * Set the chat messages and synchronize with the Agent\n * @param messages New messages to set\n */\n setMessages: (messages: Message[]) => {\n useChatHelpers.setMessages(messages);\n agent.send(\n JSON.stringify({\n messages,\n type: \"cf_agent_chat_messages\",\n })\n );\n },\n };\n}\n"],"mappings":";AAAA,SAAS,eAAe;AAExB,SAAS,cAAc;AACvB,SAAS,KAAK,iBAAiB;AA0B/B,IAAM,eAAe,oBAAI,IAAgC;AAOlD,SAAS,aACd,SACA;AACA,QAAM,EAAE,OAAO,oB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MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;","names":["options"]}
@@ -64,6 +64,11 @@ type IncomingMessage =
64
64
  type: "cf_agent_chat_messages";
65
65
  /** Array of chat messages */
66
66
  messages: Message[];
67
+ }
68
+ | {
69
+ /** Indicates the user wants to stop generation of this message */
70
+ type: "cf_agent_chat_request_cancel";
71
+ id: string;
67
72
  };
68
73
 
69
74
  export type { IncomingMessage, OutgoingMessage };
@@ -0,0 +1,106 @@
1
+ // src/mcp/do-oauth-client-provider.ts
2
+ var DurableObjectOAuthClientProvider = class {
3
+ constructor(storage, clientName, baseRedirectUrl) {
4
+ this.storage = storage;
5
+ this.clientName = clientName;
6
+ this.baseRedirectUrl = baseRedirectUrl;
7
+ }
8
+ get clientMetadata() {
9
+ return {
10
+ client_name: this.clientName,
11
+ client_uri: "example.com",
12
+ grant_types: ["authorization_code", "refresh_token"],
13
+ redirect_uris: [this.redirectUrl],
14
+ response_types: ["code"],
15
+ token_endpoint_auth_method: "none"
16
+ };
17
+ }
18
+ get redirectUrl() {
19
+ return `${this.baseRedirectUrl}/${this.serverId}`;
20
+ }
21
+ get clientId() {
22
+ if (!this._clientId_) {
23
+ throw new Error("Trying to access clientId before it was set");
24
+ }
25
+ return this._clientId_;
26
+ }
27
+ set clientId(clientId_) {
28
+ this._clientId_ = clientId_;
29
+ }
30
+ get serverId() {
31
+ if (!this._serverId_) {
32
+ throw new Error("Trying to access serverId before it was set");
33
+ }
34
+ return this._serverId_;
35
+ }
36
+ set serverId(serverId_) {
37
+ this._serverId_ = serverId_;
38
+ }
39
+ keyPrefix(clientId) {
40
+ return `/${this.clientName}/${this.serverId}/${clientId}`;
41
+ }
42
+ clientInfoKey(clientId) {
43
+ return `${this.keyPrefix(clientId)}/client_info/`;
44
+ }
45
+ async clientInformation() {
46
+ if (!this._clientId_) {
47
+ return void 0;
48
+ }
49
+ return await this.storage.get(
50
+ this.clientInfoKey(this.clientId)
51
+ ) ?? void 0;
52
+ }
53
+ async saveClientInformation(clientInformation) {
54
+ await this.storage.put(
55
+ this.clientInfoKey(clientInformation.client_id),
56
+ clientInformation
57
+ );
58
+ this.clientId = clientInformation.client_id;
59
+ }
60
+ tokenKey(clientId) {
61
+ return `${this.keyPrefix(clientId)}/token`;
62
+ }
63
+ async tokens() {
64
+ if (!this._clientId_) {
65
+ return void 0;
66
+ }
67
+ return await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;
68
+ }
69
+ async saveTokens(tokens) {
70
+ await this.storage.put(this.tokenKey(this.clientId), tokens);
71
+ }
72
+ get authUrl() {
73
+ return this._authUrl_;
74
+ }
75
+ /**
76
+ * Because this operates on the server side (but we need browser auth), we send this url back to the user
77
+ * and require user interact to initiate the redirect flow
78
+ */
79
+ async redirectToAuthorization(authUrl) {
80
+ const client_id = authUrl.searchParams.get("client_id");
81
+ if (client_id) {
82
+ authUrl.searchParams.append("state", client_id);
83
+ }
84
+ this._authUrl_ = authUrl.toString();
85
+ }
86
+ codeVerifierKey(clientId) {
87
+ return `${this.keyPrefix(clientId)}/code_verifier`;
88
+ }
89
+ async saveCodeVerifier(verifier) {
90
+ await this.storage.put(this.codeVerifierKey(this.clientId), verifier);
91
+ }
92
+ async codeVerifier() {
93
+ const codeVerifier = await this.storage.get(
94
+ this.codeVerifierKey(this.clientId)
95
+ );
96
+ if (!codeVerifier) {
97
+ throw new Error("No code verifier found");
98
+ }
99
+ return codeVerifier;
100
+ }
101
+ };
102
+
103
+ export {
104
+ DurableObjectOAuthClientProvider
105
+ };
106
+ //# sourceMappingURL=chunk-767EASBA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/do-oauth-client-provider.ts"],"sourcesContent":["import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport type {\n OAuthClientInformation,\n OAuthClientInformationFull,\n OAuthClientMetadata,\n OAuthTokens,\n} from \"@modelcontextprotocol/sdk/shared/auth.js\";\n\n// A slight extension to the standard OAuthClientProvider interface because `redirectToAuthorization` doesn't give us the interface we need\n// This allows us to track authentication for a specific server and associated dynamic client registration\nexport interface AgentsOAuthProvider extends OAuthClientProvider {\n authUrl: string | undefined;\n clientId: string | undefined;\n serverId: string | undefined;\n}\n\nexport class DurableObjectOAuthClientProvider implements AgentsOAuthProvider {\n private _authUrl_: string | undefined;\n private _serverId_: string | undefined;\n private _clientId_: string | undefined;\n\n constructor(\n public storage: DurableObjectStorage,\n public clientName: string,\n public baseRedirectUrl: string\n ) {}\n\n get clientMetadata(): OAuthClientMetadata {\n return {\n client_name: this.clientName,\n client_uri: \"example.com\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n redirect_uris: [this.redirectUrl],\n response_types: [\"code\"],\n token_endpoint_auth_method: \"none\",\n };\n }\n\n get redirectUrl() {\n return `${this.baseRedirectUrl}/${this.serverId}`;\n }\n\n get clientId() {\n if (!this._clientId_) {\n throw new Error(\"Trying to access clientId before it was set\");\n }\n return this._clientId_;\n }\n\n set clientId(clientId_: string) {\n this._clientId_ = clientId_;\n }\n\n get serverId() {\n if (!this._serverId_) {\n throw new Error(\"Trying to access serverId before it was set\");\n }\n return this._serverId_;\n }\n\n set serverId(serverId_: string) {\n this._serverId_ = serverId_;\n }\n\n keyPrefix(clientId: string) {\n return `/${this.clientName}/${this.serverId}/${clientId}`;\n }\n\n clientInfoKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/client_info/`;\n }\n\n async clientInformation(): Promise<OAuthClientInformation | undefined> {\n if (!this._clientId_) {\n return undefined;\n }\n return (\n (await this.storage.get<OAuthClientInformation>(\n this.clientInfoKey(this.clientId)\n )) ?? undefined\n );\n }\n\n async saveClientInformation(\n clientInformation: OAuthClientInformationFull\n ): Promise<void> {\n await this.storage.put(\n this.clientInfoKey(clientInformation.client_id),\n clientInformation\n );\n this.clientId = clientInformation.client_id;\n }\n\n tokenKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/token`;\n }\n\n async tokens(): Promise<OAuthTokens | undefined> {\n if (!this._clientId_) {\n return undefined;\n }\n return (\n (await this.storage.get<OAuthTokens>(this.tokenKey(this.clientId))) ??\n undefined\n );\n }\n\n async saveTokens(tokens: OAuthTokens): Promise<void> {\n await this.storage.put(this.tokenKey(this.clientId), tokens);\n }\n\n get authUrl() {\n return this._authUrl_;\n }\n\n /**\n * Because this operates on the server side (but we need browser auth), we send this url back to the user\n * and require user interact to initiate the redirect flow\n */\n async redirectToAuthorization(authUrl: URL): Promise<void> {\n // We want to track the client ID in state here because the typescript SSE client sometimes does\n // a dynamic client registration AFTER generating this redirect URL.\n const client_id = authUrl.searchParams.get(\"client_id\");\n if (client_id) {\n authUrl.searchParams.append(\"state\", client_id);\n }\n this._authUrl_ = authUrl.toString();\n }\n\n codeVerifierKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/code_verifier`;\n }\n\n async saveCodeVerifier(verifier: string): Promise<void> {\n await this.storage.put(this.codeVerifierKey(this.clientId), verifier);\n }\n\n async codeVerifier(): Promise<string> {\n const codeVerifier = await this.storage.get<string>(\n this.codeVerifierKey(this.clientId)\n );\n if (!codeVerifier) {\n throw new Error(\"No code verifier found\");\n }\n return codeVerifier;\n }\n}\n"],"mappings":";AAgBO,IAAM,mCAAN,MAAsE;AAAA,EAK3E,YACS,SACA,YACA,iBACP;AAHO;AACA;AACA;AAAA,EACN;AAAA,EAEH,IAAI,iBAAsC;AACxC,WAAO;AAAA,MACL,aAAa,KAAK;AAAA,MAClB,YAAY;AAAA,MACZ,aAAa,CAAC,sBAAsB,eAAe;AAAA,MACnD,eAAe,CAAC,KAAK,WAAW;AAAA,MAChC,gBAAgB,CAAC,MAAM;AAAA,MACvB,4BAA4B;AAAA,IAC9B;AAAA,EACF;AAAA,EAEA,IAAI,cAAc;AAChB,WAAO,GAAG,KAAK,eAAe,IAAI,KAAK,QAAQ;AAAA,EACjD;AAAA,EAEA,IAAI,WAAW;AACb,QAAI,CAAC,KAAK,YAAY;AACpB,YAAM,IAAI,MAAM,6CAA6C;AAA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;AAAA;AAAA,EAMA,MAAM,wBAAwB,SAA6B;AAGzD,UAAM,YAAY,QAAQ,aAAa,IAAI,WAAW;AACtD,QAAI,WAAW;AACb,cAAQ,aAAa,OAAO,SAAS,SAAS;AAAA,IAChD;AACA,SAAK,YAAY,QAAQ,SAAS;AAAA,EACpC;AAAA,EAEA,gBAAgB,UAAkB;AAChC,WAAO,GAAG,KAAK,UAAU,QAAQ,CAAC;AAAA,EACpC;AAAA,EAEA,MAAM,iBAAiB,UAAiC;AACtD,UAAM,KAAK,QAAQ,IAAI,KAAK,gBAAgB,KAAK,QAAQ,GAAG,QAAQ;AAAA,EACtE;AAAA,EAEA,MAAM,eAAgC;AACpC,UAAM,eAAe,MAAM,KAAK,QAAQ;AAAA,MACtC,KAAK,gBAAgB,KAAK,QAAQ;AAAA,IACpC;AACA,QAAI,CAAC,cAAc;AACjB,YAAM,IAAI,MAAM,wBAAwB;AAAA,IAC1C;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -0,0 +1,469 @@
1
+ // src/mcp/client.ts
2
+ import { jsonSchema } from "ai";
3
+ import { nanoid } from "nanoid";
4
+
5
+ // src/mcp/client-connection.ts
6
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
7
+ import {
8
+ PromptListChangedNotificationSchema,
9
+ ResourceListChangedNotificationSchema,
10
+ ToolListChangedNotificationSchema
11
+ } from "@modelcontextprotocol/sdk/types.js";
12
+
13
+ // src/mcp/sse-edge.ts
14
+ import {
15
+ SSEClientTransport
16
+ } from "@modelcontextprotocol/sdk/client/sse.js";
17
+ var SSEEdgeClientTransport = class extends SSEClientTransport {
18
+ /**
19
+ * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment
20
+ */
21
+ constructor(url, options) {
22
+ const fetchOverride = async (fetchUrl, fetchInit = {}) => {
23
+ const headers = await this.authHeaders();
24
+ const workerOptions = {
25
+ ...fetchInit,
26
+ headers: {
27
+ ...options.requestInit?.headers,
28
+ ...fetchInit?.headers,
29
+ ...headers
30
+ }
31
+ };
32
+ delete workerOptions.mode;
33
+ return options.eventSourceInit?.fetch?.(
34
+ fetchUrl,
35
+ // @ts-expect-error Expects FetchLikeInit from EventSource but is compatible with RequestInit
36
+ workerOptions
37
+ ) || fetch(fetchUrl, workerOptions);
38
+ };
39
+ super(url, {
40
+ ...options,
41
+ eventSourceInit: {
42
+ ...options.eventSourceInit,
43
+ fetch: fetchOverride
44
+ }
45
+ });
46
+ this.authProvider = options.authProvider;
47
+ }
48
+ async authHeaders() {
49
+ if (this.authProvider) {
50
+ const tokens = await this.authProvider.tokens();
51
+ if (tokens) {
52
+ return {
53
+ Authorization: `Bearer ${tokens.access_token}`
54
+ };
55
+ }
56
+ }
57
+ }
58
+ };
59
+
60
+ // src/mcp/client-connection.ts
61
+ var MCPClientConnection = class {
62
+ constructor(url, info, options = { client: {}, transport: {} }) {
63
+ this.url = url;
64
+ this.options = options;
65
+ this.connectionState = "connecting";
66
+ this.tools = [];
67
+ this.prompts = [];
68
+ this.resources = [];
69
+ this.resourceTemplates = [];
70
+ this.client = new Client(info, options.client);
71
+ }
72
+ /**
73
+ * Initialize a client connection
74
+ *
75
+ * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized
76
+ * @returns
77
+ */
78
+ async init(code) {
79
+ try {
80
+ const transport = new SSEEdgeClientTransport(
81
+ this.url,
82
+ this.options.transport
83
+ );
84
+ if (code) {
85
+ await transport.finishAuth(code);
86
+ }
87
+ await this.client.connect(transport);
88
+ } catch (e) {
89
+ if (e.toString().includes("Unauthorized")) {
90
+ this.connectionState = "authenticating";
91
+ return;
92
+ }
93
+ this.connectionState = "failed";
94
+ throw e;
95
+ }
96
+ this.connectionState = "discovering";
97
+ this.serverCapabilities = await this.client.getServerCapabilities();
98
+ if (!this.serverCapabilities) {
99
+ throw new Error("The MCP Server failed to return server capabilities");
100
+ }
101
+ const [instructions, tools, resources, prompts, resourceTemplates] = await Promise.all([
102
+ this.client.getInstructions(),
103
+ this.registerTools(),
104
+ this.registerResources(),
105
+ this.registerPrompts(),
106
+ this.registerResourceTemplates()
107
+ ]);
108
+ this.instructions = instructions;
109
+ this.tools = tools;
110
+ this.resources = resources;
111
+ this.prompts = prompts;
112
+ this.resourceTemplates = resourceTemplates;
113
+ this.connectionState = "ready";
114
+ }
115
+ /**
116
+ * Notification handler registration
117
+ */
118
+ async registerTools() {
119
+ if (!this.serverCapabilities || !this.serverCapabilities.tools) {
120
+ return [];
121
+ }
122
+ if (this.serverCapabilities.tools.listChanged) {
123
+ this.client.setNotificationHandler(
124
+ ToolListChangedNotificationSchema,
125
+ async (_notification) => {
126
+ this.tools = await this.fetchTools();
127
+ }
128
+ );
129
+ }
130
+ return this.fetchTools();
131
+ }
132
+ async registerResources() {
133
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) {
134
+ return [];
135
+ }
136
+ if (this.serverCapabilities.resources.listChanged) {
137
+ this.client.setNotificationHandler(
138
+ ResourceListChangedNotificationSchema,
139
+ async (_notification) => {
140
+ this.resources = await this.fetchResources();
141
+ }
142
+ );
143
+ }
144
+ return this.fetchResources();
145
+ }
146
+ async registerPrompts() {
147
+ if (!this.serverCapabilities || !this.serverCapabilities.prompts) {
148
+ return [];
149
+ }
150
+ if (this.serverCapabilities.prompts.listChanged) {
151
+ this.client.setNotificationHandler(
152
+ PromptListChangedNotificationSchema,
153
+ async (_notification) => {
154
+ this.prompts = await this.fetchPrompts();
155
+ }
156
+ );
157
+ }
158
+ return this.fetchPrompts();
159
+ }
160
+ async registerResourceTemplates() {
161
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) {
162
+ return [];
163
+ }
164
+ return this.fetchResourceTemplates();
165
+ }
166
+ async fetchTools() {
167
+ let toolsAgg = [];
168
+ let toolsResult = { tools: [] };
169
+ do {
170
+ toolsResult = await this.client.listTools({
171
+ cursor: toolsResult.nextCursor
172
+ }).catch(capabilityErrorHandler({ tools: [] }, "tools/list"));
173
+ toolsAgg = toolsAgg.concat(toolsResult.tools);
174
+ } while (toolsResult.nextCursor);
175
+ return toolsAgg;
176
+ }
177
+ async fetchResources() {
178
+ let resourcesAgg = [];
179
+ let resourcesResult = { resources: [] };
180
+ do {
181
+ resourcesResult = await this.client.listResources({
182
+ cursor: resourcesResult.nextCursor
183
+ }).catch(capabilityErrorHandler({ resources: [] }, "resources/list"));
184
+ resourcesAgg = resourcesAgg.concat(resourcesResult.resources);
185
+ } while (resourcesResult.nextCursor);
186
+ return resourcesAgg;
187
+ }
188
+ async fetchPrompts() {
189
+ let promptsAgg = [];
190
+ let promptsResult = { prompts: [] };
191
+ do {
192
+ promptsResult = await this.client.listPrompts({
193
+ cursor: promptsResult.nextCursor
194
+ }).catch(capabilityErrorHandler({ prompts: [] }, "prompts/list"));
195
+ promptsAgg = promptsAgg.concat(promptsResult.prompts);
196
+ } while (promptsResult.nextCursor);
197
+ return promptsAgg;
198
+ }
199
+ async fetchResourceTemplates() {
200
+ let templatesAgg = [];
201
+ let templatesResult = {
202
+ resourceTemplates: []
203
+ };
204
+ do {
205
+ templatesResult = await this.client.listResourceTemplates({
206
+ cursor: templatesResult.nextCursor
207
+ }).catch(
208
+ capabilityErrorHandler(
209
+ { resourceTemplates: [] },
210
+ "resources/templates/list"
211
+ )
212
+ );
213
+ templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);
214
+ } while (templatesResult.nextCursor);
215
+ return templatesAgg;
216
+ }
217
+ };
218
+ function capabilityErrorHandler(empty, method) {
219
+ return (e) => {
220
+ if (e.code === -32601) {
221
+ console.error(
222
+ `The server advertised support for the capability ${method.split("/")[0]}, but returned "Method not found" for '${method}'.`
223
+ );
224
+ return empty;
225
+ }
226
+ throw e;
227
+ };
228
+ }
229
+
230
+ // src/mcp/client.ts
231
+ var MCPClientManager = class {
232
+ /**
233
+ * @param _name Name of the MCP client
234
+ * @param _version Version of the MCP Client
235
+ * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
236
+ */
237
+ constructor(_name, _version) {
238
+ this._name = _name;
239
+ this._version = _version;
240
+ this.mcpConnections = {};
241
+ this._callbackUrls = [];
242
+ }
243
+ /**
244
+ * Connect to and register an MCP server
245
+ *
246
+ * @param transportConfig Transport config
247
+ * @param clientConfig Client config
248
+ * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
249
+ */
250
+ async connect(url, options = {}) {
251
+ const id = options.reconnect?.id ?? nanoid(8);
252
+ if (!options.transport?.authProvider) {
253
+ console.warn(
254
+ "No authProvider provided in the transport options. This client will only support unauthenticated remote MCP Servers"
255
+ );
256
+ } else {
257
+ options.transport.authProvider.serverId = id;
258
+ if (options.reconnect?.oauthClientId) {
259
+ options.transport.authProvider.clientId = options.reconnect?.oauthClientId;
260
+ }
261
+ }
262
+ this.mcpConnections[id] = new MCPClientConnection(
263
+ new URL(url),
264
+ {
265
+ name: this._name,
266
+ version: this._version
267
+ },
268
+ {
269
+ client: options.client ?? {},
270
+ transport: options.transport ?? {}
271
+ }
272
+ );
273
+ await this.mcpConnections[id].init(options.reconnect?.oauthCode);
274
+ const authUrl = options.transport?.authProvider?.authUrl;
275
+ if (authUrl && options.transport?.authProvider?.redirectUrl) {
276
+ this._callbackUrls.push(
277
+ options.transport.authProvider.redirectUrl.toString()
278
+ );
279
+ return {
280
+ authUrl,
281
+ clientId: options.transport?.authProvider?.clientId,
282
+ id
283
+ };
284
+ }
285
+ return {
286
+ id
287
+ };
288
+ }
289
+ isCallbackRequest(req) {
290
+ return req.method === "GET" && !!this._callbackUrls.find((url) => {
291
+ return req.url.startsWith(url);
292
+ });
293
+ }
294
+ async handleCallbackRequest(req) {
295
+ const url = new URL(req.url);
296
+ const urlMatch = this._callbackUrls.find((url2) => {
297
+ return req.url.startsWith(url2);
298
+ });
299
+ if (!urlMatch) {
300
+ throw new Error(
301
+ `No callback URI match found for the request url: ${req.url}. Was the request matched with \`isCallbackRequest()\`?`
302
+ );
303
+ }
304
+ const code = url.searchParams.get("code");
305
+ const clientId = url.searchParams.get("state");
306
+ const urlParams = urlMatch.split("/");
307
+ const serverId = urlParams[urlParams.length - 1];
308
+ if (!code) {
309
+ throw new Error("Unauthorized: no code provided");
310
+ }
311
+ if (!clientId) {
312
+ throw new Error("Unauthorized: no state provided");
313
+ }
314
+ if (this.mcpConnections[serverId] === void 0) {
315
+ throw new Error(`Could not find serverId: ${serverId}`);
316
+ }
317
+ if (this.mcpConnections[serverId].connectionState !== "authenticating") {
318
+ throw new Error(
319
+ "Failed to authenticate: the client isn't in the `authenticating` state"
320
+ );
321
+ }
322
+ const conn = this.mcpConnections[serverId];
323
+ if (!conn.options.transport.authProvider) {
324
+ throw new Error(
325
+ "Trying to finalize authentication for a server connection without an authProvider"
326
+ );
327
+ }
328
+ conn.options.transport.authProvider.clientId = clientId;
329
+ conn.options.transport.authProvider.serverId = serverId;
330
+ const serverUrl = conn.url.toString();
331
+ await this.connect(serverUrl, {
332
+ reconnect: {
333
+ id: serverId,
334
+ oauthClientId: clientId,
335
+ oauthCode: code
336
+ },
337
+ ...conn.options
338
+ });
339
+ if (this.mcpConnections[serverId].connectionState === "authenticating") {
340
+ throw new Error("Failed to authenticate: client failed to initialize");
341
+ }
342
+ return { serverId };
343
+ }
344
+ /**
345
+ * @returns namespaced list of tools
346
+ */
347
+ listTools() {
348
+ return getNamespacedData(this.mcpConnections, "tools");
349
+ }
350
+ /**
351
+ * @returns a set of tools that you can use with the AI SDK
352
+ */
353
+ unstable_getAITools() {
354
+ return Object.fromEntries(
355
+ getNamespacedData(this.mcpConnections, "tools").map((tool) => {
356
+ return [
357
+ `${tool.serverId}_${tool.name}`,
358
+ {
359
+ description: tool.description,
360
+ execute: async (args) => {
361
+ const result = await this.callTool({
362
+ arguments: args,
363
+ name: tool.name,
364
+ serverId: tool.serverId
365
+ });
366
+ if (result.isError) {
367
+ throw new Error(result.content[0].text);
368
+ }
369
+ return result;
370
+ },
371
+ parameters: jsonSchema(tool.inputSchema)
372
+ }
373
+ ];
374
+ })
375
+ );
376
+ }
377
+ /**
378
+ * Closes all connections to MCP servers
379
+ */
380
+ async closeAllConnections() {
381
+ return Promise.all(
382
+ Object.values(this.mcpConnections).map(async (connection) => {
383
+ await connection.client.close();
384
+ })
385
+ );
386
+ }
387
+ /**
388
+ * Closes a connection to an MCP server
389
+ * @param id The id of the connection to close
390
+ */
391
+ async closeConnection(id) {
392
+ if (!this.mcpConnections[id]) {
393
+ throw new Error(`Connection with id "${id}" does not exist.`);
394
+ }
395
+ await this.mcpConnections[id].client.close();
396
+ delete this.mcpConnections[id];
397
+ }
398
+ /**
399
+ * @returns namespaced list of prompts
400
+ */
401
+ listPrompts() {
402
+ return getNamespacedData(this.mcpConnections, "prompts");
403
+ }
404
+ /**
405
+ * @returns namespaced list of tools
406
+ */
407
+ listResources() {
408
+ return getNamespacedData(this.mcpConnections, "resources");
409
+ }
410
+ /**
411
+ * @returns namespaced list of resource templates
412
+ */
413
+ listResourceTemplates() {
414
+ return getNamespacedData(this.mcpConnections, "resourceTemplates");
415
+ }
416
+ /**
417
+ * Namespaced version of callTool
418
+ */
419
+ callTool(params, resultSchema, options) {
420
+ const unqualifiedName = params.name.replace(`${params.serverId}.`, "");
421
+ return this.mcpConnections[params.serverId].client.callTool(
422
+ {
423
+ ...params,
424
+ name: unqualifiedName
425
+ },
426
+ resultSchema,
427
+ options
428
+ );
429
+ }
430
+ /**
431
+ * Namespaced version of readResource
432
+ */
433
+ readResource(params, options) {
434
+ return this.mcpConnections[params.serverId].client.readResource(
435
+ params,
436
+ options
437
+ );
438
+ }
439
+ /**
440
+ * Namespaced version of getPrompt
441
+ */
442
+ getPrompt(params, options) {
443
+ return this.mcpConnections[params.serverId].client.getPrompt(
444
+ params,
445
+ options
446
+ );
447
+ }
448
+ };
449
+ function getNamespacedData(mcpClients, type) {
450
+ const sets = Object.entries(mcpClients).map(([name, conn]) => {
451
+ return { data: conn[type], name };
452
+ });
453
+ const namespacedData = sets.flatMap(({ name: serverId, data }) => {
454
+ return data.map((item) => {
455
+ return {
456
+ ...item,
457
+ // we add a serverId so we can easily pull it out and send the tool call to the right server
458
+ serverId
459
+ };
460
+ });
461
+ });
462
+ return namespacedData;
463
+ }
464
+
465
+ export {
466
+ MCPClientManager,
467
+ getNamespacedData
468
+ };
469
+ //# sourceMappingURL=chunk-E3LCYPCB.js.map