agents 0.0.0-25aeaf2 → 0.0.0-2662748
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-chat-agent.d.ts +28 -2
- package/dist/ai-chat-agent.js +99 -105
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +2 -1
- package/dist/ai-react.js +0 -2
- package/dist/ai-react.js.map +1 -1
- package/dist/{chunk-D6UOOELW.js → chunk-BZXOAZUX.js} +11 -11
- package/dist/chunk-BZXOAZUX.js.map +1 -0
- package/dist/{chunk-25YDMV4H.js → chunk-OYJXQRRH.js} +13 -12
- package/dist/chunk-OYJXQRRH.js.map +1 -0
- package/dist/{chunk-YFPCCSZO.js → chunk-P3RZJ72N.js} +183 -187
- package/dist/chunk-P3RZJ72N.js.map +1 -0
- package/dist/{chunk-RN4SNE73.js → chunk-VCSB47AK.js} +10 -27
- package/dist/chunk-VCSB47AK.js.map +1 -0
- package/dist/client.d.ts +8 -1
- package/dist/client.js +1 -2
- package/dist/index.d.ts +47 -3
- package/dist/index.js +4 -5
- package/dist/mcp/client.d.ts +6 -6
- package/dist/mcp/client.js +1 -2
- package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
- package/dist/mcp/do-oauth-client-provider.js +1 -2
- package/dist/mcp/index.d.ts +10 -1
- package/dist/mcp/index.js +90 -126
- package/dist/mcp/index.js.map +1 -1
- package/dist/react.d.ts +73 -7
- package/dist/react.js +10 -2
- package/dist/react.js.map +1 -1
- package/dist/schedule.js +0 -2
- package/dist/schedule.js.map +1 -1
- package/dist/serializable.d.ts +32 -0
- package/dist/serializable.js +1 -0
- package/package.json +8 -8
- package/src/index.ts +86 -78
- package/dist/chunk-25YDMV4H.js.map +0 -1
- package/dist/chunk-D6UOOELW.js.map +0 -1
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-RN4SNE73.js.map +0 -1
- package/dist/chunk-YFPCCSZO.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → serializable.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mcp/sse-edge.ts","../src/mcp/client-connection.ts","../src/mcp/client.ts"],"sourcesContent":["import {\n SSEClientTransport,\n type SSEClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.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 // biome-ignore lint/performance/noDelete: workaround for workers environment\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 { SSEEdgeClientTransport } from \"./sse-edge\";\n\nimport {\n ToolListChangedNotificationSchema,\n type ClientCapabilities,\n type Resource,\n type Tool,\n type Prompt,\n ResourceListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n type ListToolsResult,\n type ListResourcesResult,\n type ListPromptsResult,\n type ServerCapabilities,\n type ResourceTemplate,\n type ListResourceTemplatesResult,\n type Notification,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\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: SSEClientTransportOptions & {\n authProvider?: AgentsOAuthProvider;\n };\n client: ConstructorParameters<typeof Client>[1];\n } = { transport: {}, client: {} }\n ) {\n this.client = new Client(info, options.client);\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 transport = new SSEEdgeClientTransport(\n this.url,\n this.options.transport\n );\n\n if (code) {\n await transport.finishAuth(code);\n }\n\n await this.client.connect(transport);\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 [instructions, tools, resources, prompts, resourceTemplates] =\n await Promise.all([\n this.client.getInstructions(),\n this.registerTools(),\n this.registerResources(),\n this.registerPrompts(),\n this.registerResourceTemplates(),\n ]);\n\n this.instructions = instructions;\n this.tools = tools;\n this.resources = resources;\n this.prompts = prompts;\n this.resourceTemplates = resourceTemplates;\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\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 { MCPClientConnection } from \"./client-connection\";\n\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.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 { jsonSchema, type ToolSet } from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\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?: SSEClientTransportOptions & {\n authProvider?: AgentsOAuthProvider;\n };\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 transport: options.transport ?? {},\n client: options.client ?? {},\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 id,\n authUrl,\n clientId: options.transport?.authProvider?.clientId,\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.serverId}_${tool.name}`,\n {\n parameters: jsonSchema(tool.inputSchema),\n description: tool.description,\n execute: async (args) => {\n const result = await this.callTool({\n name: tool.name,\n arguments: args,\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 },\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 { name, data: conn[type] };\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"],"mappings":";AAAA;AAAA,EACE;AAAA,OAEK;AAGA,IAAM,yBAAN,cAAqC,mBAAmB;AAAA;AAAA;AAAA;AAAA,EAK7D,YAAY,KAAU,SAAoC;AACxD,UAAM,gBAA8B,OAClC,UACA,YAAyB,CAAC,MACvB;AAEH,YAAM,UAAU,MAAM,KAAK,YAAY;AACvC,YAAM,gBAAgB;AAAA,QACpB,GAAG;AAAA,QACH,SAAS;AAAA,UACP,GAAG,QAAQ,aAAa;AAAA,UACxB,GAAG,WAAW;AAAA,UACd,GAAG;AAAA,QACL;AAAA,MACF;AAIA,aAAO,cAAc;AAGrB,aACG,QAAQ,iBAAiB;AAAA,QACxB;AAAA;AAAA,QAEA;AAAA,MACF,KAA2B,MAAM,UAAU,aAAa;AAAA,IAE5D;AAEA,UAAM,KAAK;AAAA,MACT,GAAG;AAAA,MACH,iBAAiB;AAAA,QACf,GAAG,QAAQ;AAAA,QACX,OAAO;AAAA,MACT;AAAA,IACF,CAAC;AACD,SAAK,eAAe,QAAQ;AAAA,EAC9B;AAAA,EAEA,MAAM,cAAc;AAClB,QAAI,KAAK,cAAc;AACrB,YAAM,SAAS,MAAM,KAAK,aAAa,OAAO;AAC9C,UAAI,QAAQ;AACV,eAAO;AAAA,UACL,eAAe,UAAU,OAAO,YAAY;AAAA,QAC9C;AAAA,MACF;AAAA,IACF;AAAA,EACF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ASO,SAAS,kBACd,YACA,MACmB;AACnB,QAAM,OAAO,OAAO,QAAQ,UAAU,EAAE,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM;AAC5D,WAAO,EAAE,MAAM,MAAM,KAAK,IAAI,EAAE;AAAA,EAClC,CAAC;AAED,QAAM,iBAAiB,KAAK,QAAQ,CAAC,EAAE,MAAM,UAAU,KAAK,MAAM;AAChE,WAAO,KAAK,IAAI,CAAC,SAAS;AACxB,aAAO;AAAA,QACL,GAAG;AAAA;AAAA,QAEH;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AACT;","names":["url"]}
|
|
@@ -1,28 +1,22 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MCPClientManager
|
|
3
|
+
} from "./chunk-OYJXQRRH.js";
|
|
1
4
|
import {
|
|
2
5
|
DurableObjectOAuthClientProvider
|
|
3
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-BZXOAZUX.js";
|
|
4
7
|
import {
|
|
5
8
|
camelCaseToKebabCase
|
|
6
|
-
} from "./chunk-
|
|
7
|
-
import {
|
|
8
|
-
MCPClientManager
|
|
9
|
-
} from "./chunk-25YDMV4H.js";
|
|
10
|
-
import {
|
|
11
|
-
__privateAdd,
|
|
12
|
-
__privateGet,
|
|
13
|
-
__privateMethod,
|
|
14
|
-
__privateSet
|
|
15
|
-
} from "./chunk-HMLY7DHA.js";
|
|
9
|
+
} from "./chunk-VCSB47AK.js";
|
|
16
10
|
|
|
17
11
|
// src/index.ts
|
|
18
12
|
import {
|
|
19
13
|
Server,
|
|
20
|
-
|
|
21
|
-
|
|
14
|
+
getServerByName,
|
|
15
|
+
routePartykitRequest
|
|
22
16
|
} from "partyserver";
|
|
23
17
|
import { parseCronExpression } from "cron-schedule";
|
|
24
18
|
import { nanoid } from "nanoid";
|
|
25
|
-
import { AsyncLocalStorage } from "
|
|
19
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
26
20
|
function isRPCRequest(msg) {
|
|
27
21
|
return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "rpc" && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
|
|
28
22
|
}
|
|
@@ -57,14 +51,12 @@ function getCurrentAgent() {
|
|
|
57
51
|
}
|
|
58
52
|
return store;
|
|
59
53
|
}
|
|
60
|
-
var _state, _ParentClass, _Agent_instances, setStateInternal_fn, tryCatch_fn, scheduleNextAlarm_fn, isCallable_fn, connectToMcpServerInternal_fn, getMcpServerStateInternal_fn;
|
|
61
54
|
var Agent = class extends Server {
|
|
62
55
|
constructor(ctx, env) {
|
|
63
56
|
super(ctx, env);
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
this.mcp = new MCPClientManager(__privateGet(this, _ParentClass).name, "0.0.1");
|
|
57
|
+
this._state = DEFAULT_STATE;
|
|
58
|
+
this._ParentClass = Object.getPrototypeOf(this).constructor;
|
|
59
|
+
this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
68
60
|
/**
|
|
69
61
|
* Initial state for the Agent
|
|
70
62
|
* Override to provide default state values
|
|
@@ -111,7 +103,7 @@ var Agent = class extends Server {
|
|
|
111
103
|
`;
|
|
112
104
|
}
|
|
113
105
|
}
|
|
114
|
-
await
|
|
106
|
+
await this._scheduleNextAlarm();
|
|
115
107
|
};
|
|
116
108
|
this.sql`
|
|
117
109
|
CREATE TABLE IF NOT EXISTS cf_agents_state (
|
|
@@ -120,7 +112,7 @@ var Agent = class extends Server {
|
|
|
120
112
|
)
|
|
121
113
|
`;
|
|
122
114
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
123
|
-
return
|
|
115
|
+
return this._tryCatch(async () => {
|
|
124
116
|
this.sql`
|
|
125
117
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
126
118
|
id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
|
|
@@ -157,7 +149,7 @@ var Agent = class extends Server {
|
|
|
157
149
|
this.broadcast(
|
|
158
150
|
JSON.stringify({
|
|
159
151
|
type: "cf_agent_mcp_servers",
|
|
160
|
-
mcp:
|
|
152
|
+
mcp: this.getMcpServers()
|
|
161
153
|
})
|
|
162
154
|
);
|
|
163
155
|
return new Response("<script>window.close();</script>", {
|
|
@@ -165,7 +157,7 @@ var Agent = class extends Server {
|
|
|
165
157
|
headers: { "content-type": "text/html" }
|
|
166
158
|
});
|
|
167
159
|
}
|
|
168
|
-
return
|
|
160
|
+
return this._tryCatch(() => _onRequest(request));
|
|
169
161
|
}
|
|
170
162
|
);
|
|
171
163
|
};
|
|
@@ -175,16 +167,16 @@ var Agent = class extends Server {
|
|
|
175
167
|
{ agent: this, connection, request: void 0 },
|
|
176
168
|
async () => {
|
|
177
169
|
if (typeof message !== "string") {
|
|
178
|
-
return
|
|
170
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
179
171
|
}
|
|
180
172
|
let parsed;
|
|
181
173
|
try {
|
|
182
174
|
parsed = JSON.parse(message);
|
|
183
175
|
} catch (e) {
|
|
184
|
-
return
|
|
176
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
185
177
|
}
|
|
186
178
|
if (isStateUpdateMessage(parsed)) {
|
|
187
|
-
|
|
179
|
+
this._setStateInternal(parsed.state, connection);
|
|
188
180
|
return;
|
|
189
181
|
}
|
|
190
182
|
if (isRPCRequest(parsed)) {
|
|
@@ -194,7 +186,7 @@ var Agent = class extends Server {
|
|
|
194
186
|
if (typeof methodFn !== "function") {
|
|
195
187
|
throw new Error(`Method ${method} does not exist`);
|
|
196
188
|
}
|
|
197
|
-
if (!
|
|
189
|
+
if (!this._isCallable(method)) {
|
|
198
190
|
throw new Error(`Method ${method} is not callable`);
|
|
199
191
|
}
|
|
200
192
|
const metadata = callableMetadata.get(methodFn);
|
|
@@ -224,7 +216,7 @@ var Agent = class extends Server {
|
|
|
224
216
|
}
|
|
225
217
|
return;
|
|
226
218
|
}
|
|
227
|
-
return
|
|
219
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
228
220
|
}
|
|
229
221
|
);
|
|
230
222
|
};
|
|
@@ -245,10 +237,10 @@ var Agent = class extends Server {
|
|
|
245
237
|
connection.send(
|
|
246
238
|
JSON.stringify({
|
|
247
239
|
type: "cf_agent_mcp_servers",
|
|
248
|
-
mcp:
|
|
240
|
+
mcp: this.getMcpServers()
|
|
249
241
|
})
|
|
250
242
|
);
|
|
251
|
-
return
|
|
243
|
+
return this._tryCatch(() => _onConnect(connection, ctx2));
|
|
252
244
|
}, 20);
|
|
253
245
|
}
|
|
254
246
|
);
|
|
@@ -262,20 +254,26 @@ var Agent = class extends Server {
|
|
|
262
254
|
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
263
255
|
`;
|
|
264
256
|
await Promise.allSettled(
|
|
265
|
-
servers.map((server) => {
|
|
266
|
-
return
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
257
|
+
servers.filter((server) => server.auth_url === null).map((server) => {
|
|
258
|
+
return this._connectToMcpServerInternal(
|
|
259
|
+
server.name,
|
|
260
|
+
server.server_url,
|
|
261
|
+
server.callback_url,
|
|
262
|
+
server.server_options ? JSON.parse(server.server_options) : void 0,
|
|
263
|
+
{
|
|
264
|
+
id: server.id,
|
|
265
|
+
oauthClientId: server.client_id ?? void 0
|
|
266
|
+
}
|
|
267
|
+
);
|
|
270
268
|
})
|
|
271
269
|
);
|
|
272
270
|
this.broadcast(
|
|
273
271
|
JSON.stringify({
|
|
274
272
|
type: "cf_agent_mcp_servers",
|
|
275
|
-
mcp:
|
|
273
|
+
mcp: this.getMcpServers()
|
|
276
274
|
})
|
|
277
275
|
);
|
|
278
|
-
await
|
|
276
|
+
await this._tryCatch(() => _onStart());
|
|
279
277
|
}
|
|
280
278
|
);
|
|
281
279
|
};
|
|
@@ -284,8 +282,8 @@ var Agent = class extends Server {
|
|
|
284
282
|
* Current state of the Agent
|
|
285
283
|
*/
|
|
286
284
|
get state() {
|
|
287
|
-
if (
|
|
288
|
-
return
|
|
285
|
+
if (this._state !== DEFAULT_STATE) {
|
|
286
|
+
return this._state;
|
|
289
287
|
}
|
|
290
288
|
const wasChanged = this.sql`
|
|
291
289
|
SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
|
|
@@ -296,8 +294,8 @@ var Agent = class extends Server {
|
|
|
296
294
|
if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
|
|
297
295
|
result[0]?.state) {
|
|
298
296
|
const state = result[0]?.state;
|
|
299
|
-
|
|
300
|
-
return
|
|
297
|
+
this._state = JSON.parse(state);
|
|
298
|
+
return this._state;
|
|
301
299
|
}
|
|
302
300
|
if (this.initialState === DEFAULT_STATE) {
|
|
303
301
|
return void 0;
|
|
@@ -325,12 +323,39 @@ var Agent = class extends Server {
|
|
|
325
323
|
throw this.onError(e);
|
|
326
324
|
}
|
|
327
325
|
}
|
|
326
|
+
_setStateInternal(state, source = "server") {
|
|
327
|
+
this._state = state;
|
|
328
|
+
this.sql`
|
|
329
|
+
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
330
|
+
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
331
|
+
`;
|
|
332
|
+
this.sql`
|
|
333
|
+
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
334
|
+
VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
|
|
335
|
+
`;
|
|
336
|
+
this.broadcast(
|
|
337
|
+
JSON.stringify({
|
|
338
|
+
type: "cf_agent_state",
|
|
339
|
+
state
|
|
340
|
+
}),
|
|
341
|
+
source !== "server" ? [source.id] : []
|
|
342
|
+
);
|
|
343
|
+
return this._tryCatch(() => {
|
|
344
|
+
const { connection, request } = agentContext.getStore() || {};
|
|
345
|
+
return agentContext.run(
|
|
346
|
+
{ agent: this, connection, request },
|
|
347
|
+
async () => {
|
|
348
|
+
return this.onStateUpdate(state, source);
|
|
349
|
+
}
|
|
350
|
+
);
|
|
351
|
+
});
|
|
352
|
+
}
|
|
328
353
|
/**
|
|
329
354
|
* Update the Agent's state
|
|
330
355
|
* @param state New state to set
|
|
331
356
|
*/
|
|
332
357
|
setState(state) {
|
|
333
|
-
|
|
358
|
+
this._setStateInternal(state, "server");
|
|
334
359
|
}
|
|
335
360
|
/**
|
|
336
361
|
* Called when the Agent's state is updated
|
|
@@ -351,6 +376,13 @@ var Agent = class extends Server {
|
|
|
351
376
|
}
|
|
352
377
|
);
|
|
353
378
|
}
|
|
379
|
+
async _tryCatch(fn) {
|
|
380
|
+
try {
|
|
381
|
+
return await fn();
|
|
382
|
+
} catch (e) {
|
|
383
|
+
throw this.onError(e);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
354
386
|
onError(connectionOrError, error) {
|
|
355
387
|
let theError;
|
|
356
388
|
if (connectionOrError && error) {
|
|
@@ -400,7 +432,7 @@ var Agent = class extends Server {
|
|
|
400
432
|
payload
|
|
401
433
|
)}, 'scheduled', ${timestamp})
|
|
402
434
|
`;
|
|
403
|
-
await
|
|
435
|
+
await this._scheduleNextAlarm();
|
|
404
436
|
return {
|
|
405
437
|
id,
|
|
406
438
|
callback,
|
|
@@ -418,7 +450,7 @@ var Agent = class extends Server {
|
|
|
418
450
|
payload
|
|
419
451
|
)}, 'delayed', ${when}, ${timestamp})
|
|
420
452
|
`;
|
|
421
|
-
await
|
|
453
|
+
await this._scheduleNextAlarm();
|
|
422
454
|
return {
|
|
423
455
|
id,
|
|
424
456
|
callback,
|
|
@@ -437,7 +469,7 @@ var Agent = class extends Server {
|
|
|
437
469
|
payload
|
|
438
470
|
)}, 'cron', ${when}, ${timestamp})
|
|
439
471
|
`;
|
|
440
|
-
await
|
|
472
|
+
await this._scheduleNextAlarm();
|
|
441
473
|
return {
|
|
442
474
|
id,
|
|
443
475
|
callback,
|
|
@@ -504,9 +536,22 @@ var Agent = class extends Server {
|
|
|
504
536
|
*/
|
|
505
537
|
async cancelSchedule(id) {
|
|
506
538
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
507
|
-
await
|
|
539
|
+
await this._scheduleNextAlarm();
|
|
508
540
|
return true;
|
|
509
541
|
}
|
|
542
|
+
async _scheduleNextAlarm() {
|
|
543
|
+
const result = this.sql`
|
|
544
|
+
SELECT time FROM cf_agents_schedules
|
|
545
|
+
WHERE time > ${Math.floor(Date.now() / 1e3)}
|
|
546
|
+
ORDER BY time ASC
|
|
547
|
+
LIMIT 1
|
|
548
|
+
`;
|
|
549
|
+
if (!result) return;
|
|
550
|
+
if (result.length > 0 && "time" in result[0]) {
|
|
551
|
+
const nextTime = result[0].time * 1e3;
|
|
552
|
+
await this.ctx.storage.setAlarm(nextTime);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
510
555
|
/**
|
|
511
556
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
512
557
|
*/
|
|
@@ -517,6 +562,13 @@ var Agent = class extends Server {
|
|
|
517
562
|
await this.ctx.storage.deleteAlarm();
|
|
518
563
|
await this.ctx.storage.deleteAll();
|
|
519
564
|
}
|
|
565
|
+
/**
|
|
566
|
+
* Get all methods marked as callable on this Agent
|
|
567
|
+
* @returns A map of method names to their metadata
|
|
568
|
+
*/
|
|
569
|
+
_isCallable(method) {
|
|
570
|
+
return callableMetadata.has(this[method]);
|
|
571
|
+
}
|
|
520
572
|
/**
|
|
521
573
|
* Connect to a new MCP Server
|
|
522
574
|
*
|
|
@@ -527,121 +579,56 @@ var Agent = class extends Server {
|
|
|
527
579
|
* @returns authUrl
|
|
528
580
|
*/
|
|
529
581
|
async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
|
|
530
|
-
const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(
|
|
531
|
-
const result = await
|
|
582
|
+
const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
583
|
+
const result = await this._connectToMcpServerInternal(
|
|
584
|
+
serverName,
|
|
585
|
+
url,
|
|
586
|
+
callbackUrl,
|
|
587
|
+
options
|
|
588
|
+
);
|
|
532
589
|
this.broadcast(
|
|
533
590
|
JSON.stringify({
|
|
534
591
|
type: "cf_agent_mcp_servers",
|
|
535
|
-
mcp:
|
|
592
|
+
mcp: this.getMcpServers()
|
|
536
593
|
})
|
|
537
594
|
);
|
|
538
595
|
return result;
|
|
539
596
|
}
|
|
540
|
-
async
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
this.broadcast(
|
|
546
|
-
JSON.stringify({
|
|
547
|
-
type: "cf_agent_mcp_servers",
|
|
548
|
-
mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
|
|
549
|
-
})
|
|
597
|
+
async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
|
|
598
|
+
const authProvider = new DurableObjectOAuthClientProvider(
|
|
599
|
+
this.ctx.storage,
|
|
600
|
+
this.name,
|
|
601
|
+
callbackUrl
|
|
550
602
|
);
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
_Agent_instances = new WeakSet();
|
|
556
|
-
setStateInternal_fn = function(state, source = "server") {
|
|
557
|
-
__privateSet(this, _state, state);
|
|
558
|
-
this.sql`
|
|
559
|
-
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
560
|
-
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
561
|
-
`;
|
|
562
|
-
this.sql`
|
|
563
|
-
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
564
|
-
VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
|
|
565
|
-
`;
|
|
566
|
-
this.broadcast(
|
|
567
|
-
JSON.stringify({
|
|
568
|
-
type: "cf_agent_state",
|
|
569
|
-
state
|
|
570
|
-
}),
|
|
571
|
-
source !== "server" ? [source.id] : []
|
|
572
|
-
);
|
|
573
|
-
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => {
|
|
574
|
-
const { connection, request } = agentContext.getStore() || {};
|
|
575
|
-
return agentContext.run(
|
|
576
|
-
{ agent: this, connection, request },
|
|
577
|
-
async () => {
|
|
578
|
-
return this.onStateUpdate(state, source);
|
|
603
|
+
if (reconnect) {
|
|
604
|
+
authProvider.serverId = reconnect.id;
|
|
605
|
+
if (reconnect.oauthClientId) {
|
|
606
|
+
authProvider.clientId = reconnect.oauthClientId;
|
|
579
607
|
}
|
|
580
|
-
);
|
|
581
|
-
});
|
|
582
|
-
};
|
|
583
|
-
tryCatch_fn = async function(fn) {
|
|
584
|
-
try {
|
|
585
|
-
return await fn();
|
|
586
|
-
} catch (e) {
|
|
587
|
-
throw this.onError(e);
|
|
588
|
-
}
|
|
589
|
-
};
|
|
590
|
-
scheduleNextAlarm_fn = async function() {
|
|
591
|
-
const result = this.sql`
|
|
592
|
-
SELECT time FROM cf_agents_schedules
|
|
593
|
-
WHERE time > ${Math.floor(Date.now() / 1e3)}
|
|
594
|
-
ORDER BY time ASC
|
|
595
|
-
LIMIT 1
|
|
596
|
-
`;
|
|
597
|
-
if (!result) return;
|
|
598
|
-
if (result.length > 0 && "time" in result[0]) {
|
|
599
|
-
const nextTime = result[0].time * 1e3;
|
|
600
|
-
await this.ctx.storage.setAlarm(nextTime);
|
|
601
|
-
}
|
|
602
|
-
};
|
|
603
|
-
/**
|
|
604
|
-
* Get all methods marked as callable on this Agent
|
|
605
|
-
* @returns A map of method names to their metadata
|
|
606
|
-
*/
|
|
607
|
-
isCallable_fn = function(method) {
|
|
608
|
-
return callableMetadata.has(this[method]);
|
|
609
|
-
};
|
|
610
|
-
connectToMcpServerInternal_fn = async function(serverName, url, callbackUrl, options, reconnect) {
|
|
611
|
-
const authProvider = new DurableObjectOAuthClientProvider(
|
|
612
|
-
this.ctx.storage,
|
|
613
|
-
this.name,
|
|
614
|
-
callbackUrl
|
|
615
|
-
);
|
|
616
|
-
if (reconnect) {
|
|
617
|
-
authProvider.serverId = reconnect.id;
|
|
618
|
-
if (reconnect.oauthClientId) {
|
|
619
|
-
authProvider.clientId = reconnect.oauthClientId;
|
|
620
608
|
}
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
609
|
+
let headerTransportOpts = {};
|
|
610
|
+
if (options?.transport?.headers) {
|
|
611
|
+
headerTransportOpts = {
|
|
612
|
+
eventSourceInit: {
|
|
613
|
+
fetch: (url2, init) => fetch(url2, {
|
|
614
|
+
...init,
|
|
615
|
+
headers: options?.transport?.headers
|
|
616
|
+
})
|
|
617
|
+
},
|
|
618
|
+
requestInit: {
|
|
628
619
|
headers: options?.transport?.headers
|
|
629
|
-
}
|
|
620
|
+
}
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
const { id, authUrl, clientId } = await this.mcp.connect(url, {
|
|
624
|
+
reconnect,
|
|
625
|
+
transport: {
|
|
626
|
+
...headerTransportOpts,
|
|
627
|
+
authProvider
|
|
630
628
|
},
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
};
|
|
635
|
-
}
|
|
636
|
-
const { id, authUrl, clientId } = await this.mcp.connect(url, {
|
|
637
|
-
reconnect,
|
|
638
|
-
transport: {
|
|
639
|
-
...headerTransportOpts,
|
|
640
|
-
authProvider
|
|
641
|
-
},
|
|
642
|
-
client: options?.client
|
|
643
|
-
});
|
|
644
|
-
this.sql`
|
|
629
|
+
client: options?.client
|
|
630
|
+
});
|
|
631
|
+
this.sql`
|
|
645
632
|
INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
646
633
|
VALUES (
|
|
647
634
|
${id},
|
|
@@ -653,30 +640,45 @@ connectToMcpServerInternal_fn = async function(serverName, url, callbackUrl, opt
|
|
|
653
640
|
${options ? JSON.stringify(options) : null}
|
|
654
641
|
);
|
|
655
642
|
`;
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
prompts: this.mcp.listPrompts(),
|
|
666
|
-
resources: this.mcp.listResources()
|
|
667
|
-
};
|
|
668
|
-
const servers = this.sql`
|
|
669
|
-
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
643
|
+
return {
|
|
644
|
+
id,
|
|
645
|
+
authUrl
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
async removeMcpServer(id) {
|
|
649
|
+
this.mcp.closeConnection(id);
|
|
650
|
+
this.sql`
|
|
651
|
+
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
670
652
|
`;
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
653
|
+
this.broadcast(
|
|
654
|
+
JSON.stringify({
|
|
655
|
+
type: "cf_agent_mcp_servers",
|
|
656
|
+
mcp: this.getMcpServers()
|
|
657
|
+
})
|
|
658
|
+
);
|
|
659
|
+
}
|
|
660
|
+
getMcpServers() {
|
|
661
|
+
const mcpState = {
|
|
662
|
+
servers: {},
|
|
663
|
+
tools: this.mcp.listTools(),
|
|
664
|
+
prompts: this.mcp.listPrompts(),
|
|
665
|
+
resources: this.mcp.listResources()
|
|
677
666
|
};
|
|
667
|
+
const servers = this.sql`
|
|
668
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
669
|
+
`;
|
|
670
|
+
for (const server of servers) {
|
|
671
|
+
mcpState.servers[server.id] = {
|
|
672
|
+
name: server.name,
|
|
673
|
+
server_url: server.server_url,
|
|
674
|
+
auth_url: server.auth_url,
|
|
675
|
+
state: this.mcp.mcpConnections[server.id].connectionState,
|
|
676
|
+
instructions: this.mcp.mcpConnections[server.id].instructions ?? null,
|
|
677
|
+
capabilities: this.mcp.mcpConnections[server.id].serverCapabilities ?? null
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
return mcpState;
|
|
678
681
|
}
|
|
679
|
-
return mcpState;
|
|
680
682
|
};
|
|
681
683
|
/**
|
|
682
684
|
* Agent configuration options
|
|
@@ -726,54 +728,48 @@ async function routeAgentEmail(email, env, options) {
|
|
|
726
728
|
async function getAgentByName(namespace, name, options) {
|
|
727
729
|
return getServerByName(namespace, name, options);
|
|
728
730
|
}
|
|
729
|
-
var _connection, _id, _closed;
|
|
730
731
|
var StreamingResponse = class {
|
|
731
732
|
constructor(connection, id) {
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
__privateSet(this, _connection, connection);
|
|
736
|
-
__privateSet(this, _id, id);
|
|
733
|
+
this._closed = false;
|
|
734
|
+
this._connection = connection;
|
|
735
|
+
this._id = id;
|
|
737
736
|
}
|
|
738
737
|
/**
|
|
739
738
|
* Send a chunk of data to the client
|
|
740
739
|
* @param chunk The data to send
|
|
741
740
|
*/
|
|
742
741
|
send(chunk) {
|
|
743
|
-
if (
|
|
742
|
+
if (this._closed) {
|
|
744
743
|
throw new Error("StreamingResponse is already closed");
|
|
745
744
|
}
|
|
746
745
|
const response = {
|
|
747
746
|
type: "rpc",
|
|
748
|
-
id:
|
|
747
|
+
id: this._id,
|
|
749
748
|
success: true,
|
|
750
749
|
result: chunk,
|
|
751
750
|
done: false
|
|
752
751
|
};
|
|
753
|
-
|
|
752
|
+
this._connection.send(JSON.stringify(response));
|
|
754
753
|
}
|
|
755
754
|
/**
|
|
756
755
|
* End the stream and send the final chunk (if any)
|
|
757
756
|
* @param finalChunk Optional final chunk of data to send
|
|
758
757
|
*/
|
|
759
758
|
end(finalChunk) {
|
|
760
|
-
if (
|
|
759
|
+
if (this._closed) {
|
|
761
760
|
throw new Error("StreamingResponse is already closed");
|
|
762
761
|
}
|
|
763
|
-
|
|
762
|
+
this._closed = true;
|
|
764
763
|
const response = {
|
|
765
764
|
type: "rpc",
|
|
766
|
-
id:
|
|
765
|
+
id: this._id,
|
|
767
766
|
success: true,
|
|
768
767
|
result: finalChunk,
|
|
769
768
|
done: true
|
|
770
769
|
};
|
|
771
|
-
|
|
770
|
+
this._connection.send(JSON.stringify(response));
|
|
772
771
|
}
|
|
773
772
|
};
|
|
774
|
-
_connection = new WeakMap();
|
|
775
|
-
_id = new WeakMap();
|
|
776
|
-
_closed = new WeakMap();
|
|
777
773
|
|
|
778
774
|
export {
|
|
779
775
|
unstable_callable,
|
|
@@ -784,4 +780,4 @@ export {
|
|
|
784
780
|
getAgentByName,
|
|
785
781
|
StreamingResponse
|
|
786
782
|
};
|
|
787
|
-
//# sourceMappingURL=chunk-
|
|
783
|
+
//# sourceMappingURL=chunk-P3RZJ72N.js.map
|