agents 0.0.0-dfa677f → 0.0.0-e376805

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.
@@ -0,0 +1,268 @@
1
+ import "../chunk-HMLY7DHA.js";
2
+
3
+ // src/mcp/sse-edge.ts
4
+ import {
5
+ SSEClientTransport
6
+ } from "@modelcontextprotocol/sdk/client/sse.js";
7
+ var SSEEdgeClientTransport = class extends SSEClientTransport {
8
+ /**
9
+ * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment
10
+ */
11
+ constructor(url, options) {
12
+ const fetchOverride = (url2, options2 = {}) => {
13
+ const workerOptions = {
14
+ ...options2
15
+ };
16
+ delete workerOptions.mode;
17
+ return global.fetch(url2, workerOptions);
18
+ };
19
+ super(url, {
20
+ ...options,
21
+ eventSourceInit: {
22
+ fetch: fetchOverride
23
+ }
24
+ });
25
+ this.url = url;
26
+ }
27
+ };
28
+
29
+ // src/mcp/client-connection.ts
30
+ import {
31
+ ToolListChangedNotificationSchema,
32
+ ResourceListChangedNotificationSchema,
33
+ PromptListChangedNotificationSchema
34
+ } from "@modelcontextprotocol/sdk/types.js";
35
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
36
+ var MCPClientConnection = class {
37
+ constructor(url, info, opts = { transport: {}, client: {}, capabilities: {} }) {
38
+ this.info = info;
39
+ this.transport = new SSEEdgeClientTransport(url, opts.transport);
40
+ this.client = new Client(info, opts.client);
41
+ this.client.registerCapabilities(opts.capabilities);
42
+ this.connected = false;
43
+ this.tools = [];
44
+ this.prompts = [];
45
+ this.resources = [];
46
+ this.resourceTemplates = [];
47
+ }
48
+ async init() {
49
+ await this.client.connect(this.transport);
50
+ this.serverCapabilities = await this.client.getServerCapabilities();
51
+ if (!this.serverCapabilities) {
52
+ throw new Error(
53
+ `The MCP Server ${this.info.name} failed to return server capabilities`
54
+ );
55
+ }
56
+ const [instructions, tools, resources, prompts, resourceTemplates] = await Promise.all([
57
+ this.client.getInstructions(),
58
+ this.registerTools(),
59
+ this.registerResources(),
60
+ this.registerPrompts(),
61
+ this.registerResourceTemplates()
62
+ ]);
63
+ this.instructions = instructions;
64
+ this.tools = tools;
65
+ this.resources = resources;
66
+ this.prompts = prompts;
67
+ this.resourceTemplates = resourceTemplates;
68
+ }
69
+ /**
70
+ * Notification handler registration
71
+ */
72
+ async registerTools() {
73
+ if (!this.serverCapabilities || !this.serverCapabilities.tools) {
74
+ return [];
75
+ }
76
+ if (this.serverCapabilities.tools.listChanged) {
77
+ this.client.setNotificationHandler(
78
+ ToolListChangedNotificationSchema,
79
+ async (_notification) => {
80
+ this.tools = await this.fetchTools();
81
+ }
82
+ );
83
+ }
84
+ return this.fetchTools();
85
+ }
86
+ async registerResources() {
87
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) {
88
+ return [];
89
+ }
90
+ if (this.serverCapabilities.resources.listChanged) {
91
+ this.client.setNotificationHandler(
92
+ ResourceListChangedNotificationSchema,
93
+ async (_notification) => {
94
+ this.resources = await this.fetchResources();
95
+ }
96
+ );
97
+ }
98
+ return this.fetchResources();
99
+ }
100
+ async registerPrompts() {
101
+ if (!this.serverCapabilities || !this.serverCapabilities.prompts) {
102
+ return [];
103
+ }
104
+ if (this.serverCapabilities.prompts.listChanged) {
105
+ this.client.setNotificationHandler(
106
+ PromptListChangedNotificationSchema,
107
+ async (_notification) => {
108
+ this.prompts = await this.fetchPrompts();
109
+ }
110
+ );
111
+ }
112
+ return this.fetchPrompts();
113
+ }
114
+ async registerResourceTemplates() {
115
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) {
116
+ return [];
117
+ }
118
+ return this.fetchResourceTemplates();
119
+ }
120
+ async fetchTools() {
121
+ let toolsAgg = [];
122
+ let toolsResult = { tools: [] };
123
+ do {
124
+ toolsResult = await this.client.listTools({
125
+ cursor: toolsResult.nextCursor
126
+ });
127
+ toolsAgg = toolsAgg.concat(toolsResult.tools);
128
+ } while (toolsResult.nextCursor);
129
+ return toolsAgg;
130
+ }
131
+ async fetchResources() {
132
+ let resourcesAgg = [];
133
+ let resourcesResult = { resources: [] };
134
+ do {
135
+ resourcesResult = await this.client.listResources({
136
+ cursor: resourcesResult.nextCursor
137
+ });
138
+ resourcesAgg = resourcesAgg.concat(resourcesResult.resources);
139
+ } while (resourcesResult.nextCursor);
140
+ return resourcesAgg;
141
+ }
142
+ async fetchPrompts() {
143
+ let promptsAgg = [];
144
+ let promptsResult = { prompts: [] };
145
+ do {
146
+ promptsResult = await this.client.listPrompts({
147
+ cursor: promptsResult.nextCursor
148
+ });
149
+ promptsAgg = promptsAgg.concat(promptsResult.prompts);
150
+ } while (promptsResult.nextCursor);
151
+ return promptsAgg;
152
+ }
153
+ async fetchResourceTemplates() {
154
+ let templatesAgg = [];
155
+ let templatesResult = {
156
+ resourceTemplates: []
157
+ };
158
+ do {
159
+ templatesResult = await this.client.listResourceTemplates({
160
+ cursor: templatesResult.nextCursor
161
+ });
162
+ templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);
163
+ } while (templatesResult.nextCursor);
164
+ return templatesAgg;
165
+ }
166
+ };
167
+
168
+ // src/mcp/client.ts
169
+ var MCPClientManager = class {
170
+ constructor() {
171
+ this.mcpConnections = {};
172
+ }
173
+ /**
174
+ * Connect to and register an MCP server
175
+ *
176
+ * @param transportConfig Transport config
177
+ * @param clientConfig Client config
178
+ * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
179
+ */
180
+ async connectToServer(url, info, opts = { transport: {}, client: {}, capabilities: {} }) {
181
+ if (info.name in this.mcpConnections) {
182
+ throw new Error(
183
+ `An existing MCP client has already been registered under the name "${info.name}". The MCP client name must be unique.`
184
+ );
185
+ }
186
+ this.mcpConnections[info.name] = new MCPClientConnection(url, info, opts);
187
+ await this.mcpConnections[info.name].init();
188
+ }
189
+ /**
190
+ * @returns namespaced list of tools
191
+ */
192
+ listTools() {
193
+ return getNamespacedData(this.mcpConnections, "tools");
194
+ }
195
+ /**
196
+ * @returns namespaced list of prompts
197
+ */
198
+ listPrompts() {
199
+ return getNamespacedData(this.mcpConnections, "prompts");
200
+ }
201
+ /**
202
+ * @returns namespaced list of tools
203
+ */
204
+ listResources() {
205
+ return getNamespacedData(this.mcpConnections, "resources");
206
+ }
207
+ /**
208
+ * @returns namespaced list of resource templates
209
+ */
210
+ listResourceTemplates() {
211
+ return getNamespacedData(this.mcpConnections, "resourceTemplates");
212
+ }
213
+ /**
214
+ * Namespaced version of callTool
215
+ */
216
+ callTool(params, resultSchema, options) {
217
+ const unqualifiedName = params.name.replace(`${params.serverName}.`, "");
218
+ return this.mcpConnections[params.serverName].client.callTool(
219
+ {
220
+ ...params,
221
+ name: unqualifiedName
222
+ },
223
+ resultSchema,
224
+ options
225
+ );
226
+ }
227
+ /**
228
+ * Namespaced version of readResource
229
+ */
230
+ readResource(params, options) {
231
+ return this.mcpConnections[params.serverName].client.readResource(
232
+ params,
233
+ options
234
+ );
235
+ }
236
+ /**
237
+ * Namespaced version of getPrompt
238
+ */
239
+ getPrompt(params, options) {
240
+ return this.mcpConnections[params.serverName].client.getPrompt(
241
+ params,
242
+ options
243
+ );
244
+ }
245
+ };
246
+ function getNamespacedData(mcpClients, type) {
247
+ const sets = Object.entries(mcpClients).map(([name, conn]) => {
248
+ return { name, data: conn[type] };
249
+ });
250
+ const namespacedData = sets.flatMap(({ name: serverName, data }) => {
251
+ return data.map((item) => {
252
+ return {
253
+ ...item,
254
+ // we add a servername so we can easily pull it out and convert between qualified<->unqualified name
255
+ // just in case the server name or item name includes a "."
256
+ serverName: `${serverName}`,
257
+ // qualified name
258
+ name: `${serverName}.${item.name}`
259
+ };
260
+ });
261
+ });
262
+ return namespacedData;
263
+ }
264
+ export {
265
+ MCPClientManager,
266
+ getNamespacedData
267
+ };
268
+ //# sourceMappingURL=client.js.map
@@ -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\";\n\nexport class SSEEdgeClientTransport extends SSEClientTransport {\n /**\n * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment\n */\n constructor(\n private url: URL,\n options: SSEClientTransportOptions\n ) {\n // biome-ignore lint/suspicious/noExplicitAny: Overriding fetch, type doesn't matter here\n const fetchOverride = (url: any, options = {}) => {\n const workerOptions = {\n ...options,\n };\n // Remove unsupported properties\n // @ts-ignore\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 global.fetch(url, workerOptions);\n };\n\n super(url, {\n ...options,\n eventSourceInit: {\n fetch: fetchOverride,\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} from \"@modelcontextprotocol/sdk/types.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type {\n SSEClientTransport,\n SSEClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nexport class MCPClientConnection {\n client: Client;\n transport: SSEClientTransport;\n connected: boolean;\n instructions?: string;\n tools: Tool[];\n prompts: Prompt[];\n resources: Resource[];\n resourceTemplates: ResourceTemplate[];\n serverCapabilities: ServerCapabilities | undefined;\n\n constructor(\n url: URL,\n private info: ConstructorParameters<typeof Client>[0],\n opts: {\n transport: SSEClientTransportOptions;\n client: ConstructorParameters<typeof Client>[1];\n capabilities: ClientCapabilities;\n } = { transport: {}, client: {}, capabilities: {} }\n ) {\n this.transport = new SSEEdgeClientTransport(url, opts.transport);\n this.client = new Client(info, opts.client);\n this.client.registerCapabilities(opts.capabilities);\n this.connected = false;\n this.tools = [];\n this.prompts = [];\n this.resources = [];\n this.resourceTemplates = [];\n }\n\n async init() {\n await this.client.connect(this.transport);\n\n this.serverCapabilities = await this.client.getServerCapabilities();\n if (!this.serverCapabilities) {\n throw new Error(\n `The MCP Server ${this.info.name} failed to return server capabilities`\n );\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\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.listTools({\n cursor: toolsResult.nextCursor,\n });\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.listResources({\n cursor: resourcesResult.nextCursor,\n });\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.listPrompts({\n cursor: promptsResult.nextCursor,\n });\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.listResourceTemplates({\n cursor: templatesResult.nextCursor,\n });\n templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n } while (templatesResult.nextCursor);\n return templatesAgg;\n }\n}\n","import { MCPClientConnection } from \"./client-connection\";\n\nimport type {\n ClientCapabilities,\n CallToolRequest,\n CallToolResultSchema,\n CompatibilityCallToolResultSchema,\n ReadResourceRequest,\n GetPromptRequest,\n Tool,\n Resource,\n ResourceTemplate,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\n\n/**\n * Utility class that aggregates multiple MCP clients into one\n */\nexport class MCPClientManager {\n public mcpConnections: Record<string, MCPClientConnection> = {};\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 connectToServer(\n url: URL,\n info: ConstructorParameters<typeof Client>[0],\n opts: {\n transport: SSEClientTransportOptions;\n client: ConstructorParameters<typeof Client>[1];\n capabilities: ClientCapabilities;\n } = { transport: {}, client: {}, capabilities: {} }\n ) {\n if (info.name in this.mcpConnections) {\n throw new Error(\n `An existing MCP client has already been registered under the name \"${info.name}\". The MCP client name must be unique.`\n );\n }\n\n this.mcpConnections[info.name] = new MCPClientConnection(url, info, opts);\n await this.mcpConnections[info.name].init();\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 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\"] & { serverName: string },\n resultSchema:\n | typeof CallToolResultSchema\n | typeof CompatibilityCallToolResultSchema,\n options: RequestOptions\n ) {\n const unqualifiedName = params.name.replace(`${params.serverName}.`, \"\");\n return this.mcpConnections[params.serverName].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\"] & { serverName: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverName].client.readResource(\n params,\n options\n );\n }\n\n /**\n * Namespaced version of getPrompt\n */\n getPrompt(\n params: GetPromptRequest[\"params\"] & { serverName: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverName].client.getPrompt(\n params,\n options\n );\n }\n}\n\ntype NamespacedData = {\n tools: (Tool & { serverName: string })[];\n prompts: (Prompt & { serverName: string })[];\n resources: (Resource & { serverName: string })[];\n resourceTemplates: (ResourceTemplate & { serverName: 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: serverName, data }) => {\n return data.map((item) => {\n return {\n ...item,\n // we add a servername so we can easily pull it out and convert between qualified<->unqualified name\n // just in case the server name or item name includes a \".\"\n serverName: `${serverName}`,\n // qualified name\n name: `${serverName}.${item.name}`,\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;AAEA,IAAM,yBAAN,cAAqC,mBAAmB;AAAA;AAAA;AAAA;AAAA,EAI7D,YACU,KACR,SACA;AAEA,UAAM,gBAAgB,CAACA,MAAUC,WAAU,CAAC,MAAM;AAChD,YAAM,gBAAgB;AAAA,QACpB,GAAGA;AAAA,MACL;AAIA,aAAO,cAAc;AAGrB,aAAO,OAAO,MAAMD,MAAK,aAAa;AAAA,IACxC;AAEA,UAAM,KAAK;AAAA,MACT,GAAG;AAAA,MACH,iBAAiB;AAAA,QACf,OAAO;AAAA,MACT;AAAA,IACF,CAAC;AAtBO;AAAA,EAuBV;AACF;;;AChCA;AAAA,EACE;AAAA,EAKA;AAAA,EACA;AAAA,OAOK;AACP,SAAS,cAAc;AAMhB,IAAM,sBAAN,MAA0B;AAAA,EAW/B,YACE,KACQ,MACR,OAII,EAAE,WAAW,CAAC,GAAG,QAAQ,CAAC,GAAG,cAAc,CAAC,EAAE,GAClD;AANQ;AAOR,SAAK,YAAY,IAAI,uBAAuB,KAAK,KAAK,SAAS;AAC/D,SAAK,SAAS,IAAI,OAAO,MAAM,KAAK,MAAM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BAAgB,WAAW;AAAA,EAC3D;AAAA;AAAA;AAAA;AAAA,EAKA,wBAA6D;AAC3D,WAAO,kBAAkB,KAAK,gBAAgB,mBAAmB;AAAA,EACnE;AAAA;AAAA;AAAA;AAAA,EAKA,SACE,QACA,cAGA,SACA;AACA,UAAM,kBAAkB,OAAO,KAAK,QAAQ,GAAG,OAAO,UAAU,KAAK,EAAE;AACvE,WAAO,KAAK,eAAe,OAAO,UAAU,EAAE,OAAO;AAAA,MACnD;AAAA,QACE,GAAG;AAAA,QACH,MAAM;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,aACE,QACA,SACA;AACA,WAAO,KAAK,eAAe,OAAO,UAAU,EAAE,OAAO;AAAA,MACnD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,UACE,QACA,SACA;AACA,WAAO,KAAK,eAAe,OAAO,UAAU,EAAE,OAAO;AAAA,MACnD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AASO,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,YAAY,KAAK,MAAM;AAClE,WAAO,KAAK,IAAI,CAAC,SAAS;AACxB,aAAO;AAAA,QACL,GAAG;AAAA;AAAA;AAAA,QAGH,YAAY,GAAG,UAAU;AAAA;AAAA,QAEzB,MAAM,GAAG,UAAU,IAAI,KAAK,IAAI;AAAA,MAClC;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AACT;","names":["url","options"]}
@@ -0,0 +1,45 @@
1
+ import { DurableObject } from 'cloudflare:workers';
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { Connection } from 'partyserver';
4
+
5
+ interface CORSOptions {
6
+ origin?: string;
7
+ methods?: string;
8
+ headers?: string;
9
+ maxAge?: number;
10
+ }
11
+ declare abstract class McpAgent<Env = unknown, State = unknown, Props extends Record<string, unknown> = Record<string, unknown>> extends DurableObject<Env> {
12
+ #private;
13
+ protected constructor(ctx: DurableObjectState, env: Env);
14
+ /**
15
+ * Agents API allowlist
16
+ */
17
+ initialState: State;
18
+ get state(): State;
19
+ sql<T = Record<string, string | number | boolean | null>>(strings: TemplateStringsArray, ...values: (string | number | boolean | null)[]): T[];
20
+ setState(state: State): void;
21
+ onStateUpdate(state: State | undefined, source: Connection | "server"): void;
22
+ onStart(): Promise<void>;
23
+ /**
24
+ * McpAgent API
25
+ */
26
+ abstract server: McpServer;
27
+ props: Props;
28
+ initRun: boolean;
29
+ abstract init(): Promise<void>;
30
+ _init(props: Props): Promise<void>;
31
+ fetch(request: Request): Promise<Response>;
32
+ getWebSocket(): WebSocket | null;
33
+ onMCPMessage(sessionId: string, request: Request): Promise<Response>;
34
+ webSocketMessage(ws: WebSocket, event: ArrayBuffer | string): Promise<void>;
35
+ webSocketError(ws: WebSocket, error: unknown): Promise<void>;
36
+ webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean): Promise<void>;
37
+ static mount(path: string, { binding, corsOptions, }?: {
38
+ binding?: string;
39
+ corsOptions?: CORSOptions;
40
+ }): {
41
+ fetch: (request: Request, env: Record<string, DurableObjectNamespace<McpAgent>>, ctx: ExecutionContext) => Promise<Response | undefined>;
42
+ };
43
+ }
44
+
45
+ export { McpAgent };
@@ -0,0 +1,343 @@
1
+ import {
2
+ Agent
3
+ } from "../chunk-YMUU7QHV.js";
4
+ import {
5
+ __privateAdd,
6
+ __privateGet,
7
+ __privateMethod,
8
+ __privateSet
9
+ } from "../chunk-HMLY7DHA.js";
10
+
11
+ // src/mcp/index.ts
12
+ import { DurableObject } from "cloudflare:workers";
13
+ import { JSONRPCMessageSchema } from "@modelcontextprotocol/sdk/types.js";
14
+ var MAXIMUM_MESSAGE_SIZE = 4 * 1024 * 1024;
15
+ function handleCORS(request, corsOptions) {
16
+ const origin = request.headers.get("Origin") || "*";
17
+ const corsHeaders = {
18
+ "Access-Control-Allow-Origin": corsOptions?.origin || origin,
19
+ "Access-Control-Allow-Methods": corsOptions?.methods || "GET, POST, OPTIONS",
20
+ "Access-Control-Allow-Headers": corsOptions?.headers || "Content-Type",
21
+ "Access-Control-Max-Age": (corsOptions?.maxAge || 86400).toString()
22
+ };
23
+ if (request.method === "OPTIONS") {
24
+ return new Response(null, { headers: corsHeaders });
25
+ }
26
+ return null;
27
+ }
28
+ var _getWebSocket, _started;
29
+ var McpTransport = class {
30
+ constructor(getWebSocket) {
31
+ __privateAdd(this, _getWebSocket);
32
+ __privateAdd(this, _started, false);
33
+ __privateSet(this, _getWebSocket, getWebSocket);
34
+ }
35
+ async start() {
36
+ if (__privateGet(this, _started)) {
37
+ throw new Error("Transport already started");
38
+ }
39
+ __privateSet(this, _started, true);
40
+ }
41
+ async send(message) {
42
+ if (!__privateGet(this, _started)) {
43
+ throw new Error("Transport not started");
44
+ }
45
+ const websocket = __privateGet(this, _getWebSocket).call(this);
46
+ if (!websocket) {
47
+ throw new Error("WebSocket not connected");
48
+ }
49
+ try {
50
+ websocket.send(JSON.stringify(message));
51
+ } catch (error) {
52
+ this.onerror?.(error);
53
+ throw error;
54
+ }
55
+ }
56
+ async close() {
57
+ this.onclose?.();
58
+ }
59
+ };
60
+ _getWebSocket = new WeakMap();
61
+ _started = new WeakMap();
62
+ var _status, _transport, _connected, _agent, _McpAgent_instances, initialize_fn;
63
+ var McpAgent = class extends DurableObject {
64
+ constructor(ctx, env) {
65
+ var _a;
66
+ super(ctx, env);
67
+ __privateAdd(this, _McpAgent_instances);
68
+ __privateAdd(this, _status, "zero");
69
+ __privateAdd(this, _transport);
70
+ __privateAdd(this, _connected, false);
71
+ /**
72
+ * Since McpAgent's _aren't_ yet real "Agents" (they route differently, don't support
73
+ * websockets, don't support hibernation), let's only expose a couple of the methods
74
+ * to the outer class: initialState/state/setState/onStateUpdate/sql
75
+ */
76
+ __privateAdd(this, _agent);
77
+ this.initRun = false;
78
+ const self = this;
79
+ __privateSet(this, _agent, new (_a = class extends Agent {
80
+ onStateUpdate(state, source) {
81
+ return self.onStateUpdate(state, source);
82
+ }
83
+ }, _a.options = {
84
+ hibernate: true
85
+ }, _a)(ctx, env));
86
+ }
87
+ get state() {
88
+ if (this.initialState) __privateGet(this, _agent).initialState = this.initialState;
89
+ return __privateGet(this, _agent).state;
90
+ }
91
+ sql(strings, ...values) {
92
+ return __privateGet(this, _agent).sql(strings, ...values);
93
+ }
94
+ setState(state) {
95
+ return __privateGet(this, _agent).setState(state);
96
+ }
97
+ onStateUpdate(state, source) {
98
+ }
99
+ async onStart() {
100
+ this.props = await this.ctx.storage.get("props");
101
+ this.init?.();
102
+ __privateSet(this, _transport, new McpTransport(() => this.getWebSocket()));
103
+ await this.server.connect(__privateGet(this, _transport));
104
+ }
105
+ async _init(props) {
106
+ await this.ctx.storage.put("props", props);
107
+ this.props = props;
108
+ if (!this.initRun) {
109
+ this.initRun = true;
110
+ await this.init();
111
+ }
112
+ }
113
+ // Allow the worker to fetch a websocket connection to the agent
114
+ async fetch(request) {
115
+ if (__privateGet(this, _status) !== "started") {
116
+ await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
117
+ }
118
+ if (request.headers.get("Upgrade") !== "websocket") {
119
+ return new Response("Expected WebSocket Upgrade request", {
120
+ status: 400
121
+ });
122
+ }
123
+ const url = new URL(request.url);
124
+ const sessionId = url.searchParams.get("sessionId");
125
+ if (!sessionId) {
126
+ return new Response("Missing sessionId", { status: 400 });
127
+ }
128
+ const webSocketPair = new WebSocketPair();
129
+ const [client, server] = Object.values(webSocketPair);
130
+ if (__privateGet(this, _connected)) {
131
+ return new Response("WebSocket already connected", { status: 400 });
132
+ }
133
+ this.ctx.acceptWebSocket(server);
134
+ __privateSet(this, _connected, true);
135
+ __privateSet(this, _transport, new McpTransport(() => this.getWebSocket()));
136
+ await this.server.connect(__privateGet(this, _transport));
137
+ return new Response(null, {
138
+ status: 101,
139
+ webSocket: client
140
+ });
141
+ }
142
+ getWebSocket() {
143
+ const websockets = this.ctx.getWebSockets();
144
+ if (websockets.length === 0) {
145
+ return null;
146
+ }
147
+ return websockets[0];
148
+ }
149
+ async onMCPMessage(sessionId, request) {
150
+ if (__privateGet(this, _status) !== "started") {
151
+ await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
152
+ }
153
+ try {
154
+ const contentType = request.headers.get("content-type") || "";
155
+ if (!contentType.includes("application/json")) {
156
+ return new Response(`Unsupported content-type: ${contentType}`, {
157
+ status: 400
158
+ });
159
+ }
160
+ const contentLength = Number.parseInt(
161
+ request.headers.get("content-length") || "0",
162
+ 10
163
+ );
164
+ if (contentLength > MAXIMUM_MESSAGE_SIZE) {
165
+ return new Response(`Request body too large: ${contentLength} bytes`, {
166
+ status: 400
167
+ });
168
+ }
169
+ const message = await request.json();
170
+ let parsedMessage;
171
+ try {
172
+ parsedMessage = JSONRPCMessageSchema.parse(message);
173
+ } catch (error) {
174
+ __privateGet(this, _transport)?.onerror?.(error);
175
+ throw error;
176
+ }
177
+ __privateGet(this, _transport)?.onmessage?.(parsedMessage);
178
+ return new Response("Accepted", { status: 202 });
179
+ } catch (error) {
180
+ __privateGet(this, _transport)?.onerror?.(error);
181
+ return new Response(String(error), { status: 400 });
182
+ }
183
+ }
184
+ // This is unused since there are no incoming websocket messages
185
+ async webSocketMessage(ws, event) {
186
+ let message;
187
+ try {
188
+ const data = typeof event === "string" ? event : new TextDecoder().decode(event);
189
+ message = JSONRPCMessageSchema.parse(JSON.parse(data));
190
+ } catch (error) {
191
+ __privateGet(this, _transport)?.onerror?.(error);
192
+ return;
193
+ }
194
+ if (__privateGet(this, _status) !== "started") {
195
+ await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
196
+ }
197
+ __privateGet(this, _transport)?.onmessage?.(message);
198
+ }
199
+ // WebSocket event handlers for hibernation support
200
+ async webSocketError(ws, error) {
201
+ if (__privateGet(this, _status) !== "started") {
202
+ await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
203
+ }
204
+ __privateGet(this, _transport)?.onerror?.(error);
205
+ }
206
+ async webSocketClose(ws, code, reason, wasClean) {
207
+ if (__privateGet(this, _status) !== "started") {
208
+ await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
209
+ }
210
+ __privateGet(this, _transport)?.onclose?.();
211
+ __privateSet(this, _connected, false);
212
+ }
213
+ static mount(path, {
214
+ binding = "MCP_OBJECT",
215
+ corsOptions
216
+ } = {}) {
217
+ const basePattern = new URLPattern({ pathname: path });
218
+ const messagePattern = new URLPattern({ pathname: `${path}/message` });
219
+ return {
220
+ fetch: async (request, env, ctx) => {
221
+ const corsResponse = handleCORS(request, corsOptions);
222
+ if (corsResponse) return corsResponse;
223
+ const url = new URL(request.url);
224
+ const namespace = env[binding];
225
+ if (request.method === "GET" && basePattern.test(url)) {
226
+ const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
227
+ const { readable, writable } = new TransformStream();
228
+ const writer = writable.getWriter();
229
+ const encoder = new TextEncoder();
230
+ const endpointMessage = `event: endpoint
231
+ data: ${encodeURI(`${path}/message`)}?sessionId=${sessionId}
232
+
233
+ `;
234
+ writer.write(encoder.encode(endpointMessage));
235
+ const id = namespace.idFromString(sessionId);
236
+ const doStub = namespace.get(id);
237
+ await doStub._init(ctx.props);
238
+ const upgradeUrl = new URL(request.url);
239
+ upgradeUrl.searchParams.set("sessionId", sessionId);
240
+ const response = await doStub.fetch(
241
+ new Request(upgradeUrl, {
242
+ headers: {
243
+ Upgrade: "websocket"
244
+ }
245
+ })
246
+ );
247
+ const ws = response.webSocket;
248
+ if (!ws) {
249
+ console.error("Failed to establish WebSocket connection");
250
+ await writer.close();
251
+ return;
252
+ }
253
+ ws.accept();
254
+ ws.addEventListener("message", async (event) => {
255
+ try {
256
+ const message = JSON.parse(event.data);
257
+ if (!(typeof message.id === "number" || message.id === null)) {
258
+ throw new Error("Invalid jsonrpc message id");
259
+ }
260
+ if (message.jsonrpc !== "2.0") {
261
+ throw new Error("Invalid jsonrpc version");
262
+ }
263
+ if (!Object.hasOwn(message, "result") && !Object.hasOwn(message, "error")) {
264
+ throw new Error(
265
+ "Invalid jsonrpc message. Must have either result or error field"
266
+ );
267
+ }
268
+ const messageText = `event: message
269
+ data: ${event.data}
270
+
271
+ `;
272
+ await writer.write(encoder.encode(messageText));
273
+ } catch (error) {
274
+ console.error("Error forwarding message to SSE:", error);
275
+ }
276
+ });
277
+ ws.addEventListener("error", async (error) => {
278
+ try {
279
+ await writer.close();
280
+ } catch (e) {
281
+ }
282
+ });
283
+ ws.addEventListener("close", async () => {
284
+ try {
285
+ await writer.close();
286
+ } catch (error) {
287
+ console.error("Error closing SSE connection:", error);
288
+ }
289
+ });
290
+ return new Response(readable, {
291
+ headers: {
292
+ "Content-Type": "text/event-stream",
293
+ "Cache-Control": "no-cache",
294
+ Connection: "keep-alive",
295
+ "Access-Control-Allow-Origin": corsOptions?.origin || "*"
296
+ }
297
+ });
298
+ }
299
+ if (request.method === "POST" && messagePattern.test(url)) {
300
+ const sessionId = url.searchParams.get("sessionId");
301
+ if (!sessionId) {
302
+ return new Response(
303
+ `Missing sessionId. Expected POST to ${path} to initiate new one`,
304
+ { status: 400 }
305
+ );
306
+ }
307
+ const object = namespace.get(namespace.idFromString(sessionId));
308
+ const response = await object.onMCPMessage(sessionId, request);
309
+ const headers = new Headers();
310
+ response.headers.forEach?.((value, key) => {
311
+ headers.set(key, value);
312
+ });
313
+ headers.set(
314
+ "Access-Control-Allow-Origin",
315
+ corsOptions?.origin || "*"
316
+ );
317
+ return new Response(response.body, {
318
+ status: response.status,
319
+ statusText: response.statusText,
320
+ headers
321
+ });
322
+ }
323
+ return new Response("Not Found", { status: 404 });
324
+ }
325
+ };
326
+ }
327
+ };
328
+ _status = new WeakMap();
329
+ _transport = new WeakMap();
330
+ _connected = new WeakMap();
331
+ _agent = new WeakMap();
332
+ _McpAgent_instances = new WeakSet();
333
+ initialize_fn = async function() {
334
+ await this.ctx.blockConcurrencyWhile(async () => {
335
+ __privateSet(this, _status, "starting");
336
+ await this.onStart();
337
+ __privateSet(this, _status, "started");
338
+ });
339
+ };
340
+ export {
341
+ McpAgent
342
+ };
343
+ //# sourceMappingURL=index.js.map