@runpod/mcp-server 2.0.0 → 3.1.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.
@@ -0,0 +1,3023 @@
1
+ // src/tools/runtime.ts
2
+ import fetch from "node-fetch";
3
+ import { randomUUID } from "crypto";
4
+
5
+ // src/_shared/http.ts
6
+ var HttpError = class extends Error {
7
+ constructor(prefix, status, body) {
8
+ const hint = status === 401 ? " (the Runpod API rejected the credential \u2014 the API key may be expired or revoked; re-authenticate or update RUNPOD_API_KEY)" : "";
9
+ super(`${prefix}: ${status} - ${body}${hint}`);
10
+ this.name = "HttpError";
11
+ this.status = status;
12
+ this.body = body;
13
+ }
14
+ };
15
+ function isJsonContentType(contentType) {
16
+ if (!contentType) return false;
17
+ const ct = contentType.toLowerCase();
18
+ return ct.includes("application/json") || ct.includes("+json");
19
+ }
20
+ function methodSendsBody(method) {
21
+ return method === "POST" || method === "PATCH" || method === "PUT";
22
+ }
23
+ function buildRequestHeaders(apiKey, tracking) {
24
+ return {
25
+ Authorization: `Bearer ${apiKey}`,
26
+ "Content-Type": "application/json",
27
+ ...tracking()
28
+ };
29
+ }
30
+ function createHttpClient(deps) {
31
+ return async function request(url, method = "GET", body) {
32
+ const init = {
33
+ method,
34
+ headers: buildRequestHeaders(deps.apiKey, deps.tracking)
35
+ };
36
+ if (body && methodSendsBody(method)) {
37
+ init.body = JSON.stringify(body);
38
+ }
39
+ const response = await deps.fetch(url, init);
40
+ if (!response.ok) {
41
+ throw new HttpError(
42
+ deps.errorPrefix,
43
+ response.status,
44
+ await response.text()
45
+ );
46
+ }
47
+ return isJsonContentType(response.headers.get("content-type")) ? response.json() : { success: true, status: response.status };
48
+ };
49
+ }
50
+
51
+ // src/_shared/tracking.ts
52
+ function sanitizeUaToken(value) {
53
+ return value.replace(/[()<>@,;:\\"/[\]?={}\s]/g, "_").slice(0, 64);
54
+ }
55
+ function buildTrackingHeaders(input) {
56
+ const name = sanitizeUaToken(input.clientName || "unknown");
57
+ const version = sanitizeUaToken(input.clientVersion || "unknown");
58
+ const userAgent = `runpod-mcp-server/${input.serverVersion} (caller=mcp; client=${name}; client_version=${version}; transport=${input.transport})`;
59
+ return {
60
+ "User-Agent": userAgent,
61
+ "X-Runpod-Session-Id": input.sessionId
62
+ };
63
+ }
64
+
65
+ // src/tools/logs.ts
66
+ import { z } from "zod";
67
+ function parseLogSse(raw) {
68
+ const items = [];
69
+ for (const block of raw.split(/\r?\n\r?\n/)) {
70
+ const dataLines = block.split(/\r?\n/).filter((l) => l.startsWith("data:"));
71
+ if (!dataLines.length) continue;
72
+ const payload = dataLines.map((l) => l.slice(5).replace(/^ /, "")).join("\n");
73
+ if (!payload.trim()) continue;
74
+ try {
75
+ const parsed = JSON.parse(payload);
76
+ items.push(
77
+ parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : { raw: payload }
78
+ );
79
+ } catch {
80
+ items.push({ raw: payload });
81
+ }
82
+ }
83
+ return items;
84
+ }
85
+ var LOG_STREAM_DEFAULT_WAIT_MS = 5e3;
86
+ var LOG_STREAM_MAX_BYTES = 256 * 1024;
87
+ async function readSseSnapshot(fetchImpl, url, headers, opts) {
88
+ const controller = new AbortController();
89
+ const timer = setTimeout(() => controller.abort(), opts.maxWaitMs);
90
+ const chunks = [];
91
+ let bytes = 0;
92
+ let truncated = false;
93
+ try {
94
+ const res = await fetchImpl(url, {
95
+ method: "GET",
96
+ headers,
97
+ signal: controller.signal
98
+ });
99
+ if (!res.ok) {
100
+ throw new HttpError(
101
+ "Runpod API Error",
102
+ res.status,
103
+ await res.text().catch(() => "")
104
+ );
105
+ }
106
+ for await (const chunk of res.body ?? []) {
107
+ chunks.push(chunk);
108
+ bytes += chunk.length;
109
+ if (bytes >= opts.maxBytes) {
110
+ truncated = true;
111
+ controller.abort();
112
+ break;
113
+ }
114
+ }
115
+ } catch (err) {
116
+ if (!(err instanceof Error && err.name === "AbortError")) throw err;
117
+ } finally {
118
+ clearTimeout(timer);
119
+ }
120
+ return { raw: Buffer.concat(chunks).toString("utf8"), truncated };
121
+ }
122
+ var logStreamParams = {
123
+ source: z.enum(["container", "system", "both"]).optional().describe("Which log source to read (default: both)"),
124
+ tail: z.number().int().min(0).max(5e3).optional().describe(
125
+ "Historical lines to backfill before live output (API default 100, max 5000; 0 = live only). Ignored when `since` is set."
126
+ ),
127
+ since: z.string().optional().describe("RFC3339 timestamp to resume from; when set, `tail` is ignored."),
128
+ maxWaitMs: z.number().int().min(500).max(3e4).optional().describe("How long to read the stream, in ms (default 5000, max 30000)")
129
+ };
130
+ async function collectLogSnapshot(streamSse, logsUrl, params) {
131
+ const qs = new URLSearchParams();
132
+ if (params.source && params.source !== "both")
133
+ qs.append("source", params.source);
134
+ if (params.tail !== void 0) qs.append("tail", String(params.tail));
135
+ if (params.since) qs.append("since", params.since);
136
+ const query = qs.toString() ? `?${qs}` : "";
137
+ const { raw, truncated } = await streamSse(`${logsUrl}${query}`, {
138
+ maxWaitMs: params.maxWaitMs ?? LOG_STREAM_DEFAULT_WAIT_MS,
139
+ maxBytes: LOG_STREAM_MAX_BYTES
140
+ });
141
+ const items = parseLogSse(raw);
142
+ if (truncated) items.pop();
143
+ return { items, count: items.length, truncated };
144
+ }
145
+ async function streamLogsReply(rt, tool, params) {
146
+ const backend = rt.backendFor(tool.resource);
147
+ if (backend.version === "v1") {
148
+ return rt.jsonReply({
149
+ error: `${tool.name} is only available on the v2 REST API. Set RUNPOD_REST_VERSION=v2.`,
150
+ status: 501
151
+ });
152
+ }
153
+ try {
154
+ return rt.jsonReply(
155
+ await collectLogSnapshot(rt.streamSse, tool.logsUrl(backend), params)
156
+ );
157
+ } catch (error) {
158
+ if (error instanceof HttpError) {
159
+ return rt.jsonReply({ error: error.message, status: error.status });
160
+ }
161
+ throw error;
162
+ }
163
+ }
164
+
165
+ // src/_shared/mappers.ts
166
+ function compact(obj) {
167
+ const out = {};
168
+ for (const [k, v] of Object.entries(obj)) {
169
+ if (v !== void 0) out[k] = v;
170
+ }
171
+ return out;
172
+ }
173
+ function persistentMount(size, path) {
174
+ if (size === void 0 || path === void 0) return void 0;
175
+ return { persistent: { size, path } };
176
+ }
177
+ function joinStartCmd(cmd) {
178
+ return cmd && cmd.length ? cmd.join(" ") : void 0;
179
+ }
180
+ function containerConfigToV2(p) {
181
+ return compact({
182
+ image: p.imageName,
183
+ disk: p.containerDiskInGb,
184
+ ports: p.ports,
185
+ env: p.env,
186
+ mounts: persistentMount(p.volumeInGb, p.volumeMountPath)
187
+ });
188
+ }
189
+ function gpuConfigToV2(gpuTypeIds, gpuCount) {
190
+ const id = gpuTypeIds?.[0];
191
+ if (id === void 0) return void 0;
192
+ return compact({ id, count: gpuCount });
193
+ }
194
+ function mapPodCreateToV2(params) {
195
+ return compact({
196
+ ...containerConfigToV2(params),
197
+ name: params.name,
198
+ // Private-image registry credential (v2 ContainerConfig `registry`). When
199
+ // deploying from a template, this spreads over the template's registry, so
200
+ // passing it overrides the inherited credential. An empty string is an
201
+ // explicit opt-out: emit `registry: null` (v2 accepts null) to CLEAR a
202
+ // template's inherited credential. Undefined is dropped by compact, so an
203
+ // omitted param leaves the template's registry in place.
204
+ registry: params.containerRegistryAuthId === "" ? null : params.containerRegistryAuthId,
205
+ cloud: params.cloudType,
206
+ // v2 CreatePodRequest takes `dataCenterIds` as an ARRAY (preferred data
207
+ // centers; omit/empty = scheduler chooses). Pass the v1 list straight
208
+ // through — the earlier singular `dataCenter` key did not exist on the pod
209
+ // schema, so placement was being silently dropped. GPU, by contrast, IS
210
+ // singular on v2 (`gpu.id`): gpuConfigToV2 takes the first id; the
211
+ // create-pod handler warns when more than one gpuTypeId was supplied.
212
+ dataCenterIds: params.dataCenterIds?.length ? params.dataCenterIds : void 0,
213
+ gpu: gpuConfigToV2(params.gpuTypeIds, params.gpuCount)
214
+ });
215
+ }
216
+ function mapPodUpdateToV2(params) {
217
+ return {
218
+ ...containerConfigToV2(params),
219
+ ...compact({ name: params.name })
220
+ };
221
+ }
222
+ var DEFAULT_ENDPOINT_TYPE = "QUEUE";
223
+ var DEFAULT_SCALER_VALUE = 4;
224
+ function defaultScalerType(endpointType) {
225
+ return endpointType === "LOAD_BALANCER" ? "REQUEST_COUNT" : "QUEUE_DELAY";
226
+ }
227
+ function endpointScaling(scalerType, value) {
228
+ return scalerType === "REQUEST_COUNT" ? { type: "REQUEST_COUNT", requestCount: value } : { type: "QUEUE_DELAY", queueDelay: value };
229
+ }
230
+ function endpointGpuConfig(pools, count) {
231
+ if (!pools?.length) return void 0;
232
+ return compact({ pools, count });
233
+ }
234
+ function endpointWorkers(params) {
235
+ const workers = compact({
236
+ min: params.workersMin,
237
+ max: params.workersMax,
238
+ idleTimeout: params.idleTimeout
239
+ });
240
+ return Object.keys(workers).length ? workers : void 0;
241
+ }
242
+ function endpointCommonToV2(params) {
243
+ return compact({
244
+ name: params.name,
245
+ image: params.imageName,
246
+ args: params.args,
247
+ disk: params.containerDiskInGb,
248
+ ports: params.ports,
249
+ env: params.env,
250
+ registry: params.containerRegistryAuthId,
251
+ gpu: endpointGpuConfig(params.gpuPoolIds, params.gpuCount),
252
+ workers: endpointWorkers(params),
253
+ dataCenterIds: params.dataCenterIds?.length ? params.dataCenterIds : void 0,
254
+ networkVolumes: params.networkVolumeIds?.length ? params.networkVolumeIds : void 0,
255
+ timeout: params.executionTimeoutMs,
256
+ flashboot: params.flashboot
257
+ });
258
+ }
259
+ function mapEndpointCreateToV2(params) {
260
+ const endpointType = params.endpointType ?? DEFAULT_ENDPOINT_TYPE;
261
+ return compact({
262
+ ...endpointCommonToV2(params),
263
+ type: endpointType,
264
+ scaling: endpointScaling(
265
+ params.scalerType ?? defaultScalerType(endpointType),
266
+ params.scalerValue ?? DEFAULT_SCALER_VALUE
267
+ )
268
+ });
269
+ }
270
+ function mapEndpointUpdateToV2(params) {
271
+ return compact({
272
+ ...endpointCommonToV2(params),
273
+ scaling: params.scalerType ? endpointScaling(
274
+ params.scalerType,
275
+ params.scalerValue ?? DEFAULT_SCALER_VALUE
276
+ ) : void 0
277
+ });
278
+ }
279
+ function mapNetworkVolumeCreateToV2(params) {
280
+ return compact({
281
+ name: params.name,
282
+ size: params.size,
283
+ dataCenter: params.dataCenterId,
284
+ type: params.volumeType
285
+ });
286
+ }
287
+ function mapTemplateCreateToV2(params) {
288
+ return {
289
+ ...containerConfigToV2(params),
290
+ ...compact({
291
+ name: params.name,
292
+ serverless: params.isServerless,
293
+ registry: params.containerRegistryAuthId,
294
+ args: joinStartCmd(params.dockerStartCmd),
295
+ // No longer required by v2 (it defaults to NVIDIA server-side), so an
296
+ // unset category is dropped by compact instead of being forced here.
297
+ category: params.category
298
+ })
299
+ };
300
+ }
301
+ function podBodyFromTemplate(template) {
302
+ const out = {};
303
+ const keys = [
304
+ "name",
305
+ "image",
306
+ "args",
307
+ "disk",
308
+ "ports",
309
+ "env",
310
+ "mounts",
311
+ "registry"
312
+ ];
313
+ for (const key of keys) {
314
+ const value = template[key];
315
+ if (value !== void 0 && value !== null) out[key] = value;
316
+ }
317
+ return out;
318
+ }
319
+ function mapTemplateUpdateToV2(params) {
320
+ return {
321
+ ...containerConfigToV2(params),
322
+ ...compact({
323
+ name: params.name,
324
+ registry: params.containerRegistryAuthId,
325
+ args: joinStartCmd(params.dockerStartCmd)
326
+ })
327
+ };
328
+ }
329
+
330
+ // src/_shared/backend.ts
331
+ var V1_ONLY = /* @__PURE__ */ new Set(["jobs"]);
332
+ var V2_UNWRAP_KEY = {
333
+ pods: "pods",
334
+ templates: "templates",
335
+ networkVolumes: "networkVolumes",
336
+ registries: "registries",
337
+ gpus: "gpus",
338
+ cpus: "cpus",
339
+ dataCenters: "dataCenters",
340
+ endpoints: "endpoints",
341
+ jobs: "jobs",
342
+ workers: "workers",
343
+ billing: "records"
344
+ };
345
+ var RESOURCE_ENV_KEY = {
346
+ pods: "PODS",
347
+ templates: "TEMPLATES",
348
+ networkVolumes: "NETWORK_VOLUMES",
349
+ registries: "REGISTRIES",
350
+ gpus: "GPUS",
351
+ cpus: "CPUS",
352
+ dataCenters: "DATA_CENTERS",
353
+ endpoints: "ENDPOINTS",
354
+ jobs: "JOBS",
355
+ workers: "WORKERS",
356
+ billing: "BILLING"
357
+ };
358
+ function restV1Base(env) {
359
+ return env.RUNPOD_REST_API_URL ?? "https://rest.runpod.io/v1";
360
+ }
361
+ function restV2Base(env) {
362
+ return env.RUNPOD_REST_V2_API_URL ?? "https://v2-rest.runpod.io/v2";
363
+ }
364
+ function serverlessBase(env) {
365
+ return env.RUNPOD_SERVERLESS_API_URL ?? "https://api.runpod.ai/v2";
366
+ }
367
+ function publicGraphqlBase(env) {
368
+ return env.RUNPOD_PUBLIC_GRAPHQL_URL ?? "https://api.runpod.io/graphql";
369
+ }
370
+ function authedGraphqlBase(env) {
371
+ return env.RUNPOD_AUTHED_GRAPHQL_URL ?? "https://api.runpod.io/graphql";
372
+ }
373
+ function unwrapList(resource, version, raw) {
374
+ if (version === "v1") return Array.isArray(raw) ? raw : [];
375
+ if (raw === null || typeof raw !== "object") return [];
376
+ const arr = raw[V2_UNWRAP_KEY[resource]];
377
+ return Array.isArray(arr) ? arr : [];
378
+ }
379
+ function resolveVersion(opts) {
380
+ const { resource, env, ctx, v2Available } = opts;
381
+ if (V1_ONLY.has(resource)) return "v1";
382
+ const perResource = env[`RUNPOD_REST_VERSION_${RESOURCE_ENV_KEY[resource]}`];
383
+ const setting = (perResource ?? env.RUNPOD_REST_VERSION ?? "v2").toLowerCase();
384
+ if (setting === "v2") return "v2";
385
+ if (setting === "auto") {
386
+ if (ctx.transport === "http") return "v1";
387
+ return v2Available === true ? "v2" : "v1";
388
+ }
389
+ return "v1";
390
+ }
391
+ function restVersionSummary(env) {
392
+ const raw = (env.RUNPOD_REST_VERSION ?? "").trim().toLowerCase();
393
+ const base = raw ? `RUNPOD_REST_VERSION=${raw}` : "RUNPOD_REST_VERSION unset (default v2)";
394
+ const overrides = Object.keys(env).filter(
395
+ (k) => k.startsWith("RUNPOD_REST_VERSION_") && (env[k] ?? "").trim() !== ""
396
+ ).length;
397
+ return overrides > 0 ? `${base}, +${overrides} per-resource` : base;
398
+ }
399
+ var identity = (body) => body;
400
+ var V1_REST_PATHS = {
401
+ pods: { list: "/pods", get: (id) => `/pods/${id}` },
402
+ templates: { list: "/templates", get: (id) => `/templates/${id}` },
403
+ networkVolumes: {
404
+ list: "/networkvolumes",
405
+ get: (id) => `/networkvolumes/${id}`
406
+ },
407
+ registries: {
408
+ list: "/containerregistryauth",
409
+ get: (id) => `/containerregistryauth/${id}`
410
+ },
411
+ endpoints: { list: "/endpoints", get: (id) => `/endpoints/${id}` }
412
+ };
413
+ var CATALOG = /* @__PURE__ */ new Set([
414
+ "gpus",
415
+ "cpus",
416
+ "dataCenters"
417
+ ]);
418
+ var V2_ONLY = /* @__PURE__ */ new Set([
419
+ "workers",
420
+ "billing"
421
+ ]);
422
+ var V2_REST_PATHS = {
423
+ pods: { list: "/pods", get: (id) => `/pods/${id}` },
424
+ templates: { list: "/templates", get: (id) => `/templates/${id}` },
425
+ networkVolumes: {
426
+ list: "/network-volumes",
427
+ get: (id) => `/network-volumes/${id}`
428
+ },
429
+ registries: { list: "/registries", get: (id) => `/registries/${id}` },
430
+ gpus: { list: "/catalog/gpus", get: (id) => `/catalog/gpus/${id}` },
431
+ cpus: { list: "/catalog/cpus", get: (id) => `/catalog/cpus/${id}` },
432
+ dataCenters: {
433
+ list: "/catalog/datacenters",
434
+ get: (id) => `/catalog/datacenters/${id}`
435
+ },
436
+ // Endpoints live under /v2/serverless on v2 (NOT /v2/endpoints). The v2 list
437
+ // response wraps rows under `endpoints` (see V2_UNWRAP_KEY), so the existing
438
+ // unwrap key stays correct.
439
+ endpoints: { list: "/serverless", get: (id) => `/serverless/${id}` },
440
+ // workers/billing build their own sub-paths in the tool from `base`; the
441
+ // list entry just satisfies buildV2Backend (which requires a paths entry).
442
+ workers: { list: "/serverless" },
443
+ billing: { list: "/billing" }
444
+ };
445
+ var V2_MAPPERS = {
446
+ pods: {
447
+ create: (b) => mapPodCreateToV2(b),
448
+ update: (b) => mapPodUpdateToV2(b)
449
+ },
450
+ templates: {
451
+ create: (b) => mapTemplateCreateToV2(b),
452
+ update: (b) => mapTemplateUpdateToV2(b)
453
+ },
454
+ networkVolumes: {
455
+ create: (b) => mapNetworkVolumeCreateToV2(
456
+ b
457
+ ),
458
+ update: identity
459
+ },
460
+ registries: { create: identity, update: identity },
461
+ endpoints: {
462
+ create: (b) => mapEndpointCreateToV2(b),
463
+ update: (b) => mapEndpointUpdateToV2(b)
464
+ }
465
+ };
466
+ function buildV2Backend(resource, env, unwrap) {
467
+ const paths = V2_REST_PATHS[resource];
468
+ if (!paths) throw new Error(`no v2 REST paths for resource "${resource}"`);
469
+ const mappers = V2_MAPPERS[resource];
470
+ return {
471
+ kind: "rest",
472
+ version: "v2",
473
+ base: restV2Base(env),
474
+ list: paths.list,
475
+ get: paths.get,
476
+ unwrap,
477
+ mapCreate: mappers?.create ?? identity,
478
+ mapUpdate: mappers?.update ?? identity
479
+ };
480
+ }
481
+ function buildV1Backend(resource, env, unwrap) {
482
+ if (resource === "jobs") {
483
+ return {
484
+ kind: "rest",
485
+ version: "v1",
486
+ base: serverlessBase(env),
487
+ unwrap,
488
+ mapCreate: identity,
489
+ mapUpdate: identity
490
+ };
491
+ }
492
+ if (V2_ONLY.has(resource)) {
493
+ return {
494
+ kind: "rest",
495
+ version: "v1",
496
+ base: restV1Base(env),
497
+ unwrap,
498
+ mapCreate: identity,
499
+ mapUpdate: identity
500
+ };
501
+ }
502
+ if (CATALOG.has(resource)) {
503
+ return {
504
+ kind: "graphql",
505
+ version: "v1",
506
+ base: publicGraphqlBase(env),
507
+ unwrap,
508
+ mapCreate: identity,
509
+ mapUpdate: identity
510
+ };
511
+ }
512
+ const paths = V1_REST_PATHS[resource];
513
+ if (!paths) throw new Error(`no v1 REST paths for resource "${resource}"`);
514
+ return {
515
+ kind: "rest",
516
+ version: "v1",
517
+ base: restV1Base(env),
518
+ list: paths.list,
519
+ get: paths.get,
520
+ unwrap,
521
+ mapCreate: identity,
522
+ mapUpdate: identity
523
+ };
524
+ }
525
+ function resolveBackend(opts) {
526
+ const { resource, env } = opts;
527
+ const version = resolveVersion(opts);
528
+ const unwrap = (raw) => unwrapList(resource, version, raw);
529
+ return version === "v2" ? buildV2Backend(resource, env, unwrap) : buildV1Backend(resource, env, unwrap);
530
+ }
531
+
532
+ // src/tools/runtime.ts
533
+ var MCP_SERVER_VERSION = true ? "3.1.0" : "dev";
534
+ var SESSION_ID = randomUUID();
535
+ function trackingHeaders(server, ctx) {
536
+ const info = server.server.getClientVersion();
537
+ return buildTrackingHeaders({
538
+ clientName: info?.name || ctx.clientUserAgent || "unknown",
539
+ clientVersion: info?.version || "unknown",
540
+ transport: ctx.transport,
541
+ // Prefer a server version supplied by the caller (the hosted entrypoint reads
542
+ // it from package.json at runtime, since tsup's build-time define does not
543
+ // run when Vercel compiles api/index.ts). Fall back to the build-time value.
544
+ serverVersion: ctx.serverVersion || MCP_SERVER_VERSION,
545
+ sessionId: SESSION_ID
546
+ });
547
+ }
548
+ var defaultFetch = fetch;
549
+ async function withApiErrorLog(label, call) {
550
+ try {
551
+ return await call();
552
+ } catch (error) {
553
+ console.error(label, error);
554
+ throw error;
555
+ }
556
+ }
557
+ function jsonReply(result) {
558
+ return {
559
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
560
+ };
561
+ }
562
+ var READ_ONLY = { readOnlyHint: true, openWorldHint: true };
563
+ var WRITE = { readOnlyHint: false, openWorldHint: true };
564
+ var DESTRUCTIVE = {
565
+ readOnlyHint: false,
566
+ destructiveHint: true,
567
+ idempotentHint: true,
568
+ openWorldHint: true
569
+ };
570
+ async function graphqlRequest(query, tracking, fetchImpl, url, options) {
571
+ const response = await fetchImpl(url, {
572
+ method: "POST",
573
+ headers: {
574
+ "Content-Type": "application/json",
575
+ ...options?.apiKey ? { Authorization: `Bearer ${options.apiKey}` } : {},
576
+ ...tracking()
577
+ },
578
+ body: JSON.stringify({
579
+ query,
580
+ ...options?.variables ? { variables: options.variables } : {}
581
+ })
582
+ });
583
+ const result = await response.json();
584
+ if (result.errors && result.errors.length > 0) {
585
+ throw new Error(
586
+ `GraphQL Error: ${result.errors.map((e) => e.message).join(", ")}`
587
+ );
588
+ }
589
+ if (!result.data) {
590
+ throw new Error("No data returned from GraphQL query");
591
+ }
592
+ return result.data;
593
+ }
594
+ function createToolRuntime(server, ctx, deps = {}) {
595
+ const tracking = () => trackingHeaders(server, ctx);
596
+ function observeUnauthorized(fn) {
597
+ const notify = ctx.onUnauthorized;
598
+ if (!notify) return fn;
599
+ return async (...args) => {
600
+ const response = await fn(...args);
601
+ if (response.status === 401) notify();
602
+ return response;
603
+ };
604
+ }
605
+ const rawFetch = deps.fetch ?? defaultFetch;
606
+ const httpFetch = observeUnauthorized(rawFetch);
607
+ const v1Client = createHttpClient({
608
+ apiKey: ctx.apiKey,
609
+ fetch: httpFetch,
610
+ tracking,
611
+ errorPrefix: "Runpod API Error"
612
+ });
613
+ const runpodRequest = (endpoint, method = "GET", body) => withApiErrorLog(
614
+ "Error calling Runpod API:",
615
+ () => v1Client(`${restV1Base(process.env)}${endpoint}`, method, body)
616
+ );
617
+ const serverlessClient = createHttpClient({
618
+ apiKey: ctx.apiKey,
619
+ fetch: httpFetch,
620
+ tracking,
621
+ errorPrefix: "Runpod Serverless API Error"
622
+ });
623
+ const serverlessRequest = (endpointId, path, method = "GET", body) => withApiErrorLog(
624
+ "Error calling Runpod Serverless API:",
625
+ () => serverlessClient(
626
+ `${serverlessBase(process.env)}/${endpointId}${path}`,
627
+ method,
628
+ body
629
+ )
630
+ );
631
+ const restClient = createHttpClient({
632
+ apiKey: ctx.apiKey,
633
+ fetch: httpFetch,
634
+ tracking,
635
+ errorPrefix: "Runpod API Error"
636
+ });
637
+ const callRestUrl = (url, method = "GET", body) => withApiErrorLog(
638
+ "Error calling Runpod API:",
639
+ () => restClient(url, method, body)
640
+ );
641
+ const sseFetch = observeUnauthorized(
642
+ deps.sseFetch ?? fetch
643
+ );
644
+ const streamSse = deps.streamSse ?? ((url, opts) => readSseSnapshot(
645
+ sseFetch,
646
+ url,
647
+ {
648
+ Authorization: `Bearer ${ctx.apiKey}`,
649
+ Accept: "text/event-stream",
650
+ ...tracking()
651
+ },
652
+ opts
653
+ ));
654
+ const backendFor = (resource) => resolveBackend({
655
+ resource,
656
+ env: process.env,
657
+ ctx: { transport: ctx.transport },
658
+ v2Available: deps.v2Available
659
+ });
660
+ const podAction = async (podId, action) => {
661
+ const backend = backendFor("pods");
662
+ const podPath = backend.get(podId);
663
+ if (backend.version === "v2") {
664
+ return callRestUrl(`${backend.base}${podPath}/action`, "POST", {
665
+ action
666
+ });
667
+ }
668
+ return callRestUrl(`${backend.base}${podPath}/${action}`, "POST");
669
+ };
670
+ return {
671
+ jsonReply,
672
+ graphql: (query) => graphqlRequest(
673
+ query,
674
+ tracking,
675
+ // rawFetch, not httpFetch: this call carries no credential (see above).
676
+ rawFetch,
677
+ publicGraphqlBase(process.env)
678
+ ),
679
+ graphqlAuthed: (query, variables) => graphqlRequest(
680
+ query,
681
+ tracking,
682
+ httpFetch,
683
+ // NOT publicGraphqlBase: this call carries the caller's API key.
684
+ authedGraphqlBase(process.env),
685
+ { variables, apiKey: ctx.apiKey }
686
+ ),
687
+ runpodRequest,
688
+ serverlessRequest,
689
+ callRestUrl,
690
+ backendFor,
691
+ streamSse,
692
+ podAction,
693
+ env: process.env
694
+ };
695
+ }
696
+
697
+ // src/tools/catalog.ts
698
+ import { z as z3 } from "zod";
699
+
700
+ // src/pagination.ts
701
+ import { z as z2 } from "zod";
702
+ var DEFAULT_LIST_LIMIT = 20;
703
+ var MAX_LIST_LIMIT = 100;
704
+ var listPaginationParams = {
705
+ limit: z2.number().int().positive().max(MAX_LIST_LIMIT).optional().describe(
706
+ `Maximum number of items to return (default ${DEFAULT_LIST_LIMIT}, max ${MAX_LIST_LIMIT}). Use the returned nextCursor to fetch the next page.`
707
+ ),
708
+ cursor: z2.string().optional().describe(
709
+ "Opaque pagination cursor from a previous response (nextCursor). Omit to start from the beginning."
710
+ )
711
+ };
712
+ function decodeCursorOffset(cursor) {
713
+ if (!cursor) return 0;
714
+ try {
715
+ const decoded = Buffer.from(cursor, "base64").toString("utf8");
716
+ const offset = Number.parseInt(decoded, 10);
717
+ return Number.isFinite(offset) && offset >= 0 ? offset : 0;
718
+ } catch {
719
+ return 0;
720
+ }
721
+ }
722
+ function encodeCursorOffset(offset) {
723
+ return Buffer.from(String(offset), "utf8").toString("base64");
724
+ }
725
+ function capListResult(result, options, extra) {
726
+ const limit = Math.min(options.limit ?? DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT);
727
+ const offset = decodeCursorOffset(options.cursor);
728
+ if (!Array.isArray(result)) {
729
+ return {
730
+ content: [
731
+ { type: "text", text: JSON.stringify(result, null, 2) }
732
+ ]
733
+ };
734
+ }
735
+ const total = result.length;
736
+ const page = result.slice(offset, offset + limit);
737
+ const nextOffset = offset + page.length;
738
+ const hasMore = nextOffset < total;
739
+ const { items: _i, pagination: _p, ...safeExtra } = extra ?? {};
740
+ void _i;
741
+ void _p;
742
+ const envelope = {
743
+ ...safeExtra,
744
+ items: page,
745
+ pagination: {
746
+ total,
747
+ returned: page.length,
748
+ offset,
749
+ truncated: hasMore,
750
+ nextCursor: hasMore ? encodeCursorOffset(nextOffset) : null,
751
+ note: hasMore ? `Showing ${page.length} of ${total}. Pass cursor=nextCursor to fetch more, or narrow the query with filters.` : void 0
752
+ }
753
+ };
754
+ return {
755
+ content: [
756
+ { type: "text", text: JSON.stringify(envelope, null, 2) }
757
+ ]
758
+ };
759
+ }
760
+
761
+ // src/tools/catalog.ts
762
+ function registerCatalogTools(server, rt) {
763
+ const { jsonReply: jsonReply2, graphql, callRestUrl, backendFor } = rt;
764
+ server.tool(
765
+ "list-gpu-types",
766
+ "List available GPU types with stock/pricing and capability filters (minimum VRAM, secure/community cloud, name search). Use this to discover valid gpuTypeIds before creating a pod or endpoint. By default the full catalog is returned: each result includes an `availability` summary (HIGH/MEDIUM/LOW/NONE) and results are sorted with the most-available GPUs first, but nothing is hidden. Set includeUnavailable:false to drop out-of-stock GPUs and list only deployable ones (set includeAvailability:false to skip the stock lookup entirely). For per-datacenter availability (to pick a dataCenterIds), use get-gpu-type.",
767
+ {
768
+ ...listPaginationParams,
769
+ minMemoryGb: z3.number().optional().describe("Filter to GPUs with at least this much VRAM in GB"),
770
+ secureCloudOnly: z3.boolean().optional().describe("Filter to only GPUs available in secure cloud"),
771
+ communityCloudOnly: z3.boolean().optional().describe("Filter to only GPUs available in community cloud"),
772
+ searchTerm: z3.string().optional().describe(
773
+ "Search term to filter GPUs by name (e.g., 'A100', 'RTX 4090')"
774
+ ),
775
+ includeUnavailable: z3.boolean().optional().describe(
776
+ "Out-of-stock GPUs are included by default (annotated availability:NONE and sorted last). Set false to hide them and list only currently-deployable GPUs."
777
+ ),
778
+ includeAvailability: z3.boolean().optional().describe(
779
+ "Request realtime stock and annotate each GPU with an availability summary (HIGH/MEDIUM/LOW/NONE). Default true. Set false to skip the availability lookup \u2014 then out-of-stock GPUs cannot be filtered."
780
+ )
781
+ },
782
+ { title: "List GPU types", ...READ_ONLY },
783
+ async (params) => {
784
+ const backend = backendFor("gpus");
785
+ if (backend.version === "v2") {
786
+ const wantAvailability = params.includeAvailability !== false;
787
+ const raw = await callRestUrl(
788
+ `${backend.base}${backend.list}${wantAvailability ? "?include=AVAILABILITY" : ""}`
789
+ );
790
+ let gpus = backend.unwrap(raw);
791
+ gpus = gpus.filter((g) => g.id !== "unknown");
792
+ if (params.minMemoryGb !== void 0)
793
+ gpus = gpus.filter(
794
+ (g) => Number(g.memory ?? 0) >= params.minMemoryGb
795
+ );
796
+ if (params.secureCloudOnly) gpus = gpus.filter((g) => g.secure);
797
+ if (params.communityCloudOnly) gpus = gpus.filter((g) => g.community);
798
+ if (params.searchTerm) {
799
+ const t = params.searchTerm.toLowerCase();
800
+ gpus = gpus.filter(
801
+ (g) => String(g.id ?? "").toLowerCase().includes(t) || String(g.name ?? "").toLowerCase().includes(t)
802
+ );
803
+ }
804
+ if (params.includeUnavailable === false)
805
+ gpus = gpus.filter((g) => g.availability !== "NONE");
806
+ const rank = {
807
+ HIGH: 3,
808
+ MEDIUM: 2,
809
+ LOW: 1,
810
+ NONE: 0
811
+ };
812
+ gpus.sort(
813
+ (a, b) => (rank[String(b.availability)] ?? 0) - (rank[String(a.availability)] ?? 0)
814
+ );
815
+ gpus = gpus.map(({ dataCenters: _dataCenters, ...rest }) => rest);
816
+ return capListResult(gpus, {
817
+ limit: params.limit,
818
+ cursor: params.cursor
819
+ });
820
+ }
821
+ const data = await graphql(`
822
+ query {
823
+ gpuTypes {
824
+ id
825
+ displayName
826
+ memoryInGb
827
+ secureCloud
828
+ communityCloud
829
+ lowestPrice(input: { gpuCount: 1 }) {
830
+ stockStatus
831
+ }
832
+ }
833
+ }
834
+ `);
835
+ const stockPriority = {
836
+ High: 3,
837
+ Medium: 2,
838
+ Low: 1
839
+ };
840
+ const isAvailable = (gpu) => {
841
+ const status = gpu.lowestPrice?.stockStatus;
842
+ return !!status && status !== "Out";
843
+ };
844
+ let gpuTypes = data.gpuTypes.filter((gpu) => gpu.id !== "unknown");
845
+ if (params.includeUnavailable === false) {
846
+ gpuTypes = gpuTypes.filter(isAvailable);
847
+ }
848
+ if (params.minMemoryGb) {
849
+ gpuTypes = gpuTypes.filter(
850
+ (gpu) => gpu.memoryInGb >= params.minMemoryGb
851
+ );
852
+ }
853
+ if (params.secureCloudOnly) {
854
+ gpuTypes = gpuTypes.filter((gpu) => gpu.secureCloud);
855
+ }
856
+ if (params.communityCloudOnly) {
857
+ gpuTypes = gpuTypes.filter((gpu) => gpu.communityCloud);
858
+ }
859
+ if (params.searchTerm) {
860
+ const term = params.searchTerm.toLowerCase();
861
+ gpuTypes = gpuTypes.filter(
862
+ (gpu) => gpu.id.toLowerCase().includes(term) || gpu.displayName.toLowerCase().includes(term)
863
+ );
864
+ }
865
+ gpuTypes.sort((a, b) => {
866
+ const aP = stockPriority[a.lowestPrice?.stockStatus || ""] || 0;
867
+ const bP = stockPriority[b.lowestPrice?.stockStatus || ""] || 0;
868
+ if (bP !== aP) return bP - aP;
869
+ return b.memoryInGb - a.memoryInGb;
870
+ });
871
+ const result = gpuTypes.map((gpu) => ({
872
+ id: gpu.id,
873
+ displayName: gpu.displayName,
874
+ memoryGb: gpu.memoryInGb,
875
+ secureCloud: gpu.secureCloud,
876
+ communityCloud: gpu.communityCloud,
877
+ stockStatus: gpu.lowestPrice?.stockStatus || "unavailable",
878
+ available: isAvailable(gpu)
879
+ }));
880
+ return capListResult(result, {
881
+ limit: params.limit,
882
+ cursor: params.cursor
883
+ });
884
+ }
885
+ );
886
+ server.tool(
887
+ "list-data-centers",
888
+ "List Runpod data centers (id, name, region/location). Use this to discover valid dataCenterIds for placing pods, endpoints, or network volumes.",
889
+ {
890
+ ...listPaginationParams,
891
+ region: z3.string().optional().describe(
892
+ "Filter by region/location (e.g., 'United States', 'Europe', 'Canada')"
893
+ )
894
+ },
895
+ { title: "List data centers", ...READ_ONLY },
896
+ async (params) => {
897
+ const backend = backendFor("dataCenters");
898
+ if (backend.version === "v2") {
899
+ const raw = await callRestUrl(`${backend.base}${backend.list}`);
900
+ let dcs = backend.unwrap(raw);
901
+ if (params.region) {
902
+ const t = params.region.toLowerCase();
903
+ dcs = dcs.filter(
904
+ (dc) => String(dc.region ?? "").toLowerCase().includes(t)
905
+ );
906
+ }
907
+ return capListResult(dcs, {
908
+ limit: params.limit,
909
+ cursor: params.cursor
910
+ });
911
+ }
912
+ const data = await graphql(`
913
+ query {
914
+ dataCenters {
915
+ id
916
+ name
917
+ location
918
+ }
919
+ }
920
+ `);
921
+ let dataCenters = data.dataCenters;
922
+ if (params.region) {
923
+ const term = params.region.toLowerCase();
924
+ dataCenters = dataCenters.filter(
925
+ (dc) => dc.location.toLowerCase().includes(term)
926
+ );
927
+ }
928
+ return capListResult(dataCenters, {
929
+ limit: params.limit,
930
+ cursor: params.cursor
931
+ });
932
+ }
933
+ );
934
+ server.tool(
935
+ "list-cpu-types",
936
+ "List available CPU flavor types for CPU pods/endpoints. v2-only \u2014 returns a 501 notice on the v1 API.",
937
+ { ...listPaginationParams },
938
+ { title: "List CPU types", ...READ_ONLY },
939
+ async (params) => {
940
+ const backend = backendFor("cpus");
941
+ if (backend.version === "v1") {
942
+ return jsonReply2({
943
+ error: "list-cpu-types is only available on the v2 REST API. Set RUNPOD_REST_VERSION=v2.",
944
+ status: 501
945
+ });
946
+ }
947
+ const raw = await callRestUrl(`${backend.base}${backend.list}`);
948
+ return capListResult(backend.unwrap(raw), {
949
+ limit: params.limit,
950
+ cursor: params.cursor
951
+ });
952
+ }
953
+ );
954
+ server.tool(
955
+ "get-gpu-type",
956
+ "Get details for a single GPU type by id, including per-datacenter availability. v2-only \u2014 returns a 501 notice on the v1 API (use list-gpu-types there). Use the returned dataCenters[].availability to pick a dataCenterIds with stock before creating a pod.",
957
+ {
958
+ gpuTypeId: z3.string().describe("ID of the GPU type to retrieve"),
959
+ includeAvailability: z3.boolean().optional().describe(
960
+ "Include realtime per-datacenter availability (HIGH/MEDIUM/LOW/NONE). Default true."
961
+ )
962
+ },
963
+ { title: "Get GPU type", ...READ_ONLY },
964
+ async (params) => {
965
+ const backend = backendFor("gpus");
966
+ if (backend.version === "v1") {
967
+ return jsonReply2({
968
+ error: "get-gpu-type is only available on the v2 REST API. Set RUNPOD_REST_VERSION=v2 (or use list-gpu-types on v1).",
969
+ status: 501
970
+ });
971
+ }
972
+ const path = backend.get(encodeURIComponent(params.gpuTypeId));
973
+ const query = params.includeAvailability === false ? "" : "?include=AVAILABILITY";
974
+ const result = await callRestUrl(`${backend.base}${path}${query}`);
975
+ return jsonReply2(result);
976
+ }
977
+ );
978
+ server.tool(
979
+ "get-cpu-type",
980
+ "Get details for a single CPU flavor type by id. v2-only \u2014 returns a 501 notice on the v1 API (use list-cpu-types there).",
981
+ {
982
+ cpuTypeId: z3.string().describe("ID of the CPU type to retrieve")
983
+ },
984
+ { title: "Get CPU type", ...READ_ONLY },
985
+ async (params) => {
986
+ const backend = backendFor("cpus");
987
+ if (backend.version === "v1") {
988
+ return jsonReply2({
989
+ error: "get-cpu-type is only available on the v2 REST API. Set RUNPOD_REST_VERSION=v2.",
990
+ status: 501
991
+ });
992
+ }
993
+ const result = await callRestUrl(
994
+ `${backend.base}${backend.get(params.cpuTypeId)}`
995
+ );
996
+ return jsonReply2(result);
997
+ }
998
+ );
999
+ server.tool(
1000
+ "get-data-center",
1001
+ "Get details for a single data center by id. v2-only \u2014 returns a 501 notice on the v1 API (use list-data-centers there).",
1002
+ {
1003
+ dataCenterId: z3.string().describe("ID of the data center to retrieve")
1004
+ },
1005
+ { title: "Get data center", ...READ_ONLY },
1006
+ async (params) => {
1007
+ const backend = backendFor("dataCenters");
1008
+ if (backend.version === "v1") {
1009
+ return jsonReply2({
1010
+ error: "get-data-center is only available on the v2 REST API. Set RUNPOD_REST_VERSION=v2.",
1011
+ status: 501
1012
+ });
1013
+ }
1014
+ const result = await callRestUrl(
1015
+ `${backend.base}${backend.get(params.dataCenterId)}`
1016
+ );
1017
+ return jsonReply2(result);
1018
+ }
1019
+ );
1020
+ }
1021
+
1022
+ // src/tools/hub.ts
1023
+ import { z as z4 } from "zod";
1024
+ function parseReleaseConfig(config) {
1025
+ if (!config) return void 0;
1026
+ try {
1027
+ return JSON.parse(config);
1028
+ } catch {
1029
+ return config;
1030
+ }
1031
+ }
1032
+ function listingsQuery(withConfig) {
1033
+ return `
1034
+ query {
1035
+ listings(input: {}) {
1036
+ id
1037
+ repoId
1038
+ title
1039
+ description
1040
+ repoName
1041
+ repoOwner
1042
+ createdAt
1043
+ updatedAt
1044
+ views
1045
+ stars
1046
+ deploys
1047
+ language
1048
+ category
1049
+ tags
1050
+ type
1051
+ listedRelease {
1052
+ id
1053
+ name
1054
+ tagName
1055
+ createdAt${withConfig ? "\n config" : ""}
1056
+ build {
1057
+ id
1058
+ imageName
1059
+ }
1060
+ }
1061
+ }
1062
+ }
1063
+ `;
1064
+ }
1065
+ function serializeBoolean(value, input) {
1066
+ if (value === "true") return input.trueValue ?? "true";
1067
+ if (value === "false") return input.falseValue ?? "false";
1068
+ return value;
1069
+ }
1070
+ function buildHubEnv(config, overrides) {
1071
+ const env = [];
1072
+ const missingRequired = [];
1073
+ const remaining = { ...overrides };
1074
+ for (const entry of config.env ?? []) {
1075
+ const input = entry.input ?? {};
1076
+ const override = entry.key in remaining ? remaining[entry.key] : void 0;
1077
+ delete remaining[entry.key];
1078
+ if (override !== void 0 && override !== "") {
1079
+ env.push({
1080
+ key: entry.key,
1081
+ value: input.type === "boolean" ? serializeBoolean(override, input) : override
1082
+ });
1083
+ continue;
1084
+ }
1085
+ if (input.default !== void 0 && input.default !== null) {
1086
+ env.push({
1087
+ key: entry.key,
1088
+ value: typeof input.default === "boolean" ? input.default ? input.trueValue ?? "true" : input.falseValue ?? "false" : String(input.default)
1089
+ });
1090
+ continue;
1091
+ }
1092
+ if (input.required) {
1093
+ missingRequired.push(entry.key);
1094
+ env.push({ key: entry.key, value: "" });
1095
+ continue;
1096
+ }
1097
+ }
1098
+ for (const [key, value] of Object.entries(remaining)) {
1099
+ env.push({ key, value });
1100
+ }
1101
+ return { env, missingRequired };
1102
+ }
1103
+ function minCudaVersion(versions) {
1104
+ if (!versions || versions.length === 0) return null;
1105
+ const compare = (a, b) => {
1106
+ const pa = a.split(".").map(Number);
1107
+ const pb = b.split(".").map(Number);
1108
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
1109
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
1110
+ if (d !== 0) return d;
1111
+ }
1112
+ return 0;
1113
+ };
1114
+ return [...versions].sort(compare)[0];
1115
+ }
1116
+ function randomSuffix() {
1117
+ return Math.random().toString(36).slice(2, 8);
1118
+ }
1119
+ function registerHubTools(server, rt) {
1120
+ const { graphql, graphqlAuthed, jsonReply: jsonReply2 } = rt;
1121
+ server.tool(
1122
+ "list-hub-repos",
1123
+ "List repos published to the Runpod Hub (prebuilt Serverless workers and Pod templates, e.g. vLLM, ComfyUI). Public catalog \u2014 no auth required. Each result includes the currently listed release with its hubReleaseId and prebuilt image name. Results are sorted by deploy count (most popular first). Set includeConfig:true to also return the release config (hardware requirements and environment-variable schema) \u2014 it is large, so prefer requesting it for a single repo via the repoOwner/searchTerm filters.",
1124
+ {
1125
+ ...listPaginationParams,
1126
+ searchTerm: z4.string().optional().describe(
1127
+ "Case-insensitive search across title, description, repo name, owner, and tags (e.g. 'vllm', 'comfyui', 'fine-tuning')"
1128
+ ),
1129
+ category: z4.string().optional().describe(
1130
+ "Filter by category (e.g. 'language', 'image', 'audio', 'video', 'embedding')"
1131
+ ),
1132
+ type: z4.enum(["SERVERLESS", "POD"]).optional().describe(
1133
+ "Filter by listing type: SERVERLESS (endpoint workers) or POD (pod templates)"
1134
+ ),
1135
+ repoOwner: z4.string().optional().describe(
1136
+ "Filter to listings from this GitHub owner/org (e.g. 'runpod-workers', 'axolotl-ai-cloud')"
1137
+ ),
1138
+ includeConfig: z4.boolean().optional().describe(
1139
+ "Include the listed release config (hardware requirements + env-var input schema, parsed from .runpod/hub.json). Large \u2014 off by default."
1140
+ )
1141
+ },
1142
+ { title: "List Hub repos", ...READ_ONLY },
1143
+ async (params) => {
1144
+ const data = await graphql(
1145
+ listingsQuery(params.includeConfig === true)
1146
+ );
1147
+ let listings = data.listings;
1148
+ if (params.type) {
1149
+ listings = listings.filter(
1150
+ (l) => (l.type ?? "").toUpperCase() === params.type
1151
+ );
1152
+ }
1153
+ if (params.category) {
1154
+ const term = params.category.toLowerCase();
1155
+ listings = listings.filter(
1156
+ (l) => (l.category ?? "").toLowerCase() === term
1157
+ );
1158
+ }
1159
+ if (params.repoOwner) {
1160
+ const term = params.repoOwner.toLowerCase();
1161
+ listings = listings.filter(
1162
+ (l) => (l.repoOwner ?? "").toLowerCase() === term
1163
+ );
1164
+ }
1165
+ if (params.searchTerm) {
1166
+ const term = params.searchTerm.toLowerCase();
1167
+ listings = listings.filter(
1168
+ (l) => [
1169
+ l.title,
1170
+ l.description,
1171
+ l.repoName,
1172
+ l.repoOwner,
1173
+ ...l.tags ?? []
1174
+ ].some((field) => (field ?? "").toLowerCase().includes(term))
1175
+ );
1176
+ }
1177
+ listings = [...listings].sort(
1178
+ (a, b) => (b.deploys ?? 0) - (a.deploys ?? 0) || a.id.localeCompare(b.id)
1179
+ );
1180
+ const result = listings.map((l) => ({
1181
+ id: l.id,
1182
+ repo: `${l.repoOwner}/${l.repoName}`,
1183
+ title: l.title,
1184
+ description: l.description,
1185
+ type: l.type,
1186
+ category: l.category,
1187
+ tags: l.tags,
1188
+ language: l.language,
1189
+ stars: l.stars,
1190
+ deploys: l.deploys,
1191
+ views: l.views,
1192
+ githubUrl: `https://github.com/${l.repoOwner}/${l.repoName}`,
1193
+ hubUrl: `https://console.runpod.io/hub/${l.repoOwner}/${l.repoName}`,
1194
+ createdAt: l.createdAt,
1195
+ updatedAt: l.updatedAt,
1196
+ listedRelease: l.listedRelease ? {
1197
+ hubReleaseId: l.listedRelease.id,
1198
+ name: l.listedRelease.name,
1199
+ tagName: l.listedRelease.tagName,
1200
+ createdAt: l.listedRelease.createdAt,
1201
+ imageName: l.listedRelease.build?.imageName,
1202
+ ...params.includeConfig ? { config: parseReleaseConfig(l.listedRelease.config) } : {}
1203
+ } : null
1204
+ }));
1205
+ return capListResult(result, {
1206
+ limit: params.limit,
1207
+ cursor: params.cursor
1208
+ });
1209
+ }
1210
+ );
1211
+ server.tool(
1212
+ "deploy-hub-repo",
1213
+ "Deploy a Runpod Hub repo's listed release as a new Serverless endpoint (the same as clicking Deploy on the Hub). Identify the repo by `repo` (\"owner/name\" from list-hub-repos) or by `hubReleaseId`. The release supplies the prebuilt image, container disk, CUDA constraints, and env-var defaults; pass `env` to override or fill in values (required keys without a default must be provided \u2014 check list-hub-repos with includeConfig:true for the schema). GPU selection comes from the release config when it specifies one; otherwise pass gpuIds (GPU pool names, e.g. 'ADA_24' or 'ADA_80_PRO,AMPERE_80'). Uses the authenticated GraphQL API (no REST home for Hub deploys yet), so it works the same on v1 and v2.",
1214
+ {
1215
+ repo: z4.string().optional().describe(
1216
+ `The Hub repo to deploy as "owner/name" (e.g. 'runpod-workers/worker-comfyui'). Deploys its currently listed release. Provide this or hubReleaseId.`
1217
+ ),
1218
+ hubReleaseId: z4.string().optional().describe(
1219
+ "The Hub release ID to deploy (from list-hub-repos listedRelease.hubReleaseId). Provide this or repo."
1220
+ ),
1221
+ name: z4.string().optional().describe(
1222
+ "Name for the new endpoint. Defaults to '<listing title> <release tag>'."
1223
+ ),
1224
+ env: z4.record(z4.string()).optional().describe(
1225
+ "Environment variable overrides, merged over the release config defaults. Keys not in the release schema are passed through as-is."
1226
+ ),
1227
+ gpuIds: z4.string().optional().describe(
1228
+ "Comma-separated GPU pool names for workers (e.g. 'ADA_24' or 'ADA_80_PRO,AMPERE_80'). To pin specific GPU SKUs within a pool, append exclusions prefixed with '-' using GPU type ids from list-gpu-types (e.g. 'AMPERE_16,-NVIDIA RTX 2000 Ada Generation,-NVIDIA RTX A4500' allows only the pool's remaining SKUs). Defaults to the release config's gpuIds; required when the config does not specify one."
1229
+ ),
1230
+ gpuCount: z4.number().int().positive().optional().describe("GPUs per worker. Defaults to the release config (or 1)."),
1231
+ containerDiskInGb: z4.number().int().positive().optional().describe("Container disk size in GB. Defaults to the release config."),
1232
+ workersMin: z4.number().int().min(0).optional().describe("Minimum workers (default 0 \u2014 scale to zero)."),
1233
+ workersMax: z4.number().int().positive().optional().describe("Maximum workers (default: account default)."),
1234
+ idleTimeout: z4.number().int().positive().optional().describe("Seconds a worker idles before scaling down (default 5)."),
1235
+ scalerType: z4.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe("Autoscaler type (default QUEUE_DELAY)."),
1236
+ scalerValue: z4.number().optional().describe("Autoscaler target value (default 4)."),
1237
+ executionTimeoutMs: z4.number().int().positive().optional().describe("Per-job execution timeout in ms (default 600000)."),
1238
+ flashboot: z4.enum(["OFF", "FLASHBOOT", "PRIORITY_FLASHBOOT"]).optional().describe("FlashBoot mode (default FLASHBOOT).")
1239
+ },
1240
+ { title: "Deploy Hub repo", ...WRITE },
1241
+ async (params) => {
1242
+ if (!params.repo && !params.hubReleaseId) {
1243
+ return jsonReply2({
1244
+ error: 'Provide either repo ("owner/name") or hubReleaseId. Use list-hub-repos to discover both.'
1245
+ });
1246
+ }
1247
+ const catalog = await graphql(listingsQuery(true));
1248
+ let listing;
1249
+ if (params.hubReleaseId) {
1250
+ listing = catalog.listings.find(
1251
+ (l) => l.listedRelease?.id === params.hubReleaseId
1252
+ );
1253
+ } else {
1254
+ const repoKey = params.repo.toLowerCase();
1255
+ listing = catalog.listings.find(
1256
+ (l) => `${l.repoOwner}/${l.repoName}`.toLowerCase() === repoKey
1257
+ );
1258
+ }
1259
+ if (!listing) {
1260
+ return jsonReply2({
1261
+ error: `No Hub listing found for ${params.hubReleaseId ? `hubReleaseId "${params.hubReleaseId}" (only each repo's currently listed release is deployable)` : `repo "${params.repo}"`}. Use list-hub-repos to see the catalog.`
1262
+ });
1263
+ }
1264
+ const release = listing.listedRelease;
1265
+ if (!release?.build?.imageName) {
1266
+ return jsonReply2({
1267
+ error: `Hub repo ${listing.repoOwner}/${listing.repoName} has no listed release with a built image, so it cannot be deployed.`
1268
+ });
1269
+ }
1270
+ if ((listing.type ?? "").toUpperCase() !== "SERVERLESS") {
1271
+ return jsonReply2({
1272
+ error: `Hub repo ${listing.repoOwner}/${listing.repoName} is a ${listing.type} listing \u2014 only SERVERLESS listings deploy as endpoints.`
1273
+ });
1274
+ }
1275
+ const config = parseReleaseConfig(release.config) ?? {};
1276
+ const gpuIds = params.gpuIds ?? config.gpuIds;
1277
+ if (!gpuIds) {
1278
+ return jsonReply2({
1279
+ error: 'This release does not specify a GPU pool \u2014 pass gpuIds (comma-separated pool names, e.g. "ADA_80_PRO,AMPERE_80"; see the pool field on list-gpu-types).'
1280
+ });
1281
+ }
1282
+ const { env, missingRequired } = buildHubEnv(config, params.env ?? {});
1283
+ if (missingRequired.length > 0) {
1284
+ return jsonReply2({
1285
+ error: `Missing required environment variables for this release: ${missingRequired.join(
1286
+ ", "
1287
+ )}. Pass them via the env parameter.`
1288
+ });
1289
+ }
1290
+ const endpointName = params.name ?? `${listing.title} ${release.tagName}`;
1291
+ const minCuda = minCudaVersion(config.allowedCudaVersions);
1292
+ const input = {
1293
+ name: endpointName,
1294
+ hubReleaseId: release.id,
1295
+ type: "QB",
1296
+ gpuIds,
1297
+ gpuCount: params.gpuCount ?? config.gpuCount ?? 1,
1298
+ workersMin: params.workersMin ?? 0,
1299
+ workersMax: params.workersMax ?? null,
1300
+ idleTimeout: params.idleTimeout ?? 5,
1301
+ scalerType: params.scalerType ?? "QUEUE_DELAY",
1302
+ scalerValue: params.scalerValue ?? 4,
1303
+ executionTimeoutMs: params.executionTimeoutMs ?? 6e5,
1304
+ flashBootType: params.flashboot ?? "FLASHBOOT",
1305
+ locations: null,
1306
+ networkVolumeIds: null,
1307
+ compliance: [],
1308
+ modelReferences: [],
1309
+ ...minCuda ? {
1310
+ minCudaVersion: minCuda,
1311
+ allowedCudaVersions: config.allowedCudaVersions.join(",")
1312
+ } : {},
1313
+ template: {
1314
+ name: `${endpointName}__template__${randomSuffix()}`,
1315
+ imageName: release.build.imageName,
1316
+ containerDiskInGb: params.containerDiskInGb ?? config.containerDiskInGb ?? 20,
1317
+ containerRegistryAuthId: "",
1318
+ dockerArgs: "",
1319
+ startScript: "",
1320
+ ports: "",
1321
+ env
1322
+ }
1323
+ };
1324
+ const data = await graphqlAuthed(
1325
+ `
1326
+ mutation saveEndpoint($input: EndpointInput!) {
1327
+ saveEndpoint(input: $input) {
1328
+ id
1329
+ name
1330
+ gpuIds
1331
+ gpuCount
1332
+ workersMin
1333
+ workersMax
1334
+ idleTimeout
1335
+ scalerType
1336
+ scalerValue
1337
+ flashBootType
1338
+ templateId
1339
+ }
1340
+ }
1341
+ `,
1342
+ { input }
1343
+ );
1344
+ return jsonReply2({
1345
+ endpoint: data.saveEndpoint,
1346
+ deployed: {
1347
+ repo: `${listing.repoOwner}/${listing.repoName}`,
1348
+ release: release.tagName,
1349
+ hubReleaseId: release.id,
1350
+ imageName: release.build.imageName
1351
+ },
1352
+ note: `Endpoint created. Submit jobs with run-endpoint/runsync-endpoint using endpointId "${data.saveEndpoint.id}".`
1353
+ });
1354
+ }
1355
+ );
1356
+ }
1357
+
1358
+ // src/tools/public-endpoints.ts
1359
+ import { z as z5 } from "zod";
1360
+ function parseMetadata(metadata) {
1361
+ if (!metadata) return {};
1362
+ try {
1363
+ const parsed = JSON.parse(metadata);
1364
+ return parsed && typeof parsed === "object" ? parsed : {};
1365
+ } catch {
1366
+ return {};
1367
+ }
1368
+ }
1369
+ function registerPublicEndpointTools(server, rt) {
1370
+ const { graphql } = rt;
1371
+ server.tool(
1372
+ "list-public-endpoints",
1373
+ "List Runpod Public Endpoints \u2014 managed, pay-per-use model APIs (text, image, video, audio) that require no deployment. Public catalog, no auth required. Each result includes the endpointId to call with run-endpoint/runsync-endpoint (or via https://api.runpod.ai/v2/{endpointId}), the model name, modality, owner, and pricing. Only live endpoints are returned by default; set includeOffline:true to also list ones that are not currently live.",
1374
+ {
1375
+ ...listPaginationParams,
1376
+ searchTerm: z5.string().optional().describe(
1377
+ "Case-insensitive search across display name, model name, endpoint id, description, owner, and tag (e.g. 'kimi', 'video', 'flux')"
1378
+ ),
1379
+ modality: z5.string().optional().describe(
1380
+ "Filter by modality/category (the metadata source field, e.g. 'language', 'image', 'video', 'audio')"
1381
+ ),
1382
+ owner: z5.string().optional().describe(
1383
+ "Filter by model owner (e.g. 'moonshot', 'minimax', 'google')"
1384
+ ),
1385
+ includeOffline: z5.boolean().optional().describe(
1386
+ "Include endpoints that are not currently live (isLive:false). Default false \u2014 only live endpoints are listed."
1387
+ )
1388
+ },
1389
+ { title: "List public endpoints", ...READ_ONLY },
1390
+ async (params) => {
1391
+ const data = await graphql(`
1392
+ query {
1393
+ allAiApiPublicConfigs {
1394
+ id
1395
+ aiApiId
1396
+ modelName
1397
+ displayName
1398
+ description
1399
+ metadata
1400
+ isLive
1401
+ createdAt
1402
+ updatedAt
1403
+ }
1404
+ }
1405
+ `);
1406
+ let configs = data.allAiApiPublicConfigs.map((c) => ({
1407
+ config: c,
1408
+ meta: parseMetadata(c.metadata)
1409
+ }));
1410
+ if (!params.includeOffline) {
1411
+ configs = configs.filter(({ config }) => config.isLive);
1412
+ }
1413
+ if (params.modality) {
1414
+ const term = params.modality.toLowerCase();
1415
+ configs = configs.filter(
1416
+ ({ meta }) => (meta.source ?? "").toLowerCase() === term
1417
+ );
1418
+ }
1419
+ if (params.owner) {
1420
+ const term = params.owner.toLowerCase();
1421
+ configs = configs.filter(
1422
+ ({ meta }) => (meta.owner ?? "").toLowerCase() === term
1423
+ );
1424
+ }
1425
+ if (params.searchTerm) {
1426
+ const term = params.searchTerm.toLowerCase();
1427
+ configs = configs.filter(
1428
+ ({ config, meta }) => [
1429
+ config.displayName,
1430
+ config.modelName,
1431
+ config.aiApiId,
1432
+ config.description,
1433
+ meta.owner,
1434
+ meta.tag,
1435
+ meta.source
1436
+ ].some((field) => (field ?? "").toLowerCase().includes(term))
1437
+ );
1438
+ }
1439
+ configs = [...configs].sort(
1440
+ (a, b) => a.config.displayName.localeCompare(b.config.displayName)
1441
+ );
1442
+ const result = configs.map(({ config, meta }) => ({
1443
+ endpointId: config.aiApiId,
1444
+ displayName: config.displayName,
1445
+ modelName: config.modelName,
1446
+ description: config.description,
1447
+ modality: meta.source,
1448
+ tag: meta.tag,
1449
+ owner: meta.owner,
1450
+ pricing: meta.priceString,
1451
+ isLive: config.isLive,
1452
+ baseUrl: `https://api.runpod.ai/v2/${config.aiApiId}`,
1453
+ createdAt: config.createdAt,
1454
+ updatedAt: config.updatedAt
1455
+ }));
1456
+ return capListResult(result, {
1457
+ limit: params.limit,
1458
+ cursor: params.cursor
1459
+ });
1460
+ }
1461
+ );
1462
+ }
1463
+
1464
+ // src/tools/endpoint-gpus.ts
1465
+ import { z as z6 } from "zod";
1466
+ function registerEndpointGpuTools(server, rt) {
1467
+ const { graphqlAuthed, jsonReply: jsonReply2 } = rt;
1468
+ server.tool(
1469
+ "set-endpoint-gpus",
1470
+ "Set which GPUs a Serverless endpoint's workers run on \u2014 including pinning specific GPU SKUs, which create-endpoint/update-endpoint cannot express. Provide either a raw gpuIds string, or pools plus optional excludeGpuTypeIds (GPU type ids from list-gpu-types) and the exclusion string is built for you: a pool allows every SKU in it, and excluding all but one SKU pins that SKU exactly (e.g. pools:['AMPERE_16'], excludeGpuTypeIds:['NVIDIA RTX 2000 Ada Generation','NVIDIA RTX 4000 Ada Generation','NVIDIA RTX A4500'] pins RTX A4000). All other endpoint settings (workers, scaling, timeouts, template) are read first and preserved. Works on any Serverless endpoint via the authenticated GraphQL API.",
1471
+ {
1472
+ endpointId: z6.string().describe("ID of the Serverless endpoint to update"),
1473
+ gpuIds: z6.string().optional().describe(
1474
+ "Raw gpuIds string, e.g. 'ADA_24' or 'AMPERE_16,-NVIDIA RTX A4500'. Takes precedence over pools/excludeGpuTypeIds."
1475
+ ),
1476
+ pools: z6.array(z6.string()).optional().describe(
1477
+ "GPU pool names workers may use (e.g. ['ADA_80_PRO','AMPERE_80']). The pool field from list-gpu-types."
1478
+ ),
1479
+ excludeGpuTypeIds: z6.array(z6.string()).optional().describe(
1480
+ "GPU type ids to exclude from the allowed pools (e.g. ['NVIDIA H100 NVL']). Use with pools to pin specific SKUs."
1481
+ ),
1482
+ gpuCount: z6.number().int().positive().optional().describe("GPUs per worker. Omit to keep the current value."),
1483
+ minCudaVersion: z6.string().optional().describe(
1484
+ "Minimum host CUDA version workers may run on (e.g. '12.4'). Omit to keep the current value."
1485
+ ),
1486
+ allowedCudaVersions: z6.string().optional().describe(
1487
+ "Comma-separated allowed host CUDA versions (e.g. '12.8,12.7,12.6'). Omit to keep the current value. CUDA compatibility is part of GPU selection \u2014 a narrow list can leave an endpoint unable to schedule workers."
1488
+ )
1489
+ },
1490
+ { title: "Set endpoint GPUs", ...WRITE, idempotentHint: true },
1491
+ async (params) => {
1492
+ const gpuIds = params.gpuIds ?? (params.pools && params.pools.length > 0 ? [
1493
+ ...params.pools,
1494
+ ...(params.excludeGpuTypeIds ?? []).map((id) => `-${id}`)
1495
+ ].join(",") : void 0);
1496
+ if (!gpuIds) {
1497
+ return jsonReply2({
1498
+ error: "Provide gpuIds (raw string) or pools (with optional excludeGpuTypeIds). See list-gpu-types for pool names and GPU type ids."
1499
+ });
1500
+ }
1501
+ const data = await graphqlAuthed(`
1502
+ query {
1503
+ myself {
1504
+ endpoints {
1505
+ id
1506
+ name
1507
+ gpuIds
1508
+ gpuCount
1509
+ workersMin
1510
+ workersMax
1511
+ idleTimeout
1512
+ scalerType
1513
+ scalerValue
1514
+ executionTimeoutMs
1515
+ flashBootType
1516
+ type
1517
+ locations
1518
+ templateId
1519
+ allowedCudaVersions
1520
+ minCudaVersion
1521
+ compliance
1522
+ modelReferences
1523
+ networkVolumeIds {
1524
+ networkVolumeId
1525
+ dataCenterId
1526
+ }
1527
+ }
1528
+ }
1529
+ }
1530
+ `);
1531
+ const current = data.myself.endpoints.find(
1532
+ (e) => e.id === params.endpointId
1533
+ );
1534
+ if (!current) {
1535
+ return jsonReply2({
1536
+ error: `No Serverless endpoint found with id "${params.endpointId}". Use list-endpoints to see your endpoints.`
1537
+ });
1538
+ }
1539
+ const input = {
1540
+ id: current.id,
1541
+ name: current.name,
1542
+ gpuIds,
1543
+ gpuCount: params.gpuCount ?? current.gpuCount,
1544
+ workersMin: current.workersMin,
1545
+ workersMax: current.workersMax,
1546
+ idleTimeout: current.idleTimeout,
1547
+ scalerType: current.scalerType,
1548
+ scalerValue: current.scalerValue,
1549
+ executionTimeoutMs: current.executionTimeoutMs,
1550
+ flashBootType: current.flashBootType,
1551
+ type: current.type,
1552
+ locations: current.locations,
1553
+ networkVolumeIds: current.networkVolumeIds && current.networkVolumeIds.length > 0 ? (
1554
+ // Drop dataCenterId: NetworkVolumeIdsInput takes networkVolumeId
1555
+ // ONLY, and the read shape is rejected outright.
1556
+ current.networkVolumeIds.map((v) => ({
1557
+ networkVolumeId: v.networkVolumeId
1558
+ }))
1559
+ ) : null
1560
+ };
1561
+ for (const [key, value] of Object.entries({
1562
+ templateId: current.templateId,
1563
+ allowedCudaVersions: params.allowedCudaVersions ?? current.allowedCudaVersions,
1564
+ minCudaVersion: params.minCudaVersion ?? current.minCudaVersion,
1565
+ compliance: current.compliance,
1566
+ modelReferences: current.modelReferences
1567
+ })) {
1568
+ if (value !== null && value !== void 0) input[key] = value;
1569
+ }
1570
+ const result = await graphqlAuthed(
1571
+ `
1572
+ mutation saveEndpoint($input: EndpointInput!) {
1573
+ saveEndpoint(input: $input) {
1574
+ id
1575
+ name
1576
+ gpuIds
1577
+ gpuCount
1578
+ workersMin
1579
+ workersMax
1580
+ }
1581
+ }
1582
+ `,
1583
+ { input }
1584
+ );
1585
+ return jsonReply2({
1586
+ endpoint: result.saveEndpoint,
1587
+ previousGpuIds: current.gpuIds
1588
+ });
1589
+ }
1590
+ );
1591
+ }
1592
+
1593
+ // src/tools/pods.ts
1594
+ import { z as z7 } from "zod";
1595
+ function registerPodTools(server, rt) {
1596
+ const { jsonReply: jsonReply2, callRestUrl, backendFor, podAction, env } = rt;
1597
+ server.tool(
1598
+ "list-pods",
1599
+ "List your pods (running and stopped) with optional filters \u2014 compute type, GPU type, data center, name \u2014 plus machine/network-volume expansion. Paginated via limit/cursor.",
1600
+ {
1601
+ ...listPaginationParams,
1602
+ computeType: z7.enum(["GPU", "CPU"]).optional().describe("Filter to only GPU or only CPU Pods"),
1603
+ gpuTypeId: z7.array(z7.string()).optional().describe("Filter to Pods with any of the listed GPU types"),
1604
+ dataCenterId: z7.array(z7.string()).optional().describe("Filter to Pods in any of the provided data centers"),
1605
+ name: z7.string().optional().describe("Filter to Pods with the provided name"),
1606
+ includeMachine: z7.boolean().optional().describe("Include information about the machine"),
1607
+ includeNetworkVolume: z7.boolean().optional().describe("Include information about attached network volumes")
1608
+ },
1609
+ { title: "List pods", ...READ_ONLY },
1610
+ async (params) => {
1611
+ const backend = backendFor("pods");
1612
+ let queryString = "";
1613
+ if (backend.version === "v1") {
1614
+ const queryParams = new URLSearchParams();
1615
+ if (params.computeType)
1616
+ queryParams.append("computeType", params.computeType);
1617
+ if (params.gpuTypeId)
1618
+ params.gpuTypeId.forEach(
1619
+ (type) => queryParams.append("gpuTypeId", type)
1620
+ );
1621
+ if (params.dataCenterId)
1622
+ params.dataCenterId.forEach(
1623
+ (dc) => queryParams.append("dataCenterId", dc)
1624
+ );
1625
+ if (params.name) queryParams.append("name", params.name);
1626
+ if (params.includeMachine)
1627
+ queryParams.append(
1628
+ "includeMachine",
1629
+ params.includeMachine.toString()
1630
+ );
1631
+ if (params.includeNetworkVolume)
1632
+ queryParams.append(
1633
+ "includeNetworkVolume",
1634
+ params.includeNetworkVolume.toString()
1635
+ );
1636
+ queryString = queryParams.toString() ? `?${queryParams.toString()}` : "";
1637
+ }
1638
+ const result = await callRestUrl(
1639
+ `${backend.base}${backend.list}${queryString}`
1640
+ );
1641
+ return capListResult(backend.unwrap(result), {
1642
+ limit: params.limit,
1643
+ cursor: params.cursor
1644
+ });
1645
+ }
1646
+ );
1647
+ server.tool(
1648
+ "get-pod",
1649
+ "Get full details for one pod by id, optionally expanding machine and attached network-volume info.",
1650
+ {
1651
+ podId: z7.string().describe("ID of the pod to retrieve"),
1652
+ includeMachine: z7.boolean().optional().describe("Include information about the machine"),
1653
+ includeNetworkVolume: z7.boolean().optional().describe("Include information about attached network volumes")
1654
+ },
1655
+ { title: "Get pod", ...READ_ONLY },
1656
+ async (params) => {
1657
+ const backend = backendFor("pods");
1658
+ let queryString = "";
1659
+ if (backend.version === "v1") {
1660
+ const queryParams = new URLSearchParams();
1661
+ if (params.includeMachine)
1662
+ queryParams.append(
1663
+ "includeMachine",
1664
+ params.includeMachine.toString()
1665
+ );
1666
+ if (params.includeNetworkVolume)
1667
+ queryParams.append(
1668
+ "includeNetworkVolume",
1669
+ params.includeNetworkVolume.toString()
1670
+ );
1671
+ queryString = queryParams.toString() ? `?${queryParams.toString()}` : "";
1672
+ }
1673
+ const result = await callRestUrl(
1674
+ `${backend.base}${backend.get(params.podId)}${queryString}`
1675
+ );
1676
+ return jsonReply2(result);
1677
+ }
1678
+ );
1679
+ server.tool(
1680
+ "create-pod",
1681
+ 'Create a new GPU/CPU pod on Runpod. Pass gpuTypeIds for a GPU pod, or computeType:"CPU" for a CPU pod (CPU pods are served by the v1 API for now). Pass either imageName or templateId (templateId deploys from an existing template \u2014 its name, image, start command, ports, env, disk, volume, and registry credential are used as defaults, and any field you also pass explicitly replaces the template value for that field, e.g. passing env replaces the whole env set rather than merging; pass containerRegistryAuthId to override or supply a private-image credential, or an empty string to deploy with none). If the user specifies neither an image nor a template, 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.',
1682
+ {
1683
+ name: z7.string().optional().describe("Name for the pod"),
1684
+ imageName: z7.string().optional().describe("Docker image to use. Optional when templateId is provided."),
1685
+ templateId: z7.string().optional().describe(
1686
+ "Deploy from an existing template (see list-templates / get-template). The template supplies name, image, start command, ports, env, disk, volume, and registry credential as defaults; any field you also pass replaces the template value for that field (whole-field, not a merge). Override the registry credential with containerRegistryAuthId. Requires the v2 REST API. Still pass gpuTypeIds or computeType to choose the compute \u2014 a template does not pin the pod compute."
1687
+ ),
1688
+ computeType: z7.enum(["GPU", "CPU"]).optional().describe(
1689
+ "Pod type. On v2, required when not passing gpuTypeIds. 'CPU' is served by the v1 API for now (v2 has no CPU pods yet)."
1690
+ ),
1691
+ cloudType: z7.enum(["SECURE", "COMMUNITY"]).optional().describe("SECURE or COMMUNITY cloud"),
1692
+ gpuTypeIds: z7.array(z7.string()).optional().describe("List of acceptable GPU types"),
1693
+ gpuCount: z7.number().optional().describe("Number of GPUs"),
1694
+ containerDiskInGb: z7.number().optional().describe("Container disk size in GB"),
1695
+ volumeInGb: z7.number().optional().describe("Volume size in GB"),
1696
+ volumeMountPath: z7.string().optional().describe("Path to mount the volume"),
1697
+ ports: z7.array(z7.string()).optional().describe("Ports to expose (e.g., '8888/http', '22/tcp')"),
1698
+ env: z7.record(z7.string()).optional().describe("Environment variables"),
1699
+ containerRegistryAuthId: z7.string().optional().describe(
1700
+ "Container registry credential ID for pulling a private image (see list-container-registry-auths). When deploying from a templateId, this overrides the credential the template carries; pass an empty string to deploy with NO credential (clears a template\u2019s inherited registry)."
1701
+ ),
1702
+ dataCenterIds: z7.array(z7.string()).optional().describe("List of data centers")
1703
+ },
1704
+ { title: "Create pod", ...WRITE },
1705
+ async (params) => {
1706
+ const backend = backendFor("pods");
1707
+ if (params.templateId && backend.version !== "v2") {
1708
+ return jsonReply2({
1709
+ error: "Deploying a pod from a templateId is only supported on the v2 REST API. Set RUNPOD_REST_VERSION=v2, or pass imageName instead.",
1710
+ status: 501
1711
+ });
1712
+ }
1713
+ if (!params.imageName && !params.templateId) {
1714
+ return jsonReply2({
1715
+ error: "Provide imageName, or templateId to deploy from an existing template.",
1716
+ status: 400
1717
+ });
1718
+ }
1719
+ const hasGpuTypes = (params.gpuTypeIds?.length ?? 0) > 0;
1720
+ const hasGpuCount = (params.gpuCount ?? 0) > 0;
1721
+ const wantsCpu = params.computeType === "CPU";
1722
+ const wantsGpu = hasGpuTypes || hasGpuCount || params.computeType === "GPU";
1723
+ if (backend.version === "v2") {
1724
+ if (wantsGpu && wantsCpu) {
1725
+ return jsonReply2({
1726
+ error: "Specify a GPU pod (gpuTypeIds or computeType:'GPU') OR a CPU pod (computeType:'CPU'), not both.",
1727
+ status: 400
1728
+ });
1729
+ }
1730
+ if (!wantsGpu && !wantsCpu) {
1731
+ return jsonReply2({
1732
+ error: "No pod type specified. Pass gpuTypeIds (see list-gpu-types) for a GPU pod, or computeType:'CPU' for a CPU pod.",
1733
+ status: 400
1734
+ });
1735
+ }
1736
+ if (wantsGpu && !hasGpuTypes) {
1737
+ return jsonReply2({
1738
+ error: "A GPU pod needs gpuTypeIds (see list-gpu-types); gpuCount or computeType alone is under-specified.",
1739
+ status: 400
1740
+ });
1741
+ }
1742
+ if (wantsCpu) {
1743
+ if (params.templateId) {
1744
+ return jsonReply2({
1745
+ error: "Template-based deploy is currently supported only for GPU pods on the v2 API. Create the CPU pod with an explicit imageName instead.",
1746
+ status: 400
1747
+ });
1748
+ }
1749
+ try {
1750
+ const result = await callRestUrl(
1751
+ `${restV1Base(env)}/pods`,
1752
+ "POST",
1753
+ params
1754
+ );
1755
+ return jsonReply2({
1756
+ ...result,
1757
+ _servedBy: "v1",
1758
+ _note: "CPU pod: created on the v1 API, because the v2 REST API does not support CPU pods yet."
1759
+ });
1760
+ } catch (error) {
1761
+ if (error instanceof HttpError) {
1762
+ return jsonReply2({
1763
+ error: error.message,
1764
+ status: error.status,
1765
+ _servedBy: "v1",
1766
+ _note: "CPU pod create was routed to the v1 API and failed."
1767
+ });
1768
+ }
1769
+ throw error;
1770
+ }
1771
+ }
1772
+ }
1773
+ let body = backend.mapCreate(params);
1774
+ if (params.templateId) {
1775
+ let template;
1776
+ try {
1777
+ template = await callRestUrl(
1778
+ `${restV2Base(env)}/templates/${params.templateId}`
1779
+ );
1780
+ } catch (error) {
1781
+ if (error instanceof HttpError) {
1782
+ return jsonReply2({
1783
+ error: `Failed to load template ${params.templateId}: ${error.message}`,
1784
+ status: error.status
1785
+ });
1786
+ }
1787
+ throw error;
1788
+ }
1789
+ body = { ...podBodyFromTemplate(template), ...body };
1790
+ }
1791
+ try {
1792
+ const result = await callRestUrl(
1793
+ `${backend.base}${backend.list}`,
1794
+ "POST",
1795
+ body
1796
+ );
1797
+ if (backend.version === "v2" && (params.gpuTypeIds?.length ?? 0) > 1) {
1798
+ return jsonReply2({
1799
+ ...result,
1800
+ _warning: `v2 accepts one GPU type per pod; used "${params.gpuTypeIds[0]}" and ignored ${params.gpuTypeIds.length - 1} other(s): ${params.gpuTypeIds.slice(1).join(", ")}.`
1801
+ });
1802
+ }
1803
+ return jsonReply2(result);
1804
+ } catch (error) {
1805
+ if (error instanceof HttpError) {
1806
+ return jsonReply2({ error: error.message, status: error.status });
1807
+ }
1808
+ throw error;
1809
+ }
1810
+ }
1811
+ );
1812
+ server.tool(
1813
+ "update-pod",
1814
+ "Update a pod's mutable fields (name, image, container disk, volume, ports, env). Only the fields you provide change.",
1815
+ {
1816
+ podId: z7.string().describe("ID of the pod to update"),
1817
+ name: z7.string().optional().describe("New name for the pod"),
1818
+ imageName: z7.string().optional().describe("New Docker image"),
1819
+ containerDiskInGb: z7.number().optional().describe("New container disk size in GB"),
1820
+ volumeInGb: z7.number().optional().describe("New volume size in GB"),
1821
+ volumeMountPath: z7.string().optional().describe("New path to mount the volume"),
1822
+ ports: z7.array(z7.string()).optional().describe("New ports to expose"),
1823
+ env: z7.record(z7.string()).optional().describe("New environment variables")
1824
+ },
1825
+ { title: "Update pod", ...WRITE, idempotentHint: true },
1826
+ async (params) => {
1827
+ const { podId, ...updateParams } = params;
1828
+ const backend = backendFor("pods");
1829
+ const body = backend.mapUpdate(updateParams);
1830
+ const result = await callRestUrl(
1831
+ `${backend.base}${backend.get(podId)}`,
1832
+ "PATCH",
1833
+ body
1834
+ );
1835
+ return jsonReply2(result);
1836
+ }
1837
+ );
1838
+ server.tool(
1839
+ "start-pod",
1840
+ "Start a stopped pod (resumes the same pod and its billing).",
1841
+ {
1842
+ podId: z7.string().describe("ID of the pod to start")
1843
+ },
1844
+ { title: "Start pod", ...WRITE, idempotentHint: true },
1845
+ async (params) => {
1846
+ const result = await podAction(params.podId, "start");
1847
+ return jsonReply2(result);
1848
+ }
1849
+ );
1850
+ server.tool(
1851
+ "stop-pod",
1852
+ "Stop a running pod. The pod and its disk persist; GPU billing stops.",
1853
+ {
1854
+ podId: z7.string().describe("ID of the pod to stop")
1855
+ },
1856
+ { title: "Stop pod", ...WRITE, idempotentHint: true },
1857
+ async (params) => {
1858
+ const result = await podAction(params.podId, "stop");
1859
+ return jsonReply2(result);
1860
+ }
1861
+ );
1862
+ server.tool(
1863
+ "restart-pod",
1864
+ "Restart a running pod (single PodAction call). v2-only \u2014 on the v1 API returns a 501 notice (stop then start the pod instead).",
1865
+ {
1866
+ podId: z7.string().describe("ID of the pod to restart")
1867
+ },
1868
+ { title: "Restart pod", ...WRITE },
1869
+ async (params) => {
1870
+ const backend = backendFor("pods");
1871
+ if (backend.version === "v1") {
1872
+ return jsonReply2({
1873
+ error: "restart-pod is only available on the v2 REST API. Set RUNPOD_REST_VERSION=v2 (or stop then start the pod on v1).",
1874
+ status: 501
1875
+ });
1876
+ }
1877
+ const result = await podAction(params.podId, "restart");
1878
+ return jsonReply2(result);
1879
+ }
1880
+ );
1881
+ server.tool(
1882
+ "stream-pod-logs",
1883
+ "Fetch a bounded snapshot of a pod's live logs (container and/or system) via Server-Sent Events. v2-only \u2014 returns a 501 notice on the v1 API. Reads for up to maxWaitMs (default 5s) and returns the collected log lines; use `tail` to backfill recent lines first. Large output is truncated (see the `truncated` flag).",
1884
+ {
1885
+ podId: z7.string().describe("ID of the pod whose logs to stream"),
1886
+ ...logStreamParams
1887
+ },
1888
+ { title: "Stream pod logs", ...READ_ONLY },
1889
+ (params) => streamLogsReply(
1890
+ rt,
1891
+ {
1892
+ name: "stream-pod-logs",
1893
+ resource: "pods",
1894
+ logsUrl: (backend) => `${backend.base}${backend.get(encodeURIComponent(params.podId))}/logs`
1895
+ },
1896
+ params
1897
+ )
1898
+ );
1899
+ server.tool(
1900
+ "delete-pod",
1901
+ "Permanently delete a pod and its data. This cannot be undone.",
1902
+ {
1903
+ podId: z7.string().describe("ID of the pod to delete")
1904
+ },
1905
+ { title: "Delete pod", ...DESTRUCTIVE },
1906
+ async (params) => {
1907
+ const backend = backendFor("pods");
1908
+ const result = await callRestUrl(
1909
+ `${backend.base}${backend.get(params.podId)}`,
1910
+ "DELETE"
1911
+ );
1912
+ return jsonReply2(result);
1913
+ }
1914
+ );
1915
+ }
1916
+
1917
+ // src/tools/endpoints.ts
1918
+ import { z as z8 } from "zod";
1919
+ var MIN_QUEUE_DELAY = 0.5;
1920
+ var MIN_REQUEST_COUNT = 1;
1921
+ var MIN_IDLE_TIMEOUT = 1;
1922
+ var MAX_IDLE_TIMEOUT = 3600;
1923
+ function scalerValueError(scalerType, scalerValue) {
1924
+ if (scalerType !== "REQUEST_COUNT" || scalerValue === void 0) return;
1925
+ if (!Number.isInteger(scalerValue) || scalerValue < MIN_REQUEST_COUNT) {
1926
+ return `REQUEST_COUNT scales on whole in-flight requests per worker, so scalerValue must be an integer >= ${MIN_REQUEST_COUNT} (got ${scalerValue}). For a fractional target use scalerType QUEUE_DELAY, which takes seconds >= ${MIN_QUEUE_DELAY}.`;
1927
+ }
1928
+ return;
1929
+ }
1930
+ function registerEndpointTools(server, rt) {
1931
+ const { jsonReply: jsonReply2, callRestUrl, backendFor } = rt;
1932
+ server.tool(
1933
+ "list-endpoints",
1934
+ "List your Serverless endpoints, optionally expanding template and worker details (v1 only). Paginated via limit/cursor. On v2 each endpoint carries its request routing in `type` and the URLs to call it in `requestUrls`.",
1935
+ {
1936
+ ...listPaginationParams,
1937
+ includeTemplate: z8.boolean().optional().describe("Include template information (v1 only)"),
1938
+ includeWorkers: z8.boolean().optional().describe("Include information about workers (v1 only)")
1939
+ },
1940
+ { title: "List endpoints", ...READ_ONLY },
1941
+ async (params) => {
1942
+ const backend = backendFor("endpoints");
1943
+ let queryString = "";
1944
+ if (backend.version === "v1") {
1945
+ const queryParams = new URLSearchParams();
1946
+ if (params.includeTemplate)
1947
+ queryParams.append(
1948
+ "includeTemplate",
1949
+ params.includeTemplate.toString()
1950
+ );
1951
+ if (params.includeWorkers)
1952
+ queryParams.append(
1953
+ "includeWorkers",
1954
+ params.includeWorkers.toString()
1955
+ );
1956
+ queryString = queryParams.toString() ? `?${queryParams.toString()}` : "";
1957
+ }
1958
+ const result = await callRestUrl(
1959
+ `${backend.base}${backend.list}${queryString}`
1960
+ );
1961
+ return capListResult(backend.unwrap(result), {
1962
+ limit: params.limit,
1963
+ cursor: params.cursor
1964
+ });
1965
+ }
1966
+ );
1967
+ server.tool(
1968
+ "get-endpoint",
1969
+ "Get one Serverless endpoint by id, optionally expanding template and worker details (v1 only). On v2 the reply carries `type` (queue-based vs load-balancing routing) and `requestUrls` \u2014 the run/runsync/status/... URLs for a queue endpoint, or the base + health URLs for a load-balancing one. Read those rather than constructing endpoint URLs by hand.",
1970
+ {
1971
+ endpointId: z8.string().describe("ID of the endpoint to retrieve"),
1972
+ includeTemplate: z8.boolean().optional().describe("Include template information (v1 only)"),
1973
+ includeWorkers: z8.boolean().optional().describe("Include information about workers (v1 only)")
1974
+ },
1975
+ { title: "Get endpoint", ...READ_ONLY },
1976
+ async (params) => {
1977
+ const backend = backendFor("endpoints");
1978
+ let queryString = "";
1979
+ if (backend.version === "v1") {
1980
+ const queryParams = new URLSearchParams();
1981
+ if (params.includeTemplate)
1982
+ queryParams.append(
1983
+ "includeTemplate",
1984
+ params.includeTemplate.toString()
1985
+ );
1986
+ if (params.includeWorkers)
1987
+ queryParams.append(
1988
+ "includeWorkers",
1989
+ params.includeWorkers.toString()
1990
+ );
1991
+ queryString = queryParams.toString() ? `?${queryParams.toString()}` : "";
1992
+ }
1993
+ const result = await callRestUrl(
1994
+ `${backend.base}${backend.get(params.endpointId)}${queryString}`
1995
+ );
1996
+ return jsonReply2(result);
1997
+ }
1998
+ );
1999
+ server.tool(
2000
+ "create-endpoint",
2001
+ "Create a Serverless endpoint. On v2 (default), pass an inline config: imageName + gpuPoolIds (GPU pool names from list-gpu-types \u2014 the `pool` field, e.g. AMPERE_80/ADA_24) plus optional workers/scaling/disk/env. On v1, pass a templateId instead. Worker min/max set autoscaling bounds (min 0 = scale to zero). Use endpointType to pick queue-based (default) or load-balancing request routing; the response `requestUrls` carries the URLs to call the endpoint with.",
2002
+ {
2003
+ name: z8.string().optional().describe("Name for the endpoint"),
2004
+ // --- v2 inline-config fields ---
2005
+ imageName: z8.string().optional().describe("Docker image (v2). Required on v2 instead of a templateId."),
2006
+ endpointType: z8.enum(["QUEUE", "LOAD_BALANCER"]).optional().describe(
2007
+ "How requests reach the workers (v2). QUEUE (default) = submit jobs through the managed queue (run/runsync/status/...). LOAD_BALANCER = send HTTP requests straight to worker-defined paths, and forces scalerType REQUEST_COUNT. Fixed at creation \u2014 update-endpoint cannot change it."
2008
+ ),
2009
+ gpuPoolIds: z8.array(z8.string()).optional().describe(
2010
+ 'GPU pool names (v2, required). The `pool` field from list-gpu-types, e.g. ["AMPERE_80"]. NOT GPU type ids.'
2011
+ ),
2012
+ gpuCount: z8.number().optional().describe("GPUs per worker (v2)"),
2013
+ args: z8.string().optional().describe("Container start command/args (v2)"),
2014
+ containerDiskInGb: z8.number().optional().describe("Container disk size in GB (v2)"),
2015
+ ports: z8.array(z8.string()).optional().describe("Ports to expose (v2), e.g. ['8000/http']"),
2016
+ env: z8.record(z8.string()).optional().describe("Environment variables (v2)"),
2017
+ containerRegistryAuthId: z8.string().optional().describe("Container registry auth id for a private image (v2)"),
2018
+ networkVolumeIds: z8.array(z8.string()).optional().describe("Network volume ids to attach (v2)"),
2019
+ executionTimeoutMs: z8.number().optional().describe("Per-job execution timeout in ms (v2)"),
2020
+ flashboot: z8.enum(["OFF", "FLASHBOOT", "PRIORITY_FLASHBOOT"]).optional().describe("FlashBoot mode (v2)"),
2021
+ // --- v1 template-based fields ---
2022
+ templateId: z8.string().optional().describe("Template ID (v1). Required on v1."),
2023
+ computeType: z8.enum(["GPU", "CPU"]).optional().describe("GPU or CPU endpoint (v1)"),
2024
+ gpuTypeIds: z8.array(z8.string()).optional().describe("List of acceptable GPU types (v1)"),
2025
+ // --- shared autoscaling fields ---
2026
+ workersMin: z8.number().optional().describe("Minimum number of workers"),
2027
+ workersMax: z8.number().optional().describe("Maximum number of workers"),
2028
+ scalerType: z8.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe(
2029
+ "Autoscaler signal. QUEUE_DELAY scales on how long requests wait in the queue (queue endpoints only); REQUEST_COUNT scales on in-flight requests per worker. Defaults to QUEUE_DELAY for QUEUE endpoints and REQUEST_COUNT for LOAD_BALANCER ones."
2030
+ ),
2031
+ scalerValue: z8.number().min(MIN_QUEUE_DELAY).optional().describe(
2032
+ "Autoscaler target for the chosen scalerType \u2014 seconds of queue delay (min 0.5) or in-flight requests per worker (integer, min 1). Defaults to 4."
2033
+ ),
2034
+ idleTimeout: z8.number().int().min(MIN_IDLE_TIMEOUT).max(MAX_IDLE_TIMEOUT).optional().describe(
2035
+ "Idle timeout in seconds before scaling a worker down (1-3600). Does not apply to QUEUE endpoints scaling on REQUEST_COUNT."
2036
+ ),
2037
+ dataCenterIds: z8.array(z8.string()).optional().describe("List of preferred data centers")
2038
+ },
2039
+ { title: "Create endpoint", ...WRITE },
2040
+ async (params) => {
2041
+ const backend = backendFor("endpoints");
2042
+ if (backend.version === "v2") {
2043
+ if (!params.name) {
2044
+ return jsonReply2({
2045
+ error: "On the v2 REST API, create-endpoint requires a name.",
2046
+ status: 400
2047
+ });
2048
+ }
2049
+ if (!params.imageName) {
2050
+ return jsonReply2({
2051
+ error: "On the v2 REST API, create-endpoint needs an imageName (v2 endpoints are image-based, not template-based). To use a templateId, set RUNPOD_REST_VERSION=v1.",
2052
+ status: 400
2053
+ });
2054
+ }
2055
+ if (!params.gpuPoolIds?.length) {
2056
+ return jsonReply2({
2057
+ error: 'create-endpoint needs gpuPoolIds on v2 (GPU pool names from list-gpu-types \u2014 the `pool` field, e.g. ["AMPERE_80"]).',
2058
+ status: 400
2059
+ });
2060
+ }
2061
+ if (params.endpointType === "LOAD_BALANCER" && params.scalerType === "QUEUE_DELAY") {
2062
+ return jsonReply2({
2063
+ error: "LOAD_BALANCER endpoints have no request queue, so they cannot scale on QUEUE_DELAY. Use scalerType REQUEST_COUNT (the default for this endpoint type), or create a QUEUE endpoint instead.",
2064
+ status: 400
2065
+ });
2066
+ }
2067
+ const scalerError = scalerValueError(
2068
+ params.scalerType ?? (params.endpointType === "LOAD_BALANCER" ? "REQUEST_COUNT" : void 0),
2069
+ params.scalerValue
2070
+ );
2071
+ if (scalerError) {
2072
+ return jsonReply2({ error: scalerError, status: 400 });
2073
+ }
2074
+ const body = backend.mapCreate(params);
2075
+ const result2 = await callRestUrl(
2076
+ `${backend.base}${backend.list}`,
2077
+ "POST",
2078
+ body
2079
+ );
2080
+ return jsonReply2(result2);
2081
+ }
2082
+ if (!params.templateId) {
2083
+ return jsonReply2({
2084
+ error: "On the v1 REST API, create-endpoint needs a templateId. (On v2 \u2014 the default \u2014 pass imageName + gpuPoolIds instead.)",
2085
+ status: 400
2086
+ });
2087
+ }
2088
+ const v1Body = {};
2089
+ for (const k of [
2090
+ "templateId",
2091
+ "name",
2092
+ "computeType",
2093
+ "gpuTypeIds",
2094
+ "gpuCount",
2095
+ "workersMin",
2096
+ "workersMax",
2097
+ "dataCenterIds"
2098
+ ]) {
2099
+ if (params[k] !== void 0) v1Body[k] = params[k];
2100
+ }
2101
+ const result = await callRestUrl(
2102
+ `${backend.base}${backend.list}`,
2103
+ "POST",
2104
+ v1Body
2105
+ );
2106
+ return jsonReply2(result);
2107
+ }
2108
+ );
2109
+ server.tool(
2110
+ "update-endpoint",
2111
+ "Update a Serverless endpoint's config. On v2 you can change image/disk/env/ports/registry/workers/scaling/networkVolumes/timeout/flashboot; on v1, scaling fields (worker min/max, idle timeout, scaler type/value, name). Only provided fields change. An endpoint's request routing (queue vs load balancer) is fixed at creation and cannot be changed here \u2014 recreate the endpoint instead.",
2112
+ {
2113
+ endpointId: z8.string().describe("ID of the endpoint to update"),
2114
+ name: z8.string().optional().describe("New name for the endpoint"),
2115
+ workersMin: z8.number().optional().describe("New minimum number of workers"),
2116
+ workersMax: z8.number().optional().describe("New maximum number of workers"),
2117
+ idleTimeout: z8.number().int().min(MIN_IDLE_TIMEOUT).max(MAX_IDLE_TIMEOUT).optional().describe(
2118
+ "New idle timeout in seconds (1-3600). Does not apply to queue endpoints scaling on REQUEST_COUNT."
2119
+ ),
2120
+ scalerType: z8.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe(
2121
+ "New autoscaler signal. Switchable on queue endpoints; load-balancing endpoints only accept REQUEST_COUNT."
2122
+ ),
2123
+ scalerValue: z8.number().min(MIN_QUEUE_DELAY).optional().describe(
2124
+ "New autoscaler target \u2014 seconds of queue delay (min 0.5) or in-flight requests per worker (integer, min 1). Applies to the endpoint's current scalerType unless you also pass a new one."
2125
+ ),
2126
+ // --- v2-only inline-config fields ---
2127
+ imageName: z8.string().optional().describe("New Docker image (v2)"),
2128
+ gpuPoolIds: z8.array(z8.string()).optional().describe('New GPU pool names (v2), e.g. ["AMPERE_80"]'),
2129
+ gpuCount: z8.number().optional().describe("New GPUs per worker (v2)"),
2130
+ args: z8.string().optional().describe("New container args (v2)"),
2131
+ containerDiskInGb: z8.number().optional().describe("New container disk size in GB (v2)"),
2132
+ ports: z8.array(z8.string()).optional().describe("New ports (v2)"),
2133
+ env: z8.record(z8.string()).optional().describe("New environment variables (v2)"),
2134
+ containerRegistryAuthId: z8.string().optional().describe("New container registry auth id (v2)"),
2135
+ networkVolumeIds: z8.array(z8.string()).optional().describe("New network volume ids (v2)"),
2136
+ executionTimeoutMs: z8.number().optional().describe("New per-job execution timeout in ms (v2)"),
2137
+ flashboot: z8.enum(["OFF", "FLASHBOOT", "PRIORITY_FLASHBOOT"]).optional().describe("New FlashBoot mode (v2)")
2138
+ },
2139
+ { title: "Update endpoint", ...WRITE, idempotentHint: true },
2140
+ async (params) => {
2141
+ const { endpointId, ...updateParams } = params;
2142
+ const backend = backendFor("endpoints");
2143
+ const url = `${backend.base}${backend.get(endpointId)}`;
2144
+ if (backend.version !== "v2") {
2145
+ const body2 = backend.mapUpdate(updateParams);
2146
+ return jsonReply2(await callRestUrl(url, "PATCH", body2));
2147
+ }
2148
+ let scalerType = updateParams.scalerType;
2149
+ if (scalerType === void 0 && updateParams.scalerValue !== void 0) {
2150
+ const current = await callRestUrl(url);
2151
+ scalerType = current?.scaling?.type === "REQUEST_COUNT" ? "REQUEST_COUNT" : "QUEUE_DELAY";
2152
+ }
2153
+ const scalerError = scalerValueError(
2154
+ scalerType,
2155
+ updateParams.scalerValue
2156
+ );
2157
+ if (scalerError) {
2158
+ return jsonReply2({ error: scalerError, status: 400 });
2159
+ }
2160
+ const body = backend.mapUpdate({
2161
+ ...updateParams,
2162
+ scalerType
2163
+ });
2164
+ return jsonReply2(await callRestUrl(url, "PATCH", body));
2165
+ }
2166
+ );
2167
+ server.tool(
2168
+ "delete-endpoint",
2169
+ "Permanently delete a Serverless endpoint. This cannot be undone.",
2170
+ {
2171
+ endpointId: z8.string().describe("ID of the endpoint to delete")
2172
+ },
2173
+ { title: "Delete endpoint", ...DESTRUCTIVE },
2174
+ async (params) => {
2175
+ const backend = backendFor("endpoints");
2176
+ const result = await callRestUrl(
2177
+ `${backend.base}${backend.get(params.endpointId)}`,
2178
+ "DELETE"
2179
+ );
2180
+ return jsonReply2(result);
2181
+ }
2182
+ );
2183
+ server.tool(
2184
+ "list-endpoint-releases",
2185
+ "List a Serverless endpoint's release history and current rollout status (workers on the latest version). v2-only \u2014 returns a 501 notice on the v1 API. Paginated via limit/cursor.",
2186
+ {
2187
+ ...listPaginationParams,
2188
+ endpointId: z8.string().describe("ID of the Serverless endpoint whose releases to list")
2189
+ },
2190
+ { title: "List endpoint releases", ...READ_ONLY },
2191
+ async (params) => {
2192
+ const backend = backendFor("endpoints");
2193
+ if (backend.version === "v1") {
2194
+ return jsonReply2({
2195
+ error: "list-endpoint-releases is only available on the v2 REST API. Set RUNPOD_REST_VERSION=v2.",
2196
+ status: 501
2197
+ });
2198
+ }
2199
+ const raw = await callRestUrl(
2200
+ `${backend.base}/serverless/${params.endpointId}/releases`
2201
+ );
2202
+ const releases = Array.isArray(raw?.releases) ? raw.releases : [];
2203
+ return capListResult(
2204
+ releases,
2205
+ { limit: params.limit, cursor: params.cursor },
2206
+ { rollout: raw?.rollout, endpointVersion: raw?.endpointVersion }
2207
+ );
2208
+ }
2209
+ );
2210
+ server.tool(
2211
+ "list-endpoint-workers",
2212
+ "List the workers backing a Serverless endpoint, with their status and an aggregate summary. v2-only \u2014 returns a 501 notice on the v1 API. An UNHEALTHY worker usually means the container is crash-looping (repeated starts that exit before the handler runs) \u2014 jobs on the endpoint will sit IN_QUEUE even though this is a worker failure, not a capacity shortage; inspect it with stream-worker-logs. Zero workers while jobs queue means the endpoint is waiting for GPU capacity. Paginated via limit/cursor.",
2213
+ {
2214
+ ...listPaginationParams,
2215
+ endpointId: z8.string().describe("ID of the Serverless endpoint whose workers to list")
2216
+ },
2217
+ { title: "List endpoint workers", ...READ_ONLY },
2218
+ async (params) => {
2219
+ const backend = backendFor("workers");
2220
+ if (backend.version === "v1") {
2221
+ return jsonReply2({
2222
+ error: "list-endpoint-workers is only available on the v2 REST API. Set RUNPOD_REST_VERSION=v2 (on v1, use get-endpoint with includeWorkers).",
2223
+ status: 501
2224
+ });
2225
+ }
2226
+ const raw = await callRestUrl(
2227
+ `${backend.base}/serverless/${params.endpointId}/workers`
2228
+ );
2229
+ return capListResult(
2230
+ backend.unwrap(raw),
2231
+ { limit: params.limit, cursor: params.cursor },
2232
+ { summary: raw?.summary, endpointVersion: raw?.endpointVersion }
2233
+ );
2234
+ }
2235
+ );
2236
+ server.tool(
2237
+ "stream-worker-logs",
2238
+ "Fetch a bounded snapshot of a serverless worker's live logs (container and/or system) via Server-Sent Events. v2-only \u2014 returns a 501 notice on the v1 API. Get the workerId from list-endpoint-workers. Use this to diagnose UNHEALTHY workers: repeated `start container` system lines with no container output is the crash-loop signature (the container exits before the handler runs). Reads for up to maxWaitMs (default 5s) and returns the collected log lines; use `tail` to backfill recent lines first. Large output is truncated (see the `truncated` flag).",
2239
+ {
2240
+ endpointId: z8.string().describe("ID of the Serverless endpoint the worker belongs to"),
2241
+ workerId: z8.string().describe(
2242
+ "ID of the worker whose logs to stream (from list-endpoint-workers)"
2243
+ ),
2244
+ ...logStreamParams
2245
+ },
2246
+ { title: "Stream worker logs", ...READ_ONLY },
2247
+ (params) => streamLogsReply(
2248
+ rt,
2249
+ {
2250
+ name: "stream-worker-logs",
2251
+ resource: "workers",
2252
+ logsUrl: (backend) => `${backend.base}/serverless/${encodeURIComponent(params.endpointId)}/workers/${encodeURIComponent(params.workerId)}/logs`
2253
+ },
2254
+ params
2255
+ )
2256
+ );
2257
+ }
2258
+
2259
+ // src/tools/jobs.ts
2260
+ import { z as z9 } from "zod";
2261
+ var DIAGNOSIS_TTL_MS = 15e3;
2262
+ var MAX_DIAGNOSIS_ENTRIES = 500;
2263
+ var diagnosisCache = /* @__PURE__ */ new Map();
2264
+ function registerJobTools(server, rt) {
2265
+ const { jsonReply: jsonReply2, serverlessRequest, backendFor, callRestUrl } = rt;
2266
+ async function diagnoseQueuedJob(endpointId) {
2267
+ const cached = diagnosisCache.get(endpointId);
2268
+ if (cached && cached.expiresAt > Date.now()) {
2269
+ return cached.value;
2270
+ }
2271
+ diagnosisCache.delete(endpointId);
2272
+ try {
2273
+ const backend = backendFor("workers");
2274
+ if (backend.version !== "v2") return null;
2275
+ const raw = await callRestUrl(
2276
+ `${backend.base}/serverless/${endpointId}/workers`
2277
+ );
2278
+ const summary = raw?.summary;
2279
+ const workers = raw?.workers ?? [];
2280
+ if (!summary) return null;
2281
+ const remember = (value) => {
2282
+ if (diagnosisCache.size >= MAX_DIAGNOSIS_ENTRIES) {
2283
+ const oldest = diagnosisCache.keys().next().value;
2284
+ if (oldest !== void 0) diagnosisCache.delete(oldest);
2285
+ }
2286
+ diagnosisCache.set(endpointId, {
2287
+ value,
2288
+ expiresAt: Date.now() + DIAGNOSIS_TTL_MS
2289
+ });
2290
+ return value;
2291
+ };
2292
+ if ((summary.unhealthy ?? 0) > 0) {
2293
+ const badIds = workers.filter((w) => w.status === "UNHEALTHY").map((w) => w.id).join(", ");
2294
+ return remember({
2295
+ workerHealth: summary,
2296
+ hint: `${summary.unhealthy} of ${summary.total} worker(s) on this endpoint are UNHEALTHY \u2014 the container is likely crash-looping (repeated starts that exit before the handler runs). The job can stay IN_QUEUE indefinitely; this is a worker failure, NOT a capacity shortage. Inspect the logs with stream-worker-logs${badIds ? ` (workerId: ${badIds})` : ""}.`
2297
+ });
2298
+ }
2299
+ if ((summary.total ?? 0) === 0) {
2300
+ return remember({
2301
+ workerHealth: summary,
2302
+ hint: "No workers are scheduled for this endpoint yet \u2014 it may simply be scaling up from zero (normal for the first seconds of a cold start), or it is waiting for GPU capacity / its GPU-CUDA constraints exclude the currently-available hosts. If this persists, check availability with list-gpu-types or widen the gpuIds/CUDA settings."
2303
+ });
2304
+ }
2305
+ if ((summary.throttled ?? 0) > 0 && (summary.running ?? 0) === 0) {
2306
+ return remember({
2307
+ workerHealth: summary,
2308
+ hint: "Workers exist but are throttled \u2014 the hosts are at capacity right now; the job should start when capacity frees up."
2309
+ });
2310
+ }
2311
+ if ((summary.initializing ?? 0) > 0) {
2312
+ return remember({
2313
+ workerHealth: summary,
2314
+ hint: "A worker is initializing \u2014 likely a cold start (image pull / model load); the job should start soon."
2315
+ });
2316
+ }
2317
+ return remember({ workerHealth: summary, hint: "" });
2318
+ } catch {
2319
+ return null;
2320
+ }
2321
+ }
2322
+ const endpointIdSchema = z9.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid endpoint ID format");
2323
+ const jobIdSchema = z9.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid job ID format");
2324
+ const inputSchema = z9.record(z9.unknown()).describe(
2325
+ "Input payload for the worker handler. The expected fields depend on the deployed model or worker."
2326
+ );
2327
+ const webhookSchema = z9.string().url().optional().describe(
2328
+ "Webhook URL to receive job completion notifications instead of polling"
2329
+ );
2330
+ const policySchema = z9.object({
2331
+ executionTimeout: z9.number().optional().describe("Maximum execution time in milliseconds"),
2332
+ lowPriority: z9.boolean().optional().describe("Submit as a low-priority job"),
2333
+ ttl: z9.number().optional().describe("Time-to-live for the job result in milliseconds")
2334
+ }).optional().describe("Execution policy options");
2335
+ const s3ConfigSchema = z9.object({
2336
+ accessId: z9.string().describe("S3 access key ID"),
2337
+ accessSecret: z9.string().describe("S3 secret access key"),
2338
+ bucketName: z9.string().describe("S3 bucket name"),
2339
+ endpointUrl: z9.string().describe("S3 endpoint URL")
2340
+ }).optional().describe("S3-compatible storage config for large outputs");
2341
+ server.tool(
2342
+ "run-endpoint",
2343
+ "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.",
2344
+ {
2345
+ endpointId: endpointIdSchema.describe(
2346
+ "ID of the Serverless endpoint to run"
2347
+ ),
2348
+ input: inputSchema,
2349
+ webhook: webhookSchema,
2350
+ policy: policySchema,
2351
+ s3Config: s3ConfigSchema
2352
+ },
2353
+ { title: "Run endpoint (async)", ...WRITE },
2354
+ async (params) => {
2355
+ const { endpointId, ...body } = params;
2356
+ const result = await serverlessRequest(
2357
+ endpointId,
2358
+ "/run",
2359
+ "POST",
2360
+ body
2361
+ );
2362
+ return jsonReply2(result);
2363
+ }
2364
+ );
2365
+ server.tool(
2366
+ "runsync-endpoint",
2367
+ "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).",
2368
+ {
2369
+ endpointId: endpointIdSchema.describe(
2370
+ "ID of the Serverless endpoint to run synchronously"
2371
+ ),
2372
+ input: inputSchema,
2373
+ wait: z9.number().min(1e3).max(3e5).optional().describe(
2374
+ "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)."
2375
+ ),
2376
+ webhook: webhookSchema,
2377
+ policy: policySchema,
2378
+ s3Config: s3ConfigSchema
2379
+ },
2380
+ { title: "Run endpoint (sync)", ...WRITE },
2381
+ async (params) => {
2382
+ const { endpointId, wait, ...body } = params;
2383
+ const path = wait ? `/runsync?wait=${wait}` : "/runsync";
2384
+ const result = await serverlessRequest(
2385
+ endpointId,
2386
+ path,
2387
+ "POST",
2388
+ body
2389
+ );
2390
+ return jsonReply2(result);
2391
+ }
2392
+ );
2393
+ server.tool(
2394
+ "get-job-status",
2395
+ "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. IMPORTANT: a job stuck IN_QUEUE does not necessarily mean a capacity shortage \u2014 a worker may have spun up and crash-looped (the platform marks it UNHEALTHY while the job stays queued). When the job is IN_QUEUE this tool attaches a workerHealth summary and a hint; to dig deeper, call list-endpoint-workers (look for UNHEALTHY) and stream-worker-logs.",
2396
+ {
2397
+ endpointId: endpointIdSchema.describe(
2398
+ "ID of the Serverless endpoint the job belongs to"
2399
+ ),
2400
+ jobId: jobIdSchema.describe("ID of the job to check")
2401
+ },
2402
+ { title: "Get job status", ...READ_ONLY },
2403
+ async (params) => {
2404
+ const result = await serverlessRequest(
2405
+ params.endpointId,
2406
+ `/status/${params.jobId}`
2407
+ );
2408
+ if (result && typeof result === "object" && result.status === "IN_QUEUE") {
2409
+ const diagnosis = await diagnoseQueuedJob(params.endpointId);
2410
+ if (diagnosis) {
2411
+ return jsonReply2({
2412
+ ...result,
2413
+ workerHealth: diagnosis.workerHealth,
2414
+ ...diagnosis.hint ? { hint: diagnosis.hint } : {}
2415
+ });
2416
+ }
2417
+ }
2418
+ return jsonReply2(result);
2419
+ }
2420
+ );
2421
+ server.tool(
2422
+ "stream-job",
2423
+ "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.",
2424
+ {
2425
+ endpointId: endpointIdSchema.describe(
2426
+ "ID of the Serverless endpoint the job belongs to"
2427
+ ),
2428
+ jobId: jobIdSchema.describe("ID of the job to stream results from")
2429
+ },
2430
+ { title: "Stream job", ...READ_ONLY },
2431
+ async (params) => {
2432
+ const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
2433
+ "COMPLETED",
2434
+ "FAILED",
2435
+ "CANCELLED",
2436
+ "TIMED_OUT"
2437
+ ]);
2438
+ const MAX_POLL_TIME_MS = 5 * 60 * 1e3;
2439
+ const POLL_INTERVAL_MS = 1e3;
2440
+ const MAX_CONSECUTIVE_ERRORS = 5;
2441
+ const allChunks = [];
2442
+ let finalResult = {};
2443
+ let consecutiveErrors = 0;
2444
+ let lastError;
2445
+ const startTime = Date.now();
2446
+ while (true) {
2447
+ try {
2448
+ const result = await serverlessRequest(
2449
+ params.endpointId,
2450
+ `/stream/${params.jobId}`
2451
+ );
2452
+ consecutiveErrors = 0;
2453
+ if (Array.isArray(result.stream)) {
2454
+ allChunks.push(...result.stream);
2455
+ }
2456
+ finalResult = result;
2457
+ if (TERMINAL_STATUSES.has(result.status)) {
2458
+ break;
2459
+ }
2460
+ } catch (error) {
2461
+ consecutiveErrors++;
2462
+ lastError = error instanceof Error ? error.message : String(error);
2463
+ if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
2464
+ finalResult.error = `Polling aborted after ${MAX_CONSECUTIVE_ERRORS} consecutive errors: ${lastError}`;
2465
+ break;
2466
+ }
2467
+ }
2468
+ if (Date.now() - startTime > MAX_POLL_TIME_MS) {
2469
+ finalResult.pollingTimedOut = true;
2470
+ finalResult.note = "Polling timed out after 5 minutes. Use get-job-status to check the job later.";
2471
+ if (lastError) finalResult.lastError = lastError;
2472
+ break;
2473
+ }
2474
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
2475
+ }
2476
+ return jsonReply2({ ...finalResult, stream: allChunks });
2477
+ }
2478
+ );
2479
+ server.tool(
2480
+ "cancel-job",
2481
+ "Cancel a Serverless job that is queued or in progress.",
2482
+ {
2483
+ endpointId: endpointIdSchema.describe(
2484
+ "ID of the Serverless endpoint the job belongs to"
2485
+ ),
2486
+ jobId: jobIdSchema.describe("ID of the job to cancel")
2487
+ },
2488
+ { title: "Cancel job", ...WRITE, idempotentHint: true },
2489
+ async (params) => {
2490
+ const result = await serverlessRequest(
2491
+ params.endpointId,
2492
+ `/cancel/${params.jobId}`,
2493
+ "POST"
2494
+ );
2495
+ return jsonReply2(result);
2496
+ }
2497
+ );
2498
+ server.tool(
2499
+ "retry-job",
2500
+ "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.",
2501
+ {
2502
+ endpointId: endpointIdSchema.describe(
2503
+ "ID of the Serverless endpoint the job belongs to"
2504
+ ),
2505
+ jobId: jobIdSchema.describe("ID of the job to retry")
2506
+ },
2507
+ { title: "Retry job", ...WRITE },
2508
+ async (params) => {
2509
+ const result = await serverlessRequest(
2510
+ params.endpointId,
2511
+ `/retry/${params.jobId}`,
2512
+ "POST"
2513
+ );
2514
+ return jsonReply2(result);
2515
+ }
2516
+ );
2517
+ server.tool(
2518
+ "endpoint-health",
2519
+ "Get the health and operational status of a Serverless endpoint, including worker counts and job statistics. Use this when jobs are stuck IN_QUEUE: unhealthy workers mean a crash-looping container (a worker failure \u2014 inspect with stream-worker-logs), while zero workers means the endpoint is waiting for GPU capacity.",
2520
+ {
2521
+ endpointId: endpointIdSchema.describe(
2522
+ "ID of the Serverless endpoint to check health for"
2523
+ )
2524
+ },
2525
+ { title: "Endpoint health", ...READ_ONLY },
2526
+ async (params) => {
2527
+ const result = await serverlessRequest(params.endpointId, "/health");
2528
+ return jsonReply2(result);
2529
+ }
2530
+ );
2531
+ server.tool(
2532
+ "purge-endpoint-queue",
2533
+ "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.",
2534
+ {
2535
+ endpointId: endpointIdSchema.describe(
2536
+ "ID of the Serverless endpoint to purge the queue for"
2537
+ )
2538
+ },
2539
+ { title: "Purge endpoint queue", ...WRITE, idempotentHint: true },
2540
+ async (params) => {
2541
+ const result = await serverlessRequest(
2542
+ params.endpointId,
2543
+ "/purge-queue",
2544
+ "POST"
2545
+ );
2546
+ return jsonReply2(result);
2547
+ }
2548
+ );
2549
+ }
2550
+
2551
+ // src/tools/templates.ts
2552
+ import { z as z10 } from "zod";
2553
+ function registerTemplateTools(server, rt) {
2554
+ const { jsonReply: jsonReply2, callRestUrl, backendFor } = rt;
2555
+ server.tool(
2556
+ "list-templates",
2557
+ `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.`,
2558
+ {
2559
+ ...listPaginationParams,
2560
+ includeRunpodTemplates: z10.boolean().optional().describe("Include official Runpod templates in the response"),
2561
+ includePublicTemplates: z10.boolean().optional().describe("Include community-made public templates in the response"),
2562
+ includeEndpointBoundTemplates: z10.boolean().optional().describe(
2563
+ "Include templates bound to Serverless endpoints in the response"
2564
+ )
2565
+ },
2566
+ { title: "List templates", ...READ_ONLY },
2567
+ async (params) => {
2568
+ const backend = backendFor("templates");
2569
+ let query = "";
2570
+ if (backend.version === "v1") {
2571
+ const queryParams = new URLSearchParams();
2572
+ if (params.includeRunpodTemplates)
2573
+ queryParams.set("includeRunpodTemplates", "true");
2574
+ if (params.includePublicTemplates)
2575
+ queryParams.set("includePublicTemplates", "true");
2576
+ if (params.includeEndpointBoundTemplates)
2577
+ queryParams.set("includeEndpointBoundTemplates", "true");
2578
+ query = queryParams.toString() ? `?${queryParams.toString()}` : "";
2579
+ }
2580
+ const result = await callRestUrl(
2581
+ `${backend.base}${backend.list}${query}`
2582
+ );
2583
+ return capListResult(backend.unwrap(result), {
2584
+ limit: params.limit,
2585
+ cursor: params.cursor
2586
+ });
2587
+ }
2588
+ );
2589
+ server.tool(
2590
+ "get-template",
2591
+ "Get one template by id (image, env, ports, disk/volume config).",
2592
+ {
2593
+ templateId: z10.string().describe("ID of the template to retrieve")
2594
+ },
2595
+ { title: "Get template", ...READ_ONLY },
2596
+ async (params) => {
2597
+ const backend = backendFor("templates");
2598
+ const result = await callRestUrl(
2599
+ `${backend.base}${backend.get(params.templateId)}`
2600
+ );
2601
+ return jsonReply2(result);
2602
+ }
2603
+ );
2604
+ server.tool(
2605
+ "create-template",
2606
+ "Create a reusable pod/endpoint template (image, ports, env, disk/volume). Category is optional and defaults to NVIDIA.",
2607
+ {
2608
+ name: z10.string().describe("Name for the template"),
2609
+ imageName: z10.string().describe("Docker image to use"),
2610
+ isServerless: z10.boolean().optional().describe("Is this a serverless template"),
2611
+ ports: z10.array(z10.string()).optional().describe("Ports to expose"),
2612
+ dockerEntrypoint: z10.array(z10.string()).optional().describe(
2613
+ "Docker entrypoint commands. Note: not persisted on the v2 REST API, which has no separate entrypoint field (only a start command)."
2614
+ ),
2615
+ dockerStartCmd: z10.array(z10.string()).optional().describe(
2616
+ 'Container start command. On v2 this is stored as the template\'s `args` string; a multi-element array is joined with spaces (e.g. ["python","-u","app.py"] \u2192 "python -u app.py"). The join is lossy: an element that itself contains spaces is NOT preserved as one argument \u2014 e.g. ["sh","-c","echo hi"] becomes "sh -c echo hi", so pass a shell command as a single pre-quoted element if that distinction matters. Omit or pass an empty array to leave the command unset (never overwrites with "").'
2617
+ ),
2618
+ env: z10.record(z10.string()).optional().describe("Environment variables"),
2619
+ containerDiskInGb: z10.number().optional().describe("Container disk size in GB"),
2620
+ volumeInGb: z10.number().optional().describe("Volume size in GB"),
2621
+ volumeMountPath: z10.string().optional().describe("Path to mount the volume"),
2622
+ readme: z10.string().optional().describe("README content in markdown format"),
2623
+ category: z10.enum(["CPU", "NVIDIA", "AMD"]).optional().describe(
2624
+ "How the template is grouped and filtered in the Runpod console \u2014 it does NOT affect hardware selection, scheduling, or billing. Optional; defaults to NVIDIA. Set CPU or AMD only to file the template correctly in the console."
2625
+ ),
2626
+ containerRegistryAuthId: z10.string().optional().describe(
2627
+ "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."
2628
+ )
2629
+ },
2630
+ { title: "Create template", ...WRITE },
2631
+ async (params) => {
2632
+ const backend = backendFor("templates");
2633
+ const body = backend.mapCreate(params);
2634
+ const result = await callRestUrl(
2635
+ `${backend.base}${backend.list}`,
2636
+ "POST",
2637
+ body
2638
+ );
2639
+ return jsonReply2(result);
2640
+ }
2641
+ );
2642
+ server.tool(
2643
+ "update-template",
2644
+ "Update a template's mutable fields (name, image, ports, env, start command, registry auth). Only provided fields change; omitted fields are left untouched.",
2645
+ {
2646
+ templateId: z10.string().describe("ID of the template to update"),
2647
+ name: z10.string().optional().describe("New name for the template"),
2648
+ imageName: z10.string().optional().describe("New Docker image"),
2649
+ dockerStartCmd: z10.array(z10.string()).optional().describe(
2650
+ "New container start command. On v2 stored as the template's `args` string; a multi-element array is joined with spaces (lossy \u2014 an element containing spaces is split into separate tokens). Note: this can only set a command, not clear one \u2014 an empty or absent array is ignored so the existing command is preserved."
2651
+ ),
2652
+ ports: z10.array(z10.string()).optional().describe("New ports to expose"),
2653
+ env: z10.record(z10.string()).optional().describe("New environment variables"),
2654
+ readme: z10.string().optional().describe("New README content in markdown format"),
2655
+ containerRegistryAuthId: z10.string().optional().describe(
2656
+ "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."
2657
+ )
2658
+ },
2659
+ { title: "Update template", ...WRITE, idempotentHint: true },
2660
+ async (params) => {
2661
+ const { templateId, ...updateParams } = params;
2662
+ const backend = backendFor("templates");
2663
+ const body = backend.mapUpdate(updateParams);
2664
+ const result = await callRestUrl(
2665
+ `${backend.base}${backend.get(templateId)}`,
2666
+ "PATCH",
2667
+ body
2668
+ );
2669
+ return jsonReply2(result);
2670
+ }
2671
+ );
2672
+ server.tool(
2673
+ "delete-template",
2674
+ "Permanently delete a template. This cannot be undone.",
2675
+ {
2676
+ templateId: z10.string().describe("ID of the template to delete")
2677
+ },
2678
+ { title: "Delete template", ...DESTRUCTIVE },
2679
+ async (params) => {
2680
+ const backend = backendFor("templates");
2681
+ const result = await callRestUrl(
2682
+ `${backend.base}${backend.get(params.templateId)}`,
2683
+ "DELETE"
2684
+ );
2685
+ return jsonReply2(result);
2686
+ }
2687
+ );
2688
+ }
2689
+
2690
+ // src/tools/network-volumes.ts
2691
+ import { z as z11 } from "zod";
2692
+ function registerNetworkVolumeTools(server, rt) {
2693
+ const { jsonReply: jsonReply2, callRestUrl, backendFor } = rt;
2694
+ server.tool(
2695
+ "list-network-volumes",
2696
+ "List your network volumes (persistent storage attachable to pods). Paginated via limit/cursor.",
2697
+ listPaginationParams,
2698
+ { title: "List network volumes", ...READ_ONLY },
2699
+ async (params) => {
2700
+ const backend = backendFor("networkVolumes");
2701
+ const result = await callRestUrl(`${backend.base}${backend.list}`);
2702
+ return capListResult(backend.unwrap(result), {
2703
+ limit: params.limit,
2704
+ cursor: params.cursor
2705
+ });
2706
+ }
2707
+ );
2708
+ server.tool(
2709
+ "get-network-volume",
2710
+ "Get one network volume by id (name, size, data center).",
2711
+ {
2712
+ networkVolumeId: z11.string().describe("ID of the network volume to retrieve")
2713
+ },
2714
+ { title: "Get network volume", ...READ_ONLY },
2715
+ async (params) => {
2716
+ const backend = backendFor("networkVolumes");
2717
+ const result = await callRestUrl(
2718
+ `${backend.base}${backend.get(params.networkVolumeId)}`
2719
+ );
2720
+ return jsonReply2(result);
2721
+ }
2722
+ );
2723
+ server.tool(
2724
+ "create-network-volume",
2725
+ "Create a persistent network volume in a data center (size 10\u20134096 GB) that pods can mount. Pass volumeType to pick a storage tier; omit it to get the data center default.",
2726
+ {
2727
+ name: z11.string().describe("Name for the network volume"),
2728
+ // Bounds mirror the v2 spec (integer, minimum 10, maximum 4096). Enforced
2729
+ // here as well as described, so an out-of-range value fails locally
2730
+ // instead of costing an API roundtrip.
2731
+ size: z11.number().int().min(10).max(4096).describe("Size in GB (10-4096)"),
2732
+ dataCenterId: z11.string().describe("Data center ID (see list-data-centers)"),
2733
+ volumeType: z11.enum(["STANDARD", "HIGH_PERFORMANCE"]).optional().describe(
2734
+ "Storage tier. Omit for the data center's default (primary) tier. HIGH_PERFORMANCE provisions an HPS volume. Immutable after creation \u2014 update-network-volume cannot change it."
2735
+ )
2736
+ },
2737
+ { title: "Create network volume", ...WRITE },
2738
+ async (params) => {
2739
+ const backend = backendFor("networkVolumes");
2740
+ const body = backend.mapCreate(params);
2741
+ const result = await callRestUrl(
2742
+ `${backend.base}${backend.list}`,
2743
+ "POST",
2744
+ body
2745
+ );
2746
+ return jsonReply2(result);
2747
+ }
2748
+ );
2749
+ server.tool(
2750
+ "update-network-volume",
2751
+ "Update a network volume (rename, or grow size \u2014 the new size must exceed the current size). Only provided fields change.",
2752
+ {
2753
+ networkVolumeId: z11.string().describe("ID of the network volume to update"),
2754
+ name: z11.string().optional().describe("New name for the network volume"),
2755
+ // Same absolute bounds as create. "Larger than current" stays server-side —
2756
+ // we do not hold the current size here, so only the range is checked.
2757
+ size: z11.number().int().min(10).max(4096).optional().describe("New size in GB, 10-4096 (must be larger than current)")
2758
+ },
2759
+ { title: "Update network volume", ...WRITE, idempotentHint: true },
2760
+ async (params) => {
2761
+ const { networkVolumeId, ...updateParams } = params;
2762
+ const backend = backendFor("networkVolumes");
2763
+ const body = backend.mapUpdate(updateParams);
2764
+ const result = await callRestUrl(
2765
+ `${backend.base}${backend.get(networkVolumeId)}`,
2766
+ "PATCH",
2767
+ body
2768
+ );
2769
+ return jsonReply2(result);
2770
+ }
2771
+ );
2772
+ server.tool(
2773
+ "delete-network-volume",
2774
+ "Permanently delete a network volume and its data. This cannot be undone.",
2775
+ {
2776
+ networkVolumeId: z11.string().describe("ID of the network volume to delete")
2777
+ },
2778
+ { title: "Delete network volume", ...DESTRUCTIVE },
2779
+ async (params) => {
2780
+ const backend = backendFor("networkVolumes");
2781
+ const result = await callRestUrl(
2782
+ `${backend.base}${backend.get(params.networkVolumeId)}`,
2783
+ "DELETE"
2784
+ );
2785
+ return jsonReply2(result);
2786
+ }
2787
+ );
2788
+ }
2789
+
2790
+ // src/tools/registries.ts
2791
+ import { z as z12 } from "zod";
2792
+ var DELEGATIONS = "/delegations";
2793
+ function registerRegistryTools(server, rt) {
2794
+ const { jsonReply: jsonReply2, callRestUrl, backendFor } = rt;
2795
+ const delegationsV2OnlyNotice = (tool) => ({
2796
+ error: `${tool} is only available on the v2 REST API. Set RUNPOD_REST_VERSION=v2.`,
2797
+ status: 501
2798
+ });
2799
+ server.tool(
2800
+ "list-container-registry-auths",
2801
+ "List your saved container-registry credentials (private image-pull auth). Paginated via limit/cursor.",
2802
+ listPaginationParams,
2803
+ { title: "List container registry auths", ...READ_ONLY },
2804
+ async (params) => {
2805
+ const backend = backendFor("registries");
2806
+ const result = await callRestUrl(`${backend.base}${backend.list}`);
2807
+ return capListResult(backend.unwrap(result), {
2808
+ limit: params.limit,
2809
+ cursor: params.cursor
2810
+ });
2811
+ }
2812
+ );
2813
+ server.tool(
2814
+ "get-container-registry-auth",
2815
+ "Get one saved container-registry credential by id (the secret/password is not returned).",
2816
+ {
2817
+ containerRegistryAuthId: z12.string().describe("ID of the container registry auth to retrieve")
2818
+ },
2819
+ { title: "Get container registry auth", ...READ_ONLY },
2820
+ async (params) => {
2821
+ const backend = backendFor("registries");
2822
+ const result = await callRestUrl(
2823
+ `${backend.base}${backend.get(params.containerRegistryAuthId)}`
2824
+ );
2825
+ return jsonReply2(result);
2826
+ }
2827
+ );
2828
+ server.tool(
2829
+ "create-container-registry-auth",
2830
+ "Save container-registry credentials (username + password/token) so pods and endpoints can pull private images.",
2831
+ {
2832
+ name: z12.string().describe("Name for the container registry auth"),
2833
+ username: z12.string().describe("Registry username"),
2834
+ password: z12.string().describe("Registry password or access token (stored as a secret)")
2835
+ },
2836
+ { title: "Create container registry auth", ...WRITE },
2837
+ async (params) => {
2838
+ const backend = backendFor("registries");
2839
+ const body = backend.mapCreate(params);
2840
+ const result = await callRestUrl(
2841
+ `${backend.base}${backend.list}`,
2842
+ "POST",
2843
+ body
2844
+ );
2845
+ return jsonReply2(result);
2846
+ }
2847
+ );
2848
+ server.tool(
2849
+ "delete-container-registry-auth",
2850
+ "Permanently delete a saved container-registry credential. This cannot be undone.",
2851
+ {
2852
+ containerRegistryAuthId: z12.string().describe("ID of the container registry auth to delete")
2853
+ },
2854
+ { title: "Delete container registry auth", ...DESTRUCTIVE },
2855
+ async (params) => {
2856
+ const backend = backendFor("registries");
2857
+ const result = await callRestUrl(
2858
+ `${backend.base}${backend.get(params.containerRegistryAuthId)}`,
2859
+ "DELETE"
2860
+ );
2861
+ return jsonReply2(result);
2862
+ }
2863
+ );
2864
+ server.tool(
2865
+ "list-registry-delegations",
2866
+ "List your AWS ECR delegations \u2014 ECR repositories Runpod has been granted scoped pull access to, so private ECR images can be pulled without storing AWS credentials. Each entry includes the `dockerRegistryUri` to pull from. v2-only \u2014 returns a 501 notice on the v1 API. Paginated via limit/cursor.",
2867
+ listPaginationParams,
2868
+ { title: "List registry delegations", ...READ_ONLY },
2869
+ async (params) => {
2870
+ const backend = backendFor("registries");
2871
+ if (backend.version === "v1") {
2872
+ return jsonReply2(delegationsV2OnlyNotice("list-registry-delegations"));
2873
+ }
2874
+ const raw = await callRestUrl(
2875
+ `${backend.base}${backend.list}${DELEGATIONS}`
2876
+ );
2877
+ const delegations = Array.isArray(raw?.delegations) ? raw.delegations : [];
2878
+ return capListResult(delegations, {
2879
+ limit: params.limit,
2880
+ cursor: params.cursor
2881
+ });
2882
+ }
2883
+ );
2884
+ server.tool(
2885
+ "create-registry-delegation",
2886
+ "Register an AWS ECR repository so Runpod can pull private images from it without stored credentials. Pass the repository ARN; the reply carries the `dockerRegistryUri`, resolved repository/tag, and AWS region. v2-only \u2014 returns a 501 notice on the v1 API. For a non-ECR private registry use create-container-registry-auth instead.",
2887
+ {
2888
+ resource: z12.string().min(1).describe(
2889
+ 'ECR resource ARN, e.g. "arn:aws:ecr:us-east-2:123456789012:repository/my-org/my-image"'
2890
+ ),
2891
+ name: z12.string().optional().describe("Optional human-readable name for the delegation")
2892
+ },
2893
+ { title: "Create registry delegation", ...WRITE },
2894
+ async (params) => {
2895
+ const backend = backendFor("registries");
2896
+ if (backend.version === "v1") {
2897
+ return jsonReply2(delegationsV2OnlyNotice("create-registry-delegation"));
2898
+ }
2899
+ const body = { resource: params.resource };
2900
+ if (params.name !== void 0) body.name = params.name;
2901
+ const result = await callRestUrl(
2902
+ `${backend.base}${backend.list}${DELEGATIONS}`,
2903
+ "POST",
2904
+ body
2905
+ );
2906
+ return jsonReply2(result);
2907
+ }
2908
+ );
2909
+ server.tool(
2910
+ "delete-registry-delegation",
2911
+ "Revoke an AWS ECR delegation, withdrawing Runpod's pull access to that repository. Existing workers keep running; future pulls fail. v2-only \u2014 returns a 501 notice on the v1 API. This cannot be undone.",
2912
+ {
2913
+ delegationId: z12.string().describe(
2914
+ "ID of the delegation to revoke (from list-registry-delegations)"
2915
+ )
2916
+ },
2917
+ { title: "Revoke registry delegation", ...DESTRUCTIVE },
2918
+ async (params) => {
2919
+ const backend = backendFor("registries");
2920
+ if (backend.version === "v1") {
2921
+ return jsonReply2(delegationsV2OnlyNotice("delete-registry-delegation"));
2922
+ }
2923
+ const result = await callRestUrl(
2924
+ `${backend.base}${backend.list}${DELEGATIONS}/${encodeURIComponent(
2925
+ params.delegationId
2926
+ )}`,
2927
+ "DELETE"
2928
+ );
2929
+ return jsonReply2(result);
2930
+ }
2931
+ );
2932
+ }
2933
+
2934
+ // src/tools/billing.ts
2935
+ import { z as z13 } from "zod";
2936
+ var BILLING_SCOPE_PATH = {
2937
+ all: "/billing",
2938
+ pods: "/billing/pods",
2939
+ serverless: "/billing/serverless",
2940
+ endpoints: "/billing/endpoints",
2941
+ networkvolumes: "/billing/networkvolumes",
2942
+ clusters: "/billing/clusters"
2943
+ };
2944
+ function registerBillingTools(server, rt) {
2945
+ const { jsonReply: jsonReply2, callRestUrl, backendFor } = rt;
2946
+ server.tool(
2947
+ "get-billing",
2948
+ "Get time-bucketed Runpod spend history, either aggregated across all resources or broken down by resource type (pods, serverless, endpoints, network volumes, clusters). v2-only \u2014 returns a 501 notice on the v1 API. Records are capped via limit/cursor; narrow the window with startTime/endTime or lastN.",
2949
+ {
2950
+ ...listPaginationParams,
2951
+ scope: z13.enum([
2952
+ "all",
2953
+ "pods",
2954
+ "serverless",
2955
+ "endpoints",
2956
+ "networkvolumes",
2957
+ "clusters"
2958
+ ]).optional().describe(
2959
+ 'Which billing breakdown to fetch. "all" (default) is the aggregate across every resource.'
2960
+ ),
2961
+ startTime: z13.string().optional().describe(
2962
+ "Start of the period (RFC 3339, e.g. 2026-05-01T00:00:00Z). Defaults to 30 days ago. Mutually exclusive with lastN."
2963
+ ),
2964
+ endTime: z13.string().optional().describe(
2965
+ "End of the period (RFC 3339), exclusive. Defaults to now. Mutually exclusive with lastN."
2966
+ ),
2967
+ bucketSize: z13.enum(["hour", "day", "week", "month", "year"]).optional().describe("Length of each time bucket. Defaults to day."),
2968
+ lastN: z13.number().int().positive().optional().describe(
2969
+ "Return the last N buckets of bucketSize, ending with the current one. Mutually exclusive with startTime/endTime."
2970
+ )
2971
+ },
2972
+ { title: "Get billing history", ...READ_ONLY },
2973
+ async (params) => {
2974
+ const backend = backendFor("billing");
2975
+ if (backend.version === "v1") {
2976
+ return jsonReply2({
2977
+ error: "get-billing is only available on the v2 REST API. Set RUNPOD_REST_VERSION=v2.",
2978
+ status: 501
2979
+ });
2980
+ }
2981
+ const subPath = BILLING_SCOPE_PATH[params.scope ?? "all"];
2982
+ const query = new URLSearchParams();
2983
+ if (params.startTime) query.set("startTime", params.startTime);
2984
+ if (params.endTime) query.set("endTime", params.endTime);
2985
+ if (params.bucketSize) query.set("bucketSize", params.bucketSize);
2986
+ if (params.lastN !== void 0 && !params.startTime && !params.endTime)
2987
+ query.set("lastN", String(params.lastN));
2988
+ const qs = query.toString() ? `?${query.toString()}` : "";
2989
+ const raw = await callRestUrl(`${backend.base}${subPath}${qs}`);
2990
+ return capListResult(
2991
+ backend.unwrap(raw),
2992
+ { limit: params.limit, cursor: params.cursor },
2993
+ { metadata: raw?.metadata }
2994
+ );
2995
+ }
2996
+ );
2997
+ }
2998
+
2999
+ // src/tools.ts
3000
+ function registerTools(server, ctx, deps = {}) {
3001
+ const rt = createToolRuntime(server, ctx, deps);
3002
+ registerCatalogTools(server, rt);
3003
+ registerHubTools(server, rt);
3004
+ registerPublicEndpointTools(server, rt);
3005
+ registerPodTools(server, rt);
3006
+ registerEndpointTools(server, rt);
3007
+ registerEndpointGpuTools(server, rt);
3008
+ registerJobTools(server, rt);
3009
+ registerTemplateTools(server, rt);
3010
+ registerNetworkVolumeTools(server, rt);
3011
+ registerRegistryTools(server, rt);
3012
+ registerBillingTools(server, rt);
3013
+ }
3014
+
3015
+ export {
3016
+ restV1Base,
3017
+ restV2Base,
3018
+ serverlessBase,
3019
+ authedGraphqlBase,
3020
+ restVersionSummary,
3021
+ registerTools
3022
+ };
3023
+ //# sourceMappingURL=chunk-OM6RHPQC.mjs.map