@runpod/mcp-server 1.2.0 → 1.4.0

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/http.cjs ADDED
@@ -0,0 +1,1276 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/http.ts
31
+ var http_exports = {};
32
+ __export(http_exports, {
33
+ handleMcpRequest: () => handleMcpRequest,
34
+ registerTools: () => registerTools
35
+ });
36
+ module.exports = __toCommonJS(http_exports);
37
+ var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
38
+
39
+ // src/server.ts
40
+ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
41
+ var SERVER_NAME = "Runpod API Server";
42
+ var SERVER_VERSION = true ? "1.4.0" : "dev";
43
+ function createServer(version = SERVER_VERSION) {
44
+ return new import_mcp.McpServer({
45
+ name: SERVER_NAME,
46
+ version,
47
+ capabilities: {
48
+ resources: {},
49
+ tools: {}
50
+ }
51
+ });
52
+ }
53
+
54
+ // src/tools.ts
55
+ var import_zod2 = require("zod");
56
+ var import_node_fetch = __toESM(require("node-fetch"), 1);
57
+ var import_node_crypto = require("crypto");
58
+
59
+ // src/pagination.ts
60
+ var import_zod = require("zod");
61
+ var DEFAULT_LIST_LIMIT = 20;
62
+ var MAX_LIST_LIMIT = 100;
63
+ var listPaginationParams = {
64
+ limit: import_zod.z.number().int().positive().max(MAX_LIST_LIMIT).optional().describe(
65
+ `Maximum number of items to return (default ${DEFAULT_LIST_LIMIT}, max ${MAX_LIST_LIMIT}). Use the returned nextCursor to fetch the next page.`
66
+ ),
67
+ cursor: import_zod.z.string().optional().describe(
68
+ "Opaque pagination cursor from a previous response (nextCursor). Omit to start from the beginning."
69
+ )
70
+ };
71
+ function decodeCursorOffset(cursor) {
72
+ if (!cursor) return 0;
73
+ try {
74
+ const decoded = Buffer.from(cursor, "base64").toString("utf8");
75
+ const offset = Number.parseInt(decoded, 10);
76
+ return Number.isFinite(offset) && offset >= 0 ? offset : 0;
77
+ } catch {
78
+ return 0;
79
+ }
80
+ }
81
+ function encodeCursorOffset(offset) {
82
+ return Buffer.from(String(offset), "utf8").toString("base64");
83
+ }
84
+ function capListResult(result, options) {
85
+ const limit = Math.min(options.limit ?? DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT);
86
+ const offset = decodeCursorOffset(options.cursor);
87
+ if (!Array.isArray(result)) {
88
+ return {
89
+ content: [
90
+ { type: "text", text: JSON.stringify(result, null, 2) }
91
+ ]
92
+ };
93
+ }
94
+ const total = result.length;
95
+ const page = result.slice(offset, offset + limit);
96
+ const nextOffset = offset + page.length;
97
+ const hasMore = nextOffset < total;
98
+ const envelope = {
99
+ items: page,
100
+ pagination: {
101
+ total,
102
+ returned: page.length,
103
+ offset,
104
+ truncated: hasMore,
105
+ nextCursor: hasMore ? encodeCursorOffset(nextOffset) : null,
106
+ note: hasMore ? `Showing ${page.length} of ${total}. Pass cursor=nextCursor to fetch more, or narrow the query with filters.` : void 0
107
+ }
108
+ };
109
+ return {
110
+ content: [
111
+ { type: "text", text: JSON.stringify(envelope, null, 2) }
112
+ ]
113
+ };
114
+ }
115
+
116
+ // src/tools.ts
117
+ var API_BASE_URL = process.env.RUNPOD_REST_API_URL ?? "https://rest.runpod.io/v1";
118
+ var SERVERLESS_API_BASE_URL = process.env.RUNPOD_SERVERLESS_API_URL ?? "https://api.runpod.ai/v2";
119
+ var GRAPHQL_URL = process.env.RUNPOD_PUBLIC_GRAPHQL_URL ?? "https://api.runpod.io/graphql";
120
+ var MCP_SERVER_VERSION = true ? "1.4.0" : "dev";
121
+ var SESSION_ID = (0, import_node_crypto.randomUUID)();
122
+ function sanitizeUaToken(value) {
123
+ return value.replace(/[()<>@,;:\\"/[\]?={}\s]/g, "_").slice(0, 64);
124
+ }
125
+ function trackingHeaders(server, ctx) {
126
+ const info = server.server.getClientVersion();
127
+ const fallbackName = ctx.clientUserAgent || "unknown";
128
+ const name = sanitizeUaToken(info?.name || fallbackName);
129
+ const version = sanitizeUaToken(info?.version || "unknown");
130
+ const serverVersion = ctx.serverVersion || MCP_SERVER_VERSION;
131
+ const userAgent = `runpod-mcp-server/${serverVersion} (caller=mcp; client=${name}; client_version=${version}; transport=${ctx.transport})`;
132
+ return {
133
+ "User-Agent": userAgent,
134
+ "X-Runpod-Session-Id": SESSION_ID
135
+ };
136
+ }
137
+ async function graphqlRequest(query, tracking) {
138
+ const response = await (0, import_node_fetch.default)(GRAPHQL_URL, {
139
+ method: "POST",
140
+ headers: {
141
+ "Content-Type": "application/json",
142
+ ...tracking()
143
+ },
144
+ body: JSON.stringify({ query })
145
+ });
146
+ const result = await response.json();
147
+ if (result.errors && result.errors.length > 0) {
148
+ throw new Error(
149
+ `GraphQL Error: ${result.errors.map((e) => e.message).join(", ")}`
150
+ );
151
+ }
152
+ if (!result.data) {
153
+ throw new Error("No data returned from GraphQL query");
154
+ }
155
+ return result.data;
156
+ }
157
+ function createRunpodRequest(apiKey, tracking) {
158
+ return async function runpodRequest(endpoint, method = "GET", body) {
159
+ const url = `${API_BASE_URL}${endpoint}`;
160
+ const headers = {
161
+ Authorization: `Bearer ${apiKey}`,
162
+ "Content-Type": "application/json",
163
+ ...tracking()
164
+ };
165
+ const options = {
166
+ method,
167
+ headers
168
+ };
169
+ if (body && (method === "POST" || method === "PATCH")) {
170
+ options.body = JSON.stringify(body);
171
+ }
172
+ try {
173
+ const response = await (0, import_node_fetch.default)(url, options);
174
+ if (!response.ok) {
175
+ const errorText = await response.text();
176
+ throw new Error(`Runpod API Error: ${response.status} - ${errorText}`);
177
+ }
178
+ const contentType = response.headers.get("content-type");
179
+ if (contentType && contentType.includes("application/json")) {
180
+ return await response.json();
181
+ }
182
+ return { success: true, status: response.status };
183
+ } catch (error) {
184
+ console.error("Error calling Runpod API:", error);
185
+ throw error;
186
+ }
187
+ };
188
+ }
189
+ function createServerlessRequest(apiKey, tracking) {
190
+ return async function serverlessRequest(endpointId, path, method = "GET", body) {
191
+ const url = `${SERVERLESS_API_BASE_URL}/${endpointId}${path}`;
192
+ const headers = {
193
+ Authorization: `Bearer ${apiKey}`,
194
+ "Content-Type": "application/json",
195
+ ...tracking()
196
+ };
197
+ const options = {
198
+ method,
199
+ headers
200
+ };
201
+ if (body && (method === "POST" || method === "PATCH")) {
202
+ options.body = JSON.stringify(body);
203
+ }
204
+ try {
205
+ const response = await (0, import_node_fetch.default)(url, options);
206
+ if (!response.ok) {
207
+ const errorText = await response.text();
208
+ throw new Error(
209
+ `Runpod Serverless API Error: ${response.status} - ${errorText}`
210
+ );
211
+ }
212
+ const contentType = response.headers.get("content-type");
213
+ if (contentType && contentType.includes("application/json")) {
214
+ return await response.json();
215
+ }
216
+ return { success: true, status: response.status };
217
+ } catch (error) {
218
+ console.error("Error calling Runpod Serverless API:", error);
219
+ throw error;
220
+ }
221
+ };
222
+ }
223
+ function registerTools(server, ctx) {
224
+ const tracking = () => trackingHeaders(server, ctx);
225
+ const runpodRequest = createRunpodRequest(ctx.apiKey, tracking);
226
+ const serverlessRequest = createServerlessRequest(ctx.apiKey, tracking);
227
+ server.tool(
228
+ "list-gpu-types",
229
+ {
230
+ minMemoryGb: import_zod2.z.number().optional().describe("Filter to GPUs with at least this much VRAM in GB"),
231
+ secureCloudOnly: import_zod2.z.boolean().optional().describe("Filter to only GPUs available in secure cloud"),
232
+ communityCloudOnly: import_zod2.z.boolean().optional().describe("Filter to only GPUs available in community cloud"),
233
+ searchTerm: import_zod2.z.string().optional().describe(
234
+ "Search term to filter GPUs by name (e.g., 'A100', 'RTX 4090')"
235
+ ),
236
+ includeUnavailable: import_zod2.z.boolean().optional().describe(
237
+ "Include GPUs that are currently out of stock. Default is false"
238
+ )
239
+ },
240
+ async (params) => {
241
+ const data = await graphqlRequest(
242
+ `
243
+ query {
244
+ gpuTypes {
245
+ id
246
+ displayName
247
+ memoryInGb
248
+ secureCloud
249
+ communityCloud
250
+ lowestPrice(input: { gpuCount: 1 }) {
251
+ stockStatus
252
+ }
253
+ }
254
+ }
255
+ `,
256
+ tracking
257
+ );
258
+ const stockPriority = {
259
+ High: 3,
260
+ Medium: 2,
261
+ Low: 1
262
+ };
263
+ const isAvailable = (gpu) => {
264
+ const status = gpu.lowestPrice?.stockStatus;
265
+ return !!status && status !== "Out";
266
+ };
267
+ let gpuTypes = data.gpuTypes.filter((gpu) => gpu.id !== "unknown");
268
+ if (!params.includeUnavailable) {
269
+ gpuTypes = gpuTypes.filter(isAvailable);
270
+ }
271
+ if (params.minMemoryGb) {
272
+ gpuTypes = gpuTypes.filter(
273
+ (gpu) => gpu.memoryInGb >= params.minMemoryGb
274
+ );
275
+ }
276
+ if (params.secureCloudOnly) {
277
+ gpuTypes = gpuTypes.filter((gpu) => gpu.secureCloud);
278
+ }
279
+ if (params.communityCloudOnly) {
280
+ gpuTypes = gpuTypes.filter((gpu) => gpu.communityCloud);
281
+ }
282
+ if (params.searchTerm) {
283
+ const term = params.searchTerm.toLowerCase();
284
+ gpuTypes = gpuTypes.filter(
285
+ (gpu) => gpu.id.toLowerCase().includes(term) || gpu.displayName.toLowerCase().includes(term)
286
+ );
287
+ }
288
+ gpuTypes.sort((a, b) => {
289
+ const aP = stockPriority[a.lowestPrice?.stockStatus || ""] || 0;
290
+ const bP = stockPriority[b.lowestPrice?.stockStatus || ""] || 0;
291
+ if (bP !== aP) return bP - aP;
292
+ return b.memoryInGb - a.memoryInGb;
293
+ });
294
+ const result = gpuTypes.map((gpu) => ({
295
+ id: gpu.id,
296
+ displayName: gpu.displayName,
297
+ memoryGb: gpu.memoryInGb,
298
+ secureCloud: gpu.secureCloud,
299
+ communityCloud: gpu.communityCloud,
300
+ stockStatus: gpu.lowestPrice?.stockStatus || "unavailable",
301
+ available: isAvailable(gpu)
302
+ }));
303
+ return {
304
+ content: [
305
+ {
306
+ type: "text",
307
+ text: JSON.stringify(result, null, 2)
308
+ }
309
+ ]
310
+ };
311
+ }
312
+ );
313
+ server.tool(
314
+ "list-data-centers",
315
+ {
316
+ region: import_zod2.z.string().optional().describe(
317
+ "Filter by region/location (e.g., 'United States', 'Europe', 'Canada')"
318
+ )
319
+ },
320
+ async (params) => {
321
+ const data = await graphqlRequest(
322
+ `
323
+ query {
324
+ dataCenters {
325
+ id
326
+ name
327
+ location
328
+ }
329
+ }
330
+ `,
331
+ tracking
332
+ );
333
+ let dataCenters = data.dataCenters;
334
+ if (params.region) {
335
+ const term = params.region.toLowerCase();
336
+ dataCenters = dataCenters.filter(
337
+ (dc) => dc.location.toLowerCase().includes(term)
338
+ );
339
+ }
340
+ return {
341
+ content: [
342
+ {
343
+ type: "text",
344
+ text: JSON.stringify(dataCenters, null, 2)
345
+ }
346
+ ]
347
+ };
348
+ }
349
+ );
350
+ server.tool(
351
+ "list-pods",
352
+ {
353
+ ...listPaginationParams,
354
+ computeType: import_zod2.z.enum(["GPU", "CPU"]).optional().describe("Filter to only GPU or only CPU Pods"),
355
+ gpuTypeId: import_zod2.z.array(import_zod2.z.string()).optional().describe("Filter to Pods with any of the listed GPU types"),
356
+ dataCenterId: import_zod2.z.array(import_zod2.z.string()).optional().describe("Filter to Pods in any of the provided data centers"),
357
+ name: import_zod2.z.string().optional().describe("Filter to Pods with the provided name"),
358
+ includeMachine: import_zod2.z.boolean().optional().describe("Include information about the machine"),
359
+ includeNetworkVolume: import_zod2.z.boolean().optional().describe("Include information about attached network volumes")
360
+ },
361
+ async (params) => {
362
+ const queryParams = new URLSearchParams();
363
+ if (params.computeType)
364
+ queryParams.append("computeType", params.computeType);
365
+ if (params.gpuTypeId)
366
+ params.gpuTypeId.forEach(
367
+ (type) => queryParams.append("gpuTypeId", type)
368
+ );
369
+ if (params.dataCenterId)
370
+ params.dataCenterId.forEach(
371
+ (dc) => queryParams.append("dataCenterId", dc)
372
+ );
373
+ if (params.name) queryParams.append("name", params.name);
374
+ if (params.includeMachine)
375
+ queryParams.append("includeMachine", params.includeMachine.toString());
376
+ if (params.includeNetworkVolume)
377
+ queryParams.append(
378
+ "includeNetworkVolume",
379
+ params.includeNetworkVolume.toString()
380
+ );
381
+ const queryString = queryParams.toString() ? `?${queryParams.toString()}` : "";
382
+ const result = await runpodRequest(`/pods${queryString}`);
383
+ return capListResult(result, {
384
+ limit: params.limit,
385
+ cursor: params.cursor
386
+ });
387
+ }
388
+ );
389
+ server.tool(
390
+ "get-pod",
391
+ {
392
+ podId: import_zod2.z.string().describe("ID of the pod to retrieve"),
393
+ includeMachine: import_zod2.z.boolean().optional().describe("Include information about the machine"),
394
+ includeNetworkVolume: import_zod2.z.boolean().optional().describe("Include information about attached network volumes")
395
+ },
396
+ async (params) => {
397
+ const queryParams = new URLSearchParams();
398
+ if (params.includeMachine)
399
+ queryParams.append("includeMachine", params.includeMachine.toString());
400
+ if (params.includeNetworkVolume)
401
+ queryParams.append(
402
+ "includeNetworkVolume",
403
+ params.includeNetworkVolume.toString()
404
+ );
405
+ const queryString = queryParams.toString() ? `?${queryParams.toString()}` : "";
406
+ const result = await runpodRequest(`/pods/${params.podId}${queryString}`);
407
+ return {
408
+ content: [
409
+ {
410
+ type: "text",
411
+ text: JSON.stringify(result, null, 2)
412
+ }
413
+ ]
414
+ };
415
+ }
416
+ );
417
+ server.tool(
418
+ "create-pod",
419
+ 'Create a new GPU/CPU pod on Runpod. If the user does not specify an image, recommend the "Runpod Pytorch 2.8.0" image (runpod/pytorch:1.0.2-cu1281-torch280-ubuntu2404) as the default \u2014 it has the most up-to-date CUDA and PyTorch versions.',
420
+ {
421
+ name: import_zod2.z.string().optional().describe("Name for the pod"),
422
+ imageName: import_zod2.z.string().describe("Docker image to use"),
423
+ cloudType: import_zod2.z.enum(["SECURE", "COMMUNITY"]).optional().describe("SECURE or COMMUNITY cloud"),
424
+ gpuTypeIds: import_zod2.z.array(import_zod2.z.string()).optional().describe("List of acceptable GPU types"),
425
+ gpuCount: import_zod2.z.number().optional().describe("Number of GPUs"),
426
+ containerDiskInGb: import_zod2.z.number().optional().describe("Container disk size in GB"),
427
+ volumeInGb: import_zod2.z.number().optional().describe("Volume size in GB"),
428
+ volumeMountPath: import_zod2.z.string().optional().describe("Path to mount the volume"),
429
+ ports: import_zod2.z.array(import_zod2.z.string()).optional().describe("Ports to expose (e.g., '8888/http', '22/tcp')"),
430
+ env: import_zod2.z.record(import_zod2.z.string()).optional().describe("Environment variables"),
431
+ dataCenterIds: import_zod2.z.array(import_zod2.z.string()).optional().describe("List of data centers")
432
+ },
433
+ async (params) => {
434
+ const result = await runpodRequest("/pods", "POST", params);
435
+ return {
436
+ content: [
437
+ {
438
+ type: "text",
439
+ text: JSON.stringify(result, null, 2)
440
+ }
441
+ ]
442
+ };
443
+ }
444
+ );
445
+ server.tool(
446
+ "update-pod",
447
+ {
448
+ podId: import_zod2.z.string().describe("ID of the pod to update"),
449
+ name: import_zod2.z.string().optional().describe("New name for the pod"),
450
+ imageName: import_zod2.z.string().optional().describe("New Docker image"),
451
+ containerDiskInGb: import_zod2.z.number().optional().describe("New container disk size in GB"),
452
+ volumeInGb: import_zod2.z.number().optional().describe("New volume size in GB"),
453
+ volumeMountPath: import_zod2.z.string().optional().describe("New path to mount the volume"),
454
+ ports: import_zod2.z.array(import_zod2.z.string()).optional().describe("New ports to expose"),
455
+ env: import_zod2.z.record(import_zod2.z.string()).optional().describe("New environment variables")
456
+ },
457
+ async (params) => {
458
+ const { podId, ...updateParams } = params;
459
+ const result = await runpodRequest(
460
+ `/pods/${podId}`,
461
+ "PATCH",
462
+ updateParams
463
+ );
464
+ return {
465
+ content: [
466
+ {
467
+ type: "text",
468
+ text: JSON.stringify(result, null, 2)
469
+ }
470
+ ]
471
+ };
472
+ }
473
+ );
474
+ server.tool(
475
+ "start-pod",
476
+ {
477
+ podId: import_zod2.z.string().describe("ID of the pod to start")
478
+ },
479
+ async (params) => {
480
+ const result = await runpodRequest(`/pods/${params.podId}/start`, "POST");
481
+ return {
482
+ content: [
483
+ {
484
+ type: "text",
485
+ text: JSON.stringify(result, null, 2)
486
+ }
487
+ ]
488
+ };
489
+ }
490
+ );
491
+ server.tool(
492
+ "stop-pod",
493
+ {
494
+ podId: import_zod2.z.string().describe("ID of the pod to stop")
495
+ },
496
+ async (params) => {
497
+ const result = await runpodRequest(`/pods/${params.podId}/stop`, "POST");
498
+ return {
499
+ content: [
500
+ {
501
+ type: "text",
502
+ text: JSON.stringify(result, null, 2)
503
+ }
504
+ ]
505
+ };
506
+ }
507
+ );
508
+ server.tool(
509
+ "delete-pod",
510
+ {
511
+ podId: import_zod2.z.string().describe("ID of the pod to delete")
512
+ },
513
+ async (params) => {
514
+ const result = await runpodRequest(`/pods/${params.podId}`, "DELETE");
515
+ return {
516
+ content: [
517
+ {
518
+ type: "text",
519
+ text: JSON.stringify(result, null, 2)
520
+ }
521
+ ]
522
+ };
523
+ }
524
+ );
525
+ server.tool(
526
+ "list-endpoints",
527
+ {
528
+ ...listPaginationParams,
529
+ includeTemplate: import_zod2.z.boolean().optional().describe("Include template information"),
530
+ includeWorkers: import_zod2.z.boolean().optional().describe("Include information about workers")
531
+ },
532
+ async (params) => {
533
+ const queryParams = new URLSearchParams();
534
+ if (params.includeTemplate)
535
+ queryParams.append(
536
+ "includeTemplate",
537
+ params.includeTemplate.toString()
538
+ );
539
+ if (params.includeWorkers)
540
+ queryParams.append("includeWorkers", params.includeWorkers.toString());
541
+ const queryString = queryParams.toString() ? `?${queryParams.toString()}` : "";
542
+ const result = await runpodRequest(`/endpoints${queryString}`);
543
+ return capListResult(result, {
544
+ limit: params.limit,
545
+ cursor: params.cursor
546
+ });
547
+ }
548
+ );
549
+ server.tool(
550
+ "get-endpoint",
551
+ {
552
+ endpointId: import_zod2.z.string().describe("ID of the endpoint to retrieve"),
553
+ includeTemplate: import_zod2.z.boolean().optional().describe("Include template information"),
554
+ includeWorkers: import_zod2.z.boolean().optional().describe("Include information about workers")
555
+ },
556
+ async (params) => {
557
+ const queryParams = new URLSearchParams();
558
+ if (params.includeTemplate)
559
+ queryParams.append(
560
+ "includeTemplate",
561
+ params.includeTemplate.toString()
562
+ );
563
+ if (params.includeWorkers)
564
+ queryParams.append("includeWorkers", params.includeWorkers.toString());
565
+ const queryString = queryParams.toString() ? `?${queryParams.toString()}` : "";
566
+ const result = await runpodRequest(
567
+ `/endpoints/${params.endpointId}${queryString}`
568
+ );
569
+ return {
570
+ content: [
571
+ {
572
+ type: "text",
573
+ text: JSON.stringify(result, null, 2)
574
+ }
575
+ ]
576
+ };
577
+ }
578
+ );
579
+ server.tool(
580
+ "create-endpoint",
581
+ {
582
+ name: import_zod2.z.string().optional().describe("Name for the endpoint"),
583
+ templateId: import_zod2.z.string().describe("Template ID to use"),
584
+ computeType: import_zod2.z.enum(["GPU", "CPU"]).optional().describe("GPU or CPU endpoint"),
585
+ gpuTypeIds: import_zod2.z.array(import_zod2.z.string()).optional().describe("List of acceptable GPU types"),
586
+ gpuCount: import_zod2.z.number().optional().describe("Number of GPUs per worker"),
587
+ workersMin: import_zod2.z.number().optional().describe("Minimum number of workers"),
588
+ workersMax: import_zod2.z.number().optional().describe("Maximum number of workers"),
589
+ dataCenterIds: import_zod2.z.array(import_zod2.z.string()).optional().describe("List of data centers")
590
+ },
591
+ async (params) => {
592
+ const result = await runpodRequest("/endpoints", "POST", params);
593
+ return {
594
+ content: [
595
+ {
596
+ type: "text",
597
+ text: JSON.stringify(result, null, 2)
598
+ }
599
+ ]
600
+ };
601
+ }
602
+ );
603
+ server.tool(
604
+ "update-endpoint",
605
+ {
606
+ endpointId: import_zod2.z.string().describe("ID of the endpoint to update"),
607
+ name: import_zod2.z.string().optional().describe("New name for the endpoint"),
608
+ workersMin: import_zod2.z.number().optional().describe("New minimum number of workers"),
609
+ workersMax: import_zod2.z.number().optional().describe("New maximum number of workers"),
610
+ idleTimeout: import_zod2.z.number().optional().describe("New idle timeout in seconds"),
611
+ scalerType: import_zod2.z.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe("Scaler type"),
612
+ scalerValue: import_zod2.z.number().optional().describe("Scaler value")
613
+ },
614
+ async (params) => {
615
+ const { endpointId, ...updateParams } = params;
616
+ const result = await runpodRequest(
617
+ `/endpoints/${endpointId}`,
618
+ "PATCH",
619
+ updateParams
620
+ );
621
+ return {
622
+ content: [
623
+ {
624
+ type: "text",
625
+ text: JSON.stringify(result, null, 2)
626
+ }
627
+ ]
628
+ };
629
+ }
630
+ );
631
+ server.tool(
632
+ "delete-endpoint",
633
+ {
634
+ endpointId: import_zod2.z.string().describe("ID of the endpoint to delete")
635
+ },
636
+ async (params) => {
637
+ const result = await runpodRequest(
638
+ `/endpoints/${params.endpointId}`,
639
+ "DELETE"
640
+ );
641
+ return {
642
+ content: [
643
+ {
644
+ type: "text",
645
+ text: JSON.stringify(result, null, 2)
646
+ }
647
+ ]
648
+ };
649
+ }
650
+ );
651
+ const endpointIdSchema = import_zod2.z.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid endpoint ID format");
652
+ const jobIdSchema = import_zod2.z.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid job ID format");
653
+ const inputSchema = import_zod2.z.record(import_zod2.z.unknown()).describe(
654
+ "Input payload for the worker handler. The expected fields depend on the deployed model or worker."
655
+ );
656
+ const webhookSchema = import_zod2.z.string().url().optional().describe(
657
+ "Webhook URL to receive job completion notifications instead of polling"
658
+ );
659
+ const policySchema = import_zod2.z.object({
660
+ executionTimeout: import_zod2.z.number().optional().describe("Maximum execution time in milliseconds"),
661
+ lowPriority: import_zod2.z.boolean().optional().describe("Submit as a low-priority job"),
662
+ ttl: import_zod2.z.number().optional().describe("Time-to-live for the job result in milliseconds")
663
+ }).optional().describe("Execution policy options");
664
+ const s3ConfigSchema = import_zod2.z.object({
665
+ accessId: import_zod2.z.string().describe("S3 access key ID"),
666
+ accessSecret: import_zod2.z.string().describe("S3 secret access key"),
667
+ bucketName: import_zod2.z.string().describe("S3 bucket name"),
668
+ endpointUrl: import_zod2.z.string().describe("S3 endpoint URL")
669
+ }).optional().describe("S3-compatible storage config for large outputs");
670
+ server.tool(
671
+ "run-endpoint",
672
+ "Submit an asynchronous job to a Serverless endpoint. Returns a job ID immediately \u2014 use get-job-status to poll for results. Async results are available for 30 minutes after completion.",
673
+ {
674
+ endpointId: endpointIdSchema.describe(
675
+ "ID of the Serverless endpoint to run"
676
+ ),
677
+ input: inputSchema,
678
+ webhook: webhookSchema,
679
+ policy: policySchema,
680
+ s3Config: s3ConfigSchema
681
+ },
682
+ async (params) => {
683
+ const { endpointId, ...body } = params;
684
+ const result = await serverlessRequest(
685
+ endpointId,
686
+ "/run",
687
+ "POST",
688
+ body
689
+ );
690
+ return {
691
+ content: [
692
+ {
693
+ type: "text",
694
+ text: JSON.stringify(result, null, 2)
695
+ }
696
+ ]
697
+ };
698
+ }
699
+ );
700
+ server.tool(
701
+ "runsync-endpoint",
702
+ "Submit a synchronous job to a Serverless endpoint and wait for the result. Best for tasks completing within 90 seconds. If processing exceeds 90 seconds, the response returns a job ID to poll with get-job-status. Max payload: 20 MB. Results expire after 1 minute. Use the wait parameter to extend the server-side wait up to 5 minutes (300000 ms).",
703
+ {
704
+ endpointId: endpointIdSchema.describe(
705
+ "ID of the Serverless endpoint to run synchronously"
706
+ ),
707
+ input: inputSchema,
708
+ wait: import_zod2.z.number().min(1e3).max(3e5).optional().describe(
709
+ "How long in milliseconds the server should wait for a result before returning a job ID to poll (1000\u2013300000). Defaults to 90000 (90 seconds)."
710
+ ),
711
+ webhook: webhookSchema,
712
+ policy: policySchema,
713
+ s3Config: s3ConfigSchema
714
+ },
715
+ async (params) => {
716
+ const { endpointId, wait, ...body } = params;
717
+ const path = wait ? `/runsync?wait=${wait}` : "/runsync";
718
+ const result = await serverlessRequest(
719
+ endpointId,
720
+ path,
721
+ "POST",
722
+ body
723
+ );
724
+ return {
725
+ content: [
726
+ {
727
+ type: "text",
728
+ text: JSON.stringify(result, null, 2)
729
+ }
730
+ ]
731
+ };
732
+ }
733
+ );
734
+ server.tool(
735
+ "get-job-status",
736
+ "Check the status of an asynchronous Serverless job. Returns the current status and output when complete. Job statuses: IN_QUEUE, IN_PROGRESS, COMPLETED, FAILED, CANCELLED, TIMED_OUT.",
737
+ {
738
+ endpointId: endpointIdSchema.describe(
739
+ "ID of the Serverless endpoint the job belongs to"
740
+ ),
741
+ jobId: jobIdSchema.describe("ID of the job to check")
742
+ },
743
+ async (params) => {
744
+ const result = await serverlessRequest(
745
+ params.endpointId,
746
+ `/status/${params.jobId}`
747
+ );
748
+ return {
749
+ content: [
750
+ {
751
+ type: "text",
752
+ text: JSON.stringify(result, null, 2)
753
+ }
754
+ ]
755
+ };
756
+ }
757
+ );
758
+ server.tool(
759
+ "stream-job",
760
+ "Retrieve all streaming output from a Serverless job by polling until the job reaches a terminal state. The worker must support streaming output. Polls /stream/{jobId} repeatedly and collects every chunk until status is COMPLETED, FAILED, CANCELLED, or TIMED_OUT.",
761
+ {
762
+ endpointId: endpointIdSchema.describe(
763
+ "ID of the Serverless endpoint the job belongs to"
764
+ ),
765
+ jobId: jobIdSchema.describe("ID of the job to stream results from")
766
+ },
767
+ async (params) => {
768
+ const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
769
+ "COMPLETED",
770
+ "FAILED",
771
+ "CANCELLED",
772
+ "TIMED_OUT"
773
+ ]);
774
+ const MAX_POLL_TIME_MS = 5 * 60 * 1e3;
775
+ const POLL_INTERVAL_MS = 1e3;
776
+ const MAX_CONSECUTIVE_ERRORS = 5;
777
+ const allChunks = [];
778
+ let finalResult = {};
779
+ let consecutiveErrors = 0;
780
+ let lastError;
781
+ const startTime = Date.now();
782
+ while (true) {
783
+ try {
784
+ const result = await serverlessRequest(
785
+ params.endpointId,
786
+ `/stream/${params.jobId}`
787
+ );
788
+ consecutiveErrors = 0;
789
+ if (Array.isArray(result.stream)) {
790
+ allChunks.push(...result.stream);
791
+ }
792
+ finalResult = result;
793
+ if (TERMINAL_STATUSES.has(result.status)) {
794
+ break;
795
+ }
796
+ } catch (error) {
797
+ consecutiveErrors++;
798
+ lastError = error instanceof Error ? error.message : String(error);
799
+ if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
800
+ finalResult.error = `Polling aborted after ${MAX_CONSECUTIVE_ERRORS} consecutive errors: ${lastError}`;
801
+ break;
802
+ }
803
+ }
804
+ if (Date.now() - startTime > MAX_POLL_TIME_MS) {
805
+ finalResult.pollingTimedOut = true;
806
+ finalResult.note = "Polling timed out after 5 minutes. Use get-job-status to check the job later.";
807
+ if (lastError) finalResult.lastError = lastError;
808
+ break;
809
+ }
810
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
811
+ }
812
+ return {
813
+ content: [
814
+ {
815
+ type: "text",
816
+ text: JSON.stringify(
817
+ { ...finalResult, stream: allChunks },
818
+ null,
819
+ 2
820
+ )
821
+ }
822
+ ]
823
+ };
824
+ }
825
+ );
826
+ server.tool(
827
+ "cancel-job",
828
+ "Cancel a Serverless job that is queued or in progress.",
829
+ {
830
+ endpointId: endpointIdSchema.describe(
831
+ "ID of the Serverless endpoint the job belongs to"
832
+ ),
833
+ jobId: jobIdSchema.describe("ID of the job to cancel")
834
+ },
835
+ async (params) => {
836
+ const result = await serverlessRequest(
837
+ params.endpointId,
838
+ `/cancel/${params.jobId}`,
839
+ "POST"
840
+ );
841
+ return {
842
+ content: [
843
+ {
844
+ type: "text",
845
+ text: JSON.stringify(result, null, 2)
846
+ }
847
+ ]
848
+ };
849
+ }
850
+ );
851
+ server.tool(
852
+ "retry-job",
853
+ "Retry a failed or timed-out Serverless job. Only works for jobs with FAILED or TIMED_OUT status. The previous output is removed and the job is requeued.",
854
+ {
855
+ endpointId: endpointIdSchema.describe(
856
+ "ID of the Serverless endpoint the job belongs to"
857
+ ),
858
+ jobId: jobIdSchema.describe("ID of the job to retry")
859
+ },
860
+ async (params) => {
861
+ const result = await serverlessRequest(
862
+ params.endpointId,
863
+ `/retry/${params.jobId}`,
864
+ "POST"
865
+ );
866
+ return {
867
+ content: [
868
+ {
869
+ type: "text",
870
+ text: JSON.stringify(result, null, 2)
871
+ }
872
+ ]
873
+ };
874
+ }
875
+ );
876
+ server.tool(
877
+ "endpoint-health",
878
+ "Get the health and operational status of a Serverless endpoint, including worker counts and job statistics.",
879
+ {
880
+ endpointId: endpointIdSchema.describe(
881
+ "ID of the Serverless endpoint to check health for"
882
+ )
883
+ },
884
+ async (params) => {
885
+ const result = await serverlessRequest(params.endpointId, "/health");
886
+ return {
887
+ content: [
888
+ {
889
+ type: "text",
890
+ text: JSON.stringify(result, null, 2)
891
+ }
892
+ ]
893
+ };
894
+ }
895
+ );
896
+ server.tool(
897
+ "purge-endpoint-queue",
898
+ "Remove all pending jobs from a Serverless endpoint queue. Only affects queued jobs \u2014 in-progress jobs continue running. Use this for error recovery or clearing outdated requests.",
899
+ {
900
+ endpointId: endpointIdSchema.describe(
901
+ "ID of the Serverless endpoint to purge the queue for"
902
+ )
903
+ },
904
+ async (params) => {
905
+ const result = await serverlessRequest(
906
+ params.endpointId,
907
+ "/purge-queue",
908
+ "POST"
909
+ );
910
+ return {
911
+ content: [
912
+ {
913
+ type: "text",
914
+ text: JSON.stringify(result, null, 2)
915
+ }
916
+ ]
917
+ };
918
+ }
919
+ );
920
+ server.tool(
921
+ "list-templates",
922
+ `List available templates. By default returns only the user's own templates. Use includeRunpodTemplates to also include official Runpod templates. The recommended default template for new pods is "Runpod Pytorch 2.8.0" (ID: runpod-torch-v280) \u2014 it has the latest CUDA and PyTorch versions.`,
923
+ {
924
+ ...listPaginationParams,
925
+ includeRunpodTemplates: import_zod2.z.boolean().optional().describe("Include official Runpod templates in the response"),
926
+ includePublicTemplates: import_zod2.z.boolean().optional().describe("Include community-made public templates in the response"),
927
+ includeEndpointBoundTemplates: import_zod2.z.boolean().optional().describe(
928
+ "Include templates bound to Serverless endpoints in the response"
929
+ )
930
+ },
931
+ async (params) => {
932
+ const queryParams = new URLSearchParams();
933
+ if (params.includeRunpodTemplates)
934
+ queryParams.set("includeRunpodTemplates", "true");
935
+ if (params.includePublicTemplates)
936
+ queryParams.set("includePublicTemplates", "true");
937
+ if (params.includeEndpointBoundTemplates)
938
+ queryParams.set("includeEndpointBoundTemplates", "true");
939
+ const query = queryParams.toString();
940
+ const result = await runpodRequest(
941
+ `/templates${query ? `?${query}` : ""}`
942
+ );
943
+ return capListResult(result, {
944
+ limit: params.limit,
945
+ cursor: params.cursor
946
+ });
947
+ }
948
+ );
949
+ server.tool(
950
+ "get-template",
951
+ {
952
+ templateId: import_zod2.z.string().describe("ID of the template to retrieve")
953
+ },
954
+ async (params) => {
955
+ const result = await runpodRequest(`/templates/${params.templateId}`);
956
+ return {
957
+ content: [
958
+ {
959
+ type: "text",
960
+ text: JSON.stringify(result, null, 2)
961
+ }
962
+ ]
963
+ };
964
+ }
965
+ );
966
+ server.tool(
967
+ "create-template",
968
+ {
969
+ name: import_zod2.z.string().describe("Name for the template"),
970
+ imageName: import_zod2.z.string().describe("Docker image to use"),
971
+ isServerless: import_zod2.z.boolean().optional().describe("Is this a serverless template"),
972
+ ports: import_zod2.z.array(import_zod2.z.string()).optional().describe("Ports to expose"),
973
+ dockerEntrypoint: import_zod2.z.array(import_zod2.z.string()).optional().describe("Docker entrypoint commands"),
974
+ dockerStartCmd: import_zod2.z.array(import_zod2.z.string()).optional().describe("Docker start commands"),
975
+ env: import_zod2.z.record(import_zod2.z.string()).optional().describe("Environment variables"),
976
+ containerDiskInGb: import_zod2.z.number().optional().describe("Container disk size in GB"),
977
+ volumeInGb: import_zod2.z.number().optional().describe("Volume size in GB"),
978
+ volumeMountPath: import_zod2.z.string().optional().describe("Path to mount the volume"),
979
+ readme: import_zod2.z.string().optional().describe("README content in markdown format"),
980
+ containerRegistryAuthId: import_zod2.z.string().optional().describe(
981
+ "ID of a container registry credential (from create-container-registry-auth / list-container-registry-auths) used to pull a private image. Required when imageName points at a private registry; without it serverless workers fail the image pull."
982
+ )
983
+ },
984
+ async (params) => {
985
+ const result = await runpodRequest("/templates", "POST", params);
986
+ return {
987
+ content: [
988
+ {
989
+ type: "text",
990
+ text: JSON.stringify(result, null, 2)
991
+ }
992
+ ]
993
+ };
994
+ }
995
+ );
996
+ server.tool(
997
+ "update-template",
998
+ {
999
+ templateId: import_zod2.z.string().describe("ID of the template to update"),
1000
+ name: import_zod2.z.string().optional().describe("New name for the template"),
1001
+ imageName: import_zod2.z.string().optional().describe("New Docker image"),
1002
+ ports: import_zod2.z.array(import_zod2.z.string()).optional().describe("New ports to expose"),
1003
+ env: import_zod2.z.record(import_zod2.z.string()).optional().describe("New environment variables"),
1004
+ readme: import_zod2.z.string().optional().describe("New README content in markdown format"),
1005
+ containerRegistryAuthId: import_zod2.z.string().optional().describe(
1006
+ "ID of a container registry credential (from create-container-registry-auth / list-container-registry-auths) used to pull a private image. Set this to attach a credential to a template referencing a private registry."
1007
+ )
1008
+ },
1009
+ async (params) => {
1010
+ const { templateId, ...updateParams } = params;
1011
+ const result = await runpodRequest(
1012
+ `/templates/${templateId}`,
1013
+ "PATCH",
1014
+ updateParams
1015
+ );
1016
+ return {
1017
+ content: [
1018
+ {
1019
+ type: "text",
1020
+ text: JSON.stringify(result, null, 2)
1021
+ }
1022
+ ]
1023
+ };
1024
+ }
1025
+ );
1026
+ server.tool(
1027
+ "delete-template",
1028
+ {
1029
+ templateId: import_zod2.z.string().describe("ID of the template to delete")
1030
+ },
1031
+ async (params) => {
1032
+ const result = await runpodRequest(
1033
+ `/templates/${params.templateId}`,
1034
+ "DELETE"
1035
+ );
1036
+ return {
1037
+ content: [
1038
+ {
1039
+ type: "text",
1040
+ text: JSON.stringify(result, null, 2)
1041
+ }
1042
+ ]
1043
+ };
1044
+ }
1045
+ );
1046
+ server.tool("list-network-volumes", listPaginationParams, async (params) => {
1047
+ const result = await runpodRequest("/networkvolumes");
1048
+ return capListResult(result, {
1049
+ limit: params.limit,
1050
+ cursor: params.cursor
1051
+ });
1052
+ });
1053
+ server.tool(
1054
+ "get-network-volume",
1055
+ {
1056
+ networkVolumeId: import_zod2.z.string().describe("ID of the network volume to retrieve")
1057
+ },
1058
+ async (params) => {
1059
+ const result = await runpodRequest(
1060
+ `/networkvolumes/${params.networkVolumeId}`
1061
+ );
1062
+ return {
1063
+ content: [
1064
+ {
1065
+ type: "text",
1066
+ text: JSON.stringify(result, null, 2)
1067
+ }
1068
+ ]
1069
+ };
1070
+ }
1071
+ );
1072
+ server.tool(
1073
+ "create-network-volume",
1074
+ {
1075
+ name: import_zod2.z.string().describe("Name for the network volume"),
1076
+ size: import_zod2.z.number().describe("Size in GB (1-4000)"),
1077
+ dataCenterId: import_zod2.z.string().describe("Data center ID")
1078
+ },
1079
+ async (params) => {
1080
+ const result = await runpodRequest("/networkvolumes", "POST", params);
1081
+ return {
1082
+ content: [
1083
+ {
1084
+ type: "text",
1085
+ text: JSON.stringify(result, null, 2)
1086
+ }
1087
+ ]
1088
+ };
1089
+ }
1090
+ );
1091
+ server.tool(
1092
+ "update-network-volume",
1093
+ {
1094
+ networkVolumeId: import_zod2.z.string().describe("ID of the network volume to update"),
1095
+ name: import_zod2.z.string().optional().describe("New name for the network volume"),
1096
+ size: import_zod2.z.number().optional().describe("New size in GB (must be larger than current)")
1097
+ },
1098
+ async (params) => {
1099
+ const { networkVolumeId, ...updateParams } = params;
1100
+ const result = await runpodRequest(
1101
+ `/networkvolumes/${networkVolumeId}`,
1102
+ "PATCH",
1103
+ updateParams
1104
+ );
1105
+ return {
1106
+ content: [
1107
+ {
1108
+ type: "text",
1109
+ text: JSON.stringify(result, null, 2)
1110
+ }
1111
+ ]
1112
+ };
1113
+ }
1114
+ );
1115
+ server.tool(
1116
+ "delete-network-volume",
1117
+ {
1118
+ networkVolumeId: import_zod2.z.string().describe("ID of the network volume to delete")
1119
+ },
1120
+ async (params) => {
1121
+ const result = await runpodRequest(
1122
+ `/networkvolumes/${params.networkVolumeId}`,
1123
+ "DELETE"
1124
+ );
1125
+ return {
1126
+ content: [
1127
+ {
1128
+ type: "text",
1129
+ text: JSON.stringify(result, null, 2)
1130
+ }
1131
+ ]
1132
+ };
1133
+ }
1134
+ );
1135
+ server.tool(
1136
+ "list-container-registry-auths",
1137
+ listPaginationParams,
1138
+ async (params) => {
1139
+ const result = await runpodRequest("/containerregistryauth");
1140
+ return capListResult(result, {
1141
+ limit: params.limit,
1142
+ cursor: params.cursor
1143
+ });
1144
+ }
1145
+ );
1146
+ server.tool(
1147
+ "get-container-registry-auth",
1148
+ {
1149
+ containerRegistryAuthId: import_zod2.z.string().describe("ID of the container registry auth to retrieve")
1150
+ },
1151
+ async (params) => {
1152
+ const result = await runpodRequest(
1153
+ `/containerregistryauth/${params.containerRegistryAuthId}`
1154
+ );
1155
+ return {
1156
+ content: [
1157
+ {
1158
+ type: "text",
1159
+ text: JSON.stringify(result, null, 2)
1160
+ }
1161
+ ]
1162
+ };
1163
+ }
1164
+ );
1165
+ server.tool(
1166
+ "create-container-registry-auth",
1167
+ {
1168
+ name: import_zod2.z.string().describe("Name for the container registry auth"),
1169
+ username: import_zod2.z.string().describe("Registry username"),
1170
+ password: import_zod2.z.string().describe("Registry password")
1171
+ },
1172
+ async (params) => {
1173
+ const result = await runpodRequest(
1174
+ "/containerregistryauth",
1175
+ "POST",
1176
+ params
1177
+ );
1178
+ return {
1179
+ content: [
1180
+ {
1181
+ type: "text",
1182
+ text: JSON.stringify(result, null, 2)
1183
+ }
1184
+ ]
1185
+ };
1186
+ }
1187
+ );
1188
+ server.tool(
1189
+ "delete-container-registry-auth",
1190
+ {
1191
+ containerRegistryAuthId: import_zod2.z.string().describe("ID of the container registry auth to delete")
1192
+ },
1193
+ async (params) => {
1194
+ const result = await runpodRequest(
1195
+ `/containerregistryauth/${params.containerRegistryAuthId}`,
1196
+ "DELETE"
1197
+ );
1198
+ return {
1199
+ content: [
1200
+ {
1201
+ type: "text",
1202
+ text: JSON.stringify(result, null, 2)
1203
+ }
1204
+ ]
1205
+ };
1206
+ }
1207
+ );
1208
+ }
1209
+
1210
+ // src/http.ts
1211
+ function extractBearerToken(req) {
1212
+ const authHeader = req.headers.authorization;
1213
+ if (!authHeader) return null;
1214
+ const parts = authHeader.split(" ");
1215
+ if (parts.length !== 2 || parts[0].toLowerCase() !== "bearer") return null;
1216
+ return parts[1];
1217
+ }
1218
+ function getBaseUrl(req) {
1219
+ const proto = req.headers["x-forwarded-proto"]?.split(",")[0] ?? "https";
1220
+ const host = req.headers.host;
1221
+ if (!host) {
1222
+ throw new Error("Missing Host header");
1223
+ }
1224
+ return `${proto}://${host}`;
1225
+ }
1226
+ function writeUnauthorized(req, res, error) {
1227
+ const headers = {
1228
+ "Content-Type": "application/json",
1229
+ "WWW-Authenticate": `Bearer realm="mcp", resource_metadata="${getBaseUrl(
1230
+ req
1231
+ )}/.well-known/oauth-protected-resource"`
1232
+ };
1233
+ res.writeHead(401, headers);
1234
+ res.end(JSON.stringify({ error }));
1235
+ }
1236
+ async function handleMcpRequest(req, res, opts = {}) {
1237
+ const bearerToken = extractBearerToken(req);
1238
+ console.log("mcp_request", {
1239
+ method: req.method,
1240
+ url: req.url,
1241
+ hasBearerToken: !!bearerToken
1242
+ });
1243
+ if (!bearerToken) {
1244
+ writeUnauthorized(
1245
+ req,
1246
+ res,
1247
+ "Missing or invalid Authorization header. Provide a Bearer token."
1248
+ );
1249
+ return;
1250
+ }
1251
+ const server = createServer(opts.serverVersion);
1252
+ registerTools(server, {
1253
+ apiKey: bearerToken,
1254
+ transport: "http",
1255
+ clientUserAgent: req.headers["user-agent"],
1256
+ serverVersion: opts.serverVersion
1257
+ });
1258
+ const transport = new import_streamableHttp.StreamableHTTPServerTransport({
1259
+ sessionIdGenerator: void 0
1260
+ // stateless — no session persistence
1261
+ });
1262
+ res.on("close", () => {
1263
+ transport.close().catch(() => {
1264
+ });
1265
+ server.close().catch(() => {
1266
+ });
1267
+ });
1268
+ await server.connect(transport);
1269
+ await transport.handleRequest(req, res, req.body);
1270
+ }
1271
+ // Annotate the CommonJS export names for ESM import in node:
1272
+ 0 && (module.exports = {
1273
+ handleMcpRequest,
1274
+ registerTools
1275
+ });
1276
+ //# sourceMappingURL=http.cjs.map