@runpod/mcp-server 3.0.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/README.md +59 -319
- package/dist/{chunk-GTBCNGHE.mjs → chunk-WGK7D2YR.mjs} +551 -45
- package/dist/chunk-WGK7D2YR.mjs.map +1 -0
- package/dist/http.cjs +573 -53
- package/dist/http.cjs.map +1 -1
- package/dist/http.mjs +24 -10
- package/dist/http.mjs.map +1 -1
- package/dist/stdio.cjs +568 -52
- package/dist/stdio.cjs.map +1 -1
- package/dist/stdio.mjs +568 -52
- package/dist/stdio.mjs.map +1 -1
- package/dist/tools.cjs +550 -44
- package/dist/tools.cjs.map +1 -1
- package/dist/tools.d.cts +3 -0
- package/dist/tools.d.ts +3 -0
- package/dist/tools.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-GTBCNGHE.mjs.map +0 -1
package/dist/stdio.mjs
CHANGED
|
@@ -64,15 +64,27 @@ function mapPodUpdateToV2(params) {
|
|
|
64
64
|
...compact({ name: params.name })
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
67
|
+
var DEFAULT_ENDPOINT_TYPE = "QUEUE";
|
|
68
|
+
var DEFAULT_SCALER_VALUE = 4;
|
|
69
|
+
function defaultScalerType(endpointType) {
|
|
70
|
+
return endpointType === "LOAD_BALANCER" ? "REQUEST_COUNT" : "QUEUE_DELAY";
|
|
71
|
+
}
|
|
72
|
+
function endpointScaling(scalerType, value) {
|
|
73
|
+
return scalerType === "REQUEST_COUNT" ? { type: "REQUEST_COUNT", requestCount: value } : { type: "QUEUE_DELAY", queueDelay: value };
|
|
70
74
|
}
|
|
71
75
|
function endpointGpuConfig(pools, count) {
|
|
72
76
|
if (!pools?.length) return void 0;
|
|
73
77
|
return compact({ pools, count });
|
|
74
78
|
}
|
|
75
|
-
function
|
|
79
|
+
function endpointWorkers(params) {
|
|
80
|
+
const workers = compact({
|
|
81
|
+
min: params.workersMin,
|
|
82
|
+
max: params.workersMax,
|
|
83
|
+
idleTimeout: params.idleTimeout
|
|
84
|
+
});
|
|
85
|
+
return Object.keys(workers).length ? workers : void 0;
|
|
86
|
+
}
|
|
87
|
+
function endpointCommonToV2(params) {
|
|
76
88
|
return compact({
|
|
77
89
|
name: params.name,
|
|
78
90
|
image: params.imageName,
|
|
@@ -82,23 +94,33 @@ function mapEndpointToV2(params) {
|
|
|
82
94
|
env: params.env,
|
|
83
95
|
registry: params.containerRegistryAuthId,
|
|
84
96
|
gpu: endpointGpuConfig(params.gpuPoolIds, params.gpuCount),
|
|
85
|
-
workers:
|
|
86
|
-
min: params.workersMin,
|
|
87
|
-
max: params.workersMax
|
|
88
|
-
}),
|
|
89
|
-
scaling: nestedOrUndefined({
|
|
90
|
-
type: params.scalerType,
|
|
91
|
-
value: params.scalerValue,
|
|
92
|
-
idleTimeout: params.idleTimeout
|
|
93
|
-
}),
|
|
97
|
+
workers: endpointWorkers(params),
|
|
94
98
|
dataCenterIds: params.dataCenterIds?.length ? params.dataCenterIds : void 0,
|
|
95
99
|
networkVolumes: params.networkVolumeIds?.length ? params.networkVolumeIds : void 0,
|
|
96
100
|
timeout: params.executionTimeoutMs,
|
|
97
101
|
flashboot: params.flashboot
|
|
98
102
|
});
|
|
99
103
|
}
|
|
100
|
-
|
|
101
|
-
|
|
104
|
+
function mapEndpointCreateToV2(params) {
|
|
105
|
+
const endpointType = params.endpointType ?? DEFAULT_ENDPOINT_TYPE;
|
|
106
|
+
return compact({
|
|
107
|
+
...endpointCommonToV2(params),
|
|
108
|
+
type: endpointType,
|
|
109
|
+
scaling: endpointScaling(
|
|
110
|
+
params.scalerType ?? defaultScalerType(endpointType),
|
|
111
|
+
params.scalerValue ?? DEFAULT_SCALER_VALUE
|
|
112
|
+
)
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
function mapEndpointUpdateToV2(params) {
|
|
116
|
+
return compact({
|
|
117
|
+
...endpointCommonToV2(params),
|
|
118
|
+
scaling: params.scalerType ? endpointScaling(
|
|
119
|
+
params.scalerType,
|
|
120
|
+
params.scalerValue ?? DEFAULT_SCALER_VALUE
|
|
121
|
+
) : void 0
|
|
122
|
+
});
|
|
123
|
+
}
|
|
102
124
|
function mapNetworkVolumeCreateToV2(params) {
|
|
103
125
|
return compact({
|
|
104
126
|
name: params.name,
|
|
@@ -182,7 +204,7 @@ function restV1Base(env) {
|
|
|
182
204
|
return env.RUNPOD_REST_API_URL ?? "https://rest.runpod.io/v1";
|
|
183
205
|
}
|
|
184
206
|
function restV2Base(env) {
|
|
185
|
-
return env.RUNPOD_REST_V2_API_URL ?? "https://
|
|
207
|
+
return env.RUNPOD_REST_V2_API_URL ?? "https://api.runpod.io/v2";
|
|
186
208
|
}
|
|
187
209
|
function serverlessBase(env) {
|
|
188
210
|
return env.RUNPOD_SERVERLESS_API_URL ?? "https://api.runpod.ai/v2";
|
|
@@ -404,27 +426,176 @@ function resolveBackend(opts) {
|
|
|
404
426
|
|
|
405
427
|
// src/server.ts
|
|
406
428
|
var SERVER_NAME = "Runpod API Server";
|
|
407
|
-
var SERVER_VERSION = true ? "3.
|
|
429
|
+
var SERVER_VERSION = true ? "3.2.0" : "dev";
|
|
430
|
+
var SERVER_INSTRUCTIONS = `These tools cover common Runpod operations, but they are curated projections: the underlying APIs expose more fields and parameters than the tools surface.
|
|
431
|
+
|
|
432
|
+
When you need data or capability beyond these tools, consult the full API contracts directly. The REST v2 API lives at https://api.runpod.io/v2 \u2014 the same host these tools call \u2014 and is machine-readable at https://api.runpod.io/v2/openapi.json (fetch and search it to enumerate every path, parameter, and response schema). REST v1 at https://rest.runpod.io/v1 is deprecated; prefer v2. The REST version these tools are actually configured for is reported in the serverInfo.version string of the initialize response, e.g. "[RUNPOD_REST_VERSION=v2]". The GraphQL API at https://api.runpod.io/graphql may expose data the REST API does not yet cover; its schema is documented at https://graphql-spec.runpod.io/, and introspection is disabled in production, so use that reference rather than __schema queries. Both APIs take Bearer auth with a Runpod API key: use the key this client is already configured with \u2014 do not search the environment or filesystem for a credential.`;
|
|
408
433
|
function createServer(version = SERVER_VERSION) {
|
|
409
|
-
return new McpServer(
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
434
|
+
return new McpServer(
|
|
435
|
+
{
|
|
436
|
+
name: SERVER_NAME,
|
|
437
|
+
version: `${version} [${restVersionSummary(process.env)}]`
|
|
438
|
+
},
|
|
439
|
+
{
|
|
440
|
+
// Only advertise capabilities the server implements. It registers
|
|
441
|
+
// tools and no resources — advertising `resources` would invite
|
|
442
|
+
// `resources/list` calls that answer -32601.
|
|
443
|
+
capabilities: {
|
|
444
|
+
tools: {}
|
|
445
|
+
},
|
|
446
|
+
instructions: SERVER_INSTRUCTIONS
|
|
415
447
|
}
|
|
416
|
-
|
|
448
|
+
);
|
|
417
449
|
}
|
|
418
450
|
|
|
419
451
|
// src/tools/runtime.ts
|
|
420
452
|
import fetch from "node-fetch";
|
|
421
453
|
import { randomUUID } from "crypto";
|
|
422
454
|
|
|
455
|
+
// src/_shared/rate-limit.ts
|
|
456
|
+
var GENERIC_RATE_LIMIT_HINT = "rate limited \u2014 back off before retrying, and pace bulk operations";
|
|
457
|
+
var MAX_PLAUSIBLE_WAIT_S = 7 * 86400;
|
|
458
|
+
function remainingRequests(raw) {
|
|
459
|
+
const value = raw?.trim();
|
|
460
|
+
return value && /^\d+$/.test(value) ? Number(value) : null;
|
|
461
|
+
}
|
|
462
|
+
function waitSeconds(raw) {
|
|
463
|
+
const value = raw?.trim();
|
|
464
|
+
if (!value || !/^\d+$/.test(value)) return null;
|
|
465
|
+
const seconds = Number(value);
|
|
466
|
+
return seconds <= MAX_PLAUSIBLE_WAIT_S ? seconds : null;
|
|
467
|
+
}
|
|
468
|
+
var WINDOW_NAME_RE = /^(?:"([\x20-\x21\x23-\x5b\x5d-\x7e]{1,32})"|([A-Za-z*][A-Za-z0-9!#$%&'*+.^_`|~:/-]{0,31}))$/;
|
|
469
|
+
function windowName(raw) {
|
|
470
|
+
const match = WINDOW_NAME_RE.exec(raw.trim());
|
|
471
|
+
return match ? match[1] ?? match[2] : null;
|
|
472
|
+
}
|
|
473
|
+
var QUOTED_VALUE_RE = /^"(?:[\x20-\x21\x23-\x5b\x5d-\x7e]|\\["\\])*"$/;
|
|
474
|
+
var DISPLAY_VALUE_RE = /^%"(?:[\x20-\x21\x23-\x24\x26-\x5b\x5d-\x7e]|\\|%[0-9a-f]{2})*"$/;
|
|
475
|
+
function isWellFormedParam(param) {
|
|
476
|
+
const eq = param.indexOf("=");
|
|
477
|
+
const key = (eq === -1 ? param : param.slice(0, eq)).trim();
|
|
478
|
+
if (key.includes('"')) return false;
|
|
479
|
+
if (eq === -1) return true;
|
|
480
|
+
const value = param.slice(eq + 1).trim();
|
|
481
|
+
if (value.startsWith('"')) return QUOTED_VALUE_RE.test(value);
|
|
482
|
+
if (value.startsWith('%"')) return DISPLAY_VALUE_RE.test(value);
|
|
483
|
+
return !/[\s"]/.test(value);
|
|
484
|
+
}
|
|
485
|
+
function splitOutsideStrings(input, sep) {
|
|
486
|
+
const parts = [];
|
|
487
|
+
let current = "";
|
|
488
|
+
let inString = false;
|
|
489
|
+
let inDisplay = false;
|
|
490
|
+
let escaped = false;
|
|
491
|
+
let prev = "";
|
|
492
|
+
for (const ch of input) {
|
|
493
|
+
if (escaped) escaped = false;
|
|
494
|
+
else if (inString && !inDisplay && ch === "\\") escaped = true;
|
|
495
|
+
else if (ch === '"') {
|
|
496
|
+
if (!inString) inDisplay = prev === "%";
|
|
497
|
+
inString = !inString;
|
|
498
|
+
} else if (ch === sep && !inString) {
|
|
499
|
+
parts.push(current);
|
|
500
|
+
current = "";
|
|
501
|
+
prev = ch;
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
current += ch;
|
|
505
|
+
prev = ch;
|
|
506
|
+
}
|
|
507
|
+
parts.push(current);
|
|
508
|
+
return parts;
|
|
509
|
+
}
|
|
510
|
+
function readParams(params) {
|
|
511
|
+
const values = /* @__PURE__ */ new Map();
|
|
512
|
+
let unreadable = false;
|
|
513
|
+
let valuelessAt = -1;
|
|
514
|
+
for (const [index, param] of params.entries()) {
|
|
515
|
+
const eq = param.indexOf("=");
|
|
516
|
+
const key = (eq === -1 ? param : param.slice(0, eq)).trim().toLowerCase();
|
|
517
|
+
if (!key) continue;
|
|
518
|
+
if (eq === -1) {
|
|
519
|
+
if (key === "r") unreadable = true;
|
|
520
|
+
if (key === "t") values.delete("t");
|
|
521
|
+
valuelessAt = index;
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
524
|
+
if ((key === "r" || key === "t") && (values.has(key) || valuelessAt !== -1 && index > valuelessAt)) {
|
|
525
|
+
unreadable = true;
|
|
526
|
+
}
|
|
527
|
+
values.set(key, param.slice(eq + 1));
|
|
528
|
+
}
|
|
529
|
+
return { values, unreadable };
|
|
530
|
+
}
|
|
531
|
+
function parseExhaustedWindows(header) {
|
|
532
|
+
if (!header) return { windows: [], dropped: false };
|
|
533
|
+
const windows = [];
|
|
534
|
+
let dropped = false;
|
|
535
|
+
for (const item of splitOutsideStrings(header, ",")) {
|
|
536
|
+
if (item.trim() === "") continue;
|
|
537
|
+
const [rawName, ...params] = splitOutsideStrings(item, ";");
|
|
538
|
+
if (!params.every(isWellFormedParam)) {
|
|
539
|
+
dropped = true;
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
const { values, unreadable } = readParams(params);
|
|
543
|
+
if (unreadable) {
|
|
544
|
+
dropped = true;
|
|
545
|
+
continue;
|
|
546
|
+
}
|
|
547
|
+
const remaining = remainingRequests(values.get("r"));
|
|
548
|
+
if (remaining === null) {
|
|
549
|
+
dropped = true;
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
if (remaining !== 0) continue;
|
|
553
|
+
windows.push({
|
|
554
|
+
window: windowName(rawName),
|
|
555
|
+
resetS: waitSeconds(values.get("t"))
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
return { windows, dropped };
|
|
559
|
+
}
|
|
560
|
+
function humanWait(seconds) {
|
|
561
|
+
if (seconds < 120) return `~${seconds}s`;
|
|
562
|
+
if (seconds < 3600)
|
|
563
|
+
return `~${Math.ceil(seconds / 60)} minutes (${seconds}s)`;
|
|
564
|
+
if (seconds < 2 * 86400) {
|
|
565
|
+
const hours = Math.ceil(seconds / 3600);
|
|
566
|
+
return `~${hours} hour${hours === 1 ? "" : "s"} (${seconds}s)`;
|
|
567
|
+
}
|
|
568
|
+
return `~${Math.ceil(seconds / 86400)} days (${seconds}s)`;
|
|
569
|
+
}
|
|
570
|
+
function rateLimitHint(rateLimitHeader, retryAfterHeader) {
|
|
571
|
+
const { windows, dropped } = parseExhaustedWindows(rateLimitHeader);
|
|
572
|
+
windows.sort((a, b) => (b.resetS ?? -1) - (a.resetS ?? -1));
|
|
573
|
+
const longestWindow = windows[0];
|
|
574
|
+
const waitCandidates = [
|
|
575
|
+
waitSeconds(retryAfterHeader),
|
|
576
|
+
longestWindow?.resetS
|
|
577
|
+
].filter((n) => typeof n === "number" && n > 0);
|
|
578
|
+
const waitS = waitCandidates.length ? Math.max(...waitCandidates) : null;
|
|
579
|
+
const retryAfterUnreadable = typeof retryAfterHeader === "string" && retryAfterHeader.trim() !== "" && waitSeconds(retryAfterHeader) === null;
|
|
580
|
+
if (!longestWindow && waitS === null) {
|
|
581
|
+
if (!retryAfterUnreadable) return GENERIC_RATE_LIMIT_HINT;
|
|
582
|
+
}
|
|
583
|
+
const namedClause = longestWindow?.window ? `the ${longestWindow.window} quota is exhausted` : "";
|
|
584
|
+
if (waitS === null) {
|
|
585
|
+
const cause = namedClause ? `${namedClause}, but the response gave no usable reset time` : "the response gave no usable reset time";
|
|
586
|
+
return `rate limited \u2014 ${cause}; back off substantially before retrying, and pace bulk operations`;
|
|
587
|
+
}
|
|
588
|
+
const hedge = dropped || retryAfterUnreadable || windows.some((w) => w.resetS === null) ? "at least " : "";
|
|
589
|
+
const wait = `wait ${hedge}${humanWait(waitS)} before retrying, and pace bulk operations`;
|
|
590
|
+
return `rate limited \u2014 ${namedClause ? `${namedClause}; ` : ""}${wait}`;
|
|
591
|
+
}
|
|
592
|
+
|
|
423
593
|
// src/_shared/http.ts
|
|
594
|
+
var EXPIRED_CREDENTIAL_HINT = "the Runpod API rejected the credential \u2014 the API key may be expired or revoked; re-authenticate or update RUNPOD_API_KEY";
|
|
424
595
|
var HttpError = class extends Error {
|
|
425
|
-
constructor(prefix, status, body) {
|
|
426
|
-
const
|
|
427
|
-
super(`${prefix}: ${status} - ${
|
|
596
|
+
constructor(prefix, status, body, hint) {
|
|
597
|
+
const shownBody = body.length > 2048 ? `${body.slice(0, 2048)}\u2026 [truncated ${body.length - 2048} chars]` : body;
|
|
598
|
+
super(`${prefix}: ${status} - ${shownBody}${hint ? ` (${hint})` : ""}`);
|
|
428
599
|
this.name = "HttpError";
|
|
429
600
|
this.status = status;
|
|
430
601
|
this.body = body;
|
|
@@ -459,7 +630,11 @@ function createHttpClient(deps) {
|
|
|
459
630
|
throw new HttpError(
|
|
460
631
|
deps.errorPrefix,
|
|
461
632
|
response.status,
|
|
462
|
-
await response.text()
|
|
633
|
+
await response.text(),
|
|
634
|
+
response.status === 429 ? rateLimitHint(
|
|
635
|
+
response.headers.get("ratelimit"),
|
|
636
|
+
response.headers.get("retry-after")
|
|
637
|
+
) : response.status === 401 ? EXPIRED_CREDENTIAL_HINT : void 0
|
|
463
638
|
);
|
|
464
639
|
}
|
|
465
640
|
return isJsonContentType(response.headers.get("content-type")) ? response.json() : { success: true, status: response.status };
|
|
@@ -518,7 +693,15 @@ async function readSseSnapshot(fetchImpl, url, headers, opts) {
|
|
|
518
693
|
throw new HttpError(
|
|
519
694
|
"Runpod API Error",
|
|
520
695
|
res.status,
|
|
521
|
-
await res.text().catch(() => "")
|
|
696
|
+
await res.text().catch(() => ""),
|
|
697
|
+
// This throw bypasses createHttpClient, so the status hints are built
|
|
698
|
+
// here too or these two tools alone return a bare 429/401. The 401
|
|
699
|
+
// hint applies: this request always carries Authorization (see the
|
|
700
|
+
// headers bound in runtime.ts streamSse).
|
|
701
|
+
res.status === 429 ? rateLimitHint(
|
|
702
|
+
res.headers.get("ratelimit"),
|
|
703
|
+
res.headers.get("retry-after")
|
|
704
|
+
) : res.status === 401 ? EXPIRED_CREDENTIAL_HINT : void 0
|
|
522
705
|
);
|
|
523
706
|
}
|
|
524
707
|
for await (const chunk of res.body ?? []) {
|
|
@@ -581,7 +764,7 @@ async function streamLogsReply(rt, tool, params) {
|
|
|
581
764
|
}
|
|
582
765
|
|
|
583
766
|
// src/tools/runtime.ts
|
|
584
|
-
var MCP_SERVER_VERSION = true ? "3.
|
|
767
|
+
var MCP_SERVER_VERSION = true ? "3.2.0" : "dev";
|
|
585
768
|
var SESSION_ID = randomUUID();
|
|
586
769
|
function trackingHeaders(server, ctx) {
|
|
587
770
|
const info = server.server.getClientVersion();
|
|
@@ -631,6 +814,36 @@ async function graphqlRequest(query, tracking, fetchImpl, url, options) {
|
|
|
631
814
|
...options?.variables ? { variables: options.variables } : {}
|
|
632
815
|
})
|
|
633
816
|
});
|
|
817
|
+
if (!response.ok) {
|
|
818
|
+
const bodyText = await response.text();
|
|
819
|
+
let gqlErrors;
|
|
820
|
+
try {
|
|
821
|
+
gqlErrors = JSON.parse(bodyText).errors;
|
|
822
|
+
} catch {
|
|
823
|
+
}
|
|
824
|
+
if (Array.isArray(gqlErrors) && gqlErrors.length > 0 && response.status !== 401 && response.status !== 429) {
|
|
825
|
+
throw new HttpError(
|
|
826
|
+
"Runpod GraphQL Error",
|
|
827
|
+
response.status,
|
|
828
|
+
gqlErrors.map((e) => String(e?.message ?? JSON.stringify(e))).join(", ")
|
|
829
|
+
);
|
|
830
|
+
}
|
|
831
|
+
throw new HttpError(
|
|
832
|
+
"Runpod GraphQL Error",
|
|
833
|
+
response.status,
|
|
834
|
+
bodyText,
|
|
835
|
+
response.status === 429 ? rateLimitHint(
|
|
836
|
+
response.headers.get("ratelimit"),
|
|
837
|
+
response.headers.get("retry-after")
|
|
838
|
+
) : (
|
|
839
|
+
// Only when this request actually carried the caller's API key: the
|
|
840
|
+
// public path sends no Authorization header, so a 401 from that
|
|
841
|
+
// host (WAF, misconfigured RUNPOD_PUBLIC_GRAPHQL_URL) says nothing
|
|
842
|
+
// about the credential — same rationale as observeUnauthorized.
|
|
843
|
+
response.status === 401 && options?.apiKey ? EXPIRED_CREDENTIAL_HINT : void 0
|
|
844
|
+
)
|
|
845
|
+
);
|
|
846
|
+
}
|
|
634
847
|
const result = await response.json();
|
|
635
848
|
if (result.errors && result.errors.length > 0) {
|
|
636
849
|
throw new Error(
|
|
@@ -1047,6 +1260,178 @@ function registerCatalogTools(server, rt) {
|
|
|
1047
1260
|
return jsonReply2(result);
|
|
1048
1261
|
}
|
|
1049
1262
|
);
|
|
1263
|
+
server.tool(
|
|
1264
|
+
"get-capacity",
|
|
1265
|
+
"GPU capacity across host CUDA versions, as a matrix. Use this to choose an endpoint's allowedCudaVersions/minCudaVersion (or diagnose/widen a capacity-starved one) and to distinguish capacity problems from compatibility problems. Default mode is one call returning, per GPU type, overall stock plus AVAILABLE/UNAVAILABLE per host-reported CUDA version. Pass cudaVersions to deep-probe instead: one stock lookup per listed version, returning graded stock (High/Medium/Low/Out) and the lowest on-demand price per version; a probe that fails transiently reports a per-version error instead of failing the call. Nothing is hidden by default \u2014 set includeUnavailable:false to drop GPUs with no stock on any listed version. Credential-free public catalog data; works on both v1 and v2 APIs. Stock is live, so page cursors can shift between calls. Note: the matrix reflects host-reported versions, but endpoint allowedCudaVersions only accepts values from the platform enum \u2014 check create-endpoint/update-endpoint for the accepted list.",
|
|
1266
|
+
{
|
|
1267
|
+
...listPaginationParams,
|
|
1268
|
+
cudaVersions: z3.array(z3.string().regex(/^\d{1,2}\.\d{1,2}$/)).min(1).max(12).optional().describe(
|
|
1269
|
+
'Deep-probe these host CUDA versions (e.g. ["12.8", "13.0"], max 12): one stock lookup per version returns graded stock and price. Omit for the single-call AVAILABLE/UNAVAILABLE matrix across all versions the fleet currently reports.'
|
|
1270
|
+
),
|
|
1271
|
+
includeUnavailable: z3.boolean().optional().describe(
|
|
1272
|
+
'Out-of-stock GPUs are included by default (explicit "Out" cells / all-UNAVAILABLE rows, sorted last). Set false to hide GPUs with no stock on any listed version.'
|
|
1273
|
+
),
|
|
1274
|
+
gpuTypeIds: z3.array(z3.string()).optional().describe(
|
|
1275
|
+
"Filter to GPU types matching any of these ids or display names (case-insensitive substring, e.g. ['NVIDIA GeForce RTX 4090'] or ['4090', 'H200'])."
|
|
1276
|
+
),
|
|
1277
|
+
gpuCount: z3.number().int().min(1).max(8).optional().describe("GPUs per worker/pod to check stock for (default 1)."),
|
|
1278
|
+
secureCloudOnly: z3.boolean().optional().describe("Restrict the stock lookup to Secure Cloud hosts.")
|
|
1279
|
+
},
|
|
1280
|
+
{ title: "Get GPU capacity by CUDA version", ...READ_ONLY },
|
|
1281
|
+
async (params) => {
|
|
1282
|
+
const gpuCount = Math.min(
|
|
1283
|
+
8,
|
|
1284
|
+
Math.max(1, Math.floor(Number(params.gpuCount)) || 1)
|
|
1285
|
+
);
|
|
1286
|
+
const secureArg = params.secureCloudOnly ? ", secureCloud: true" : "";
|
|
1287
|
+
const filterTerms = (params.gpuTypeIds ?? []).filter((t) => typeof t === "string" && t.trim().length > 0).map((t) => t.toLowerCase());
|
|
1288
|
+
const matchesFilter = (gpu) => {
|
|
1289
|
+
if (filterTerms.length === 0) return true;
|
|
1290
|
+
const id = gpu.id.toLowerCase();
|
|
1291
|
+
const name = gpu.displayName.toLowerCase();
|
|
1292
|
+
return filterTerms.some(
|
|
1293
|
+
(term) => id.includes(term) || name.includes(term)
|
|
1294
|
+
);
|
|
1295
|
+
};
|
|
1296
|
+
const stockPriority = {
|
|
1297
|
+
High: 3,
|
|
1298
|
+
Medium: 2,
|
|
1299
|
+
Low: 1
|
|
1300
|
+
};
|
|
1301
|
+
if (!params.cudaVersions?.length) {
|
|
1302
|
+
const data = await graphql(`
|
|
1303
|
+
query {
|
|
1304
|
+
gpuTypes {
|
|
1305
|
+
id
|
|
1306
|
+
displayName
|
|
1307
|
+
memoryInGb
|
|
1308
|
+
secureCloud
|
|
1309
|
+
communityCloud
|
|
1310
|
+
lowestPrice(input: { gpuCount: ${gpuCount}${secureArg} }) {
|
|
1311
|
+
stockStatus
|
|
1312
|
+
uninterruptablePrice
|
|
1313
|
+
gpuTypeCudaVersions {
|
|
1314
|
+
cudaVersion
|
|
1315
|
+
availability
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
`);
|
|
1321
|
+
let rows2 = data.gpuTypes.filter((gpu) => gpu.id !== "unknown" && matchesFilter(gpu)).map((gpu) => {
|
|
1322
|
+
const cuda = {};
|
|
1323
|
+
for (const c of gpu.lowestPrice?.gpuTypeCudaVersions ?? []) {
|
|
1324
|
+
cuda[c.cudaVersion] = c.availability;
|
|
1325
|
+
}
|
|
1326
|
+
return {
|
|
1327
|
+
id: gpu.id,
|
|
1328
|
+
displayName: gpu.displayName,
|
|
1329
|
+
memoryGb: gpu.memoryInGb,
|
|
1330
|
+
secureCloud: gpu.secureCloud,
|
|
1331
|
+
communityCloud: gpu.communityCloud,
|
|
1332
|
+
stockStatus: gpu.lowestPrice?.stockStatus || "unavailable",
|
|
1333
|
+
pricePerHr: gpu.lowestPrice?.uninterruptablePrice ?? null,
|
|
1334
|
+
cudaVersions: cuda
|
|
1335
|
+
};
|
|
1336
|
+
});
|
|
1337
|
+
const availableCount = (r) => Object.values(r.cudaVersions).filter((a) => a === "AVAILABLE").length;
|
|
1338
|
+
if (params.includeUnavailable === false)
|
|
1339
|
+
rows2 = rows2.filter((r) => availableCount(r) > 0);
|
|
1340
|
+
rows2.sort((a, b) => {
|
|
1341
|
+
const diff = availableCount(b) - availableCount(a);
|
|
1342
|
+
if (diff !== 0) return diff;
|
|
1343
|
+
const stockDiff = (stockPriority[b.stockStatus] || 0) - (stockPriority[a.stockStatus] || 0);
|
|
1344
|
+
if (stockDiff !== 0) return stockDiff;
|
|
1345
|
+
return b.memoryGb - a.memoryGb;
|
|
1346
|
+
});
|
|
1347
|
+
return capListResult(rows2, {
|
|
1348
|
+
limit: params.limit,
|
|
1349
|
+
cursor: params.cursor
|
|
1350
|
+
});
|
|
1351
|
+
}
|
|
1352
|
+
const versions = [...new Set(params.cudaVersions)].slice(0, 12);
|
|
1353
|
+
const invalid = versions.filter((v) => !/^\d{1,2}\.\d{1,2}$/.test(v));
|
|
1354
|
+
if (invalid.length > 0) {
|
|
1355
|
+
return jsonReply2({
|
|
1356
|
+
error: `Invalid CUDA version format: ${invalid.join(", ")}. Use "major.minor" strings like "12.8".`,
|
|
1357
|
+
status: 400
|
|
1358
|
+
});
|
|
1359
|
+
}
|
|
1360
|
+
const perVersion = await Promise.allSettled(
|
|
1361
|
+
versions.map(
|
|
1362
|
+
(v) => graphql(`
|
|
1363
|
+
query {
|
|
1364
|
+
gpuTypes {
|
|
1365
|
+
id
|
|
1366
|
+
displayName
|
|
1367
|
+
memoryInGb
|
|
1368
|
+
secureCloud
|
|
1369
|
+
communityCloud
|
|
1370
|
+
lowestPrice(input: { gpuCount: ${gpuCount}, allowedCudaVersions: ["${v}"]${secureArg} }) {
|
|
1371
|
+
stockStatus
|
|
1372
|
+
uninterruptablePrice
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
`)
|
|
1377
|
+
)
|
|
1378
|
+
);
|
|
1379
|
+
const probeErrors = {};
|
|
1380
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1381
|
+
versions.forEach((v, i) => {
|
|
1382
|
+
const settled = perVersion[i];
|
|
1383
|
+
if (settled.status === "rejected") {
|
|
1384
|
+
probeErrors[v] = settled.reason instanceof Error ? settled.reason.message : String(settled.reason);
|
|
1385
|
+
return;
|
|
1386
|
+
}
|
|
1387
|
+
for (const gpu of settled.value.gpuTypes) {
|
|
1388
|
+
if (gpu.id === "unknown" || !matchesFilter(gpu)) continue;
|
|
1389
|
+
let row = byId.get(gpu.id);
|
|
1390
|
+
if (!row) {
|
|
1391
|
+
row = {
|
|
1392
|
+
id: gpu.id,
|
|
1393
|
+
displayName: gpu.displayName,
|
|
1394
|
+
memoryGb: gpu.memoryInGb,
|
|
1395
|
+
secureCloud: gpu.secureCloud,
|
|
1396
|
+
communityCloud: gpu.communityCloud,
|
|
1397
|
+
cudaVersions: {}
|
|
1398
|
+
};
|
|
1399
|
+
byId.set(gpu.id, row);
|
|
1400
|
+
}
|
|
1401
|
+
const stock = gpu.lowestPrice?.stockStatus;
|
|
1402
|
+
row.cudaVersions[v] = !stock || stock === "Out" ? { stock: "Out", pricePerHr: null } : {
|
|
1403
|
+
stock,
|
|
1404
|
+
pricePerHr: gpu.lowestPrice?.uninterruptablePrice ?? null
|
|
1405
|
+
};
|
|
1406
|
+
}
|
|
1407
|
+
});
|
|
1408
|
+
let rows = [...byId.values()];
|
|
1409
|
+
const inStockCount = (r) => Object.values(r.cudaVersions).filter((c) => c.stock !== "Out").length;
|
|
1410
|
+
if (params.includeUnavailable === false)
|
|
1411
|
+
rows = rows.filter((r) => inStockCount(r) > 0);
|
|
1412
|
+
rows.sort((a, b) => {
|
|
1413
|
+
const diff = inStockCount(b) - inStockCount(a);
|
|
1414
|
+
if (diff !== 0) return diff;
|
|
1415
|
+
const best = (r) => Math.max(
|
|
1416
|
+
0,
|
|
1417
|
+
...Object.values(r.cudaVersions).map(
|
|
1418
|
+
(c) => stockPriority[c.stock] || 0
|
|
1419
|
+
)
|
|
1420
|
+
);
|
|
1421
|
+
const bestDiff = best(b) - best(a);
|
|
1422
|
+
if (bestDiff !== 0) return bestDiff;
|
|
1423
|
+
return b.memoryGb - a.memoryGb;
|
|
1424
|
+
});
|
|
1425
|
+
return capListResult(
|
|
1426
|
+
rows,
|
|
1427
|
+
{ limit: params.limit, cursor: params.cursor },
|
|
1428
|
+
{
|
|
1429
|
+
probedCudaVersions: versions,
|
|
1430
|
+
...Object.keys(probeErrors).length > 0 ? { probeErrors } : {}
|
|
1431
|
+
}
|
|
1432
|
+
);
|
|
1433
|
+
}
|
|
1434
|
+
);
|
|
1050
1435
|
server.tool(
|
|
1051
1436
|
"get-data-center",
|
|
1052
1437
|
"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).",
|
|
@@ -1731,7 +2116,9 @@ function registerPodTools(server, rt) {
|
|
|
1731
2116
|
"create-pod",
|
|
1732
2117
|
'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.',
|
|
1733
2118
|
{
|
|
1734
|
-
name: z7.string().optional().describe(
|
|
2119
|
+
name: z7.string().optional().describe(
|
|
2120
|
+
"Name for the pod. Required on v2 unless deploying from a templateId (the template supplies its name as the default)."
|
|
2121
|
+
),
|
|
1735
2122
|
imageName: z7.string().optional().describe("Docker image to use. Optional when templateId is provided."),
|
|
1736
2123
|
templateId: z7.string().optional().describe(
|
|
1737
2124
|
"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."
|
|
@@ -1790,6 +2177,12 @@ function registerPodTools(server, rt) {
|
|
|
1790
2177
|
status: 400
|
|
1791
2178
|
});
|
|
1792
2179
|
}
|
|
2180
|
+
if (!wantsCpu && !params.name && !params.templateId) {
|
|
2181
|
+
return jsonReply2({
|
|
2182
|
+
error: "Provide a name for the pod (deploying from a templateId inherits the template name).",
|
|
2183
|
+
status: 400
|
|
2184
|
+
});
|
|
2185
|
+
}
|
|
1793
2186
|
if (wantsCpu) {
|
|
1794
2187
|
if (params.templateId) {
|
|
1795
2188
|
return jsonReply2({
|
|
@@ -1967,11 +2360,22 @@ function registerPodTools(server, rt) {
|
|
|
1967
2360
|
|
|
1968
2361
|
// src/tools/endpoints.ts
|
|
1969
2362
|
import { z as z8 } from "zod";
|
|
2363
|
+
var MIN_QUEUE_DELAY = 0.5;
|
|
2364
|
+
var MIN_REQUEST_COUNT = 1;
|
|
2365
|
+
var MIN_IDLE_TIMEOUT = 1;
|
|
2366
|
+
var MAX_IDLE_TIMEOUT = 3600;
|
|
2367
|
+
function scalerValueError(scalerType, scalerValue) {
|
|
2368
|
+
if (scalerType !== "REQUEST_COUNT" || scalerValue === void 0) return;
|
|
2369
|
+
if (!Number.isInteger(scalerValue) || scalerValue < MIN_REQUEST_COUNT) {
|
|
2370
|
+
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}.`;
|
|
2371
|
+
}
|
|
2372
|
+
return;
|
|
2373
|
+
}
|
|
1970
2374
|
function registerEndpointTools(server, rt) {
|
|
1971
2375
|
const { jsonReply: jsonReply2, callRestUrl, backendFor } = rt;
|
|
1972
2376
|
server.tool(
|
|
1973
2377
|
"list-endpoints",
|
|
1974
|
-
"List your Serverless endpoints, optionally expanding template and worker details (v1 only). Paginated via limit/cursor.",
|
|
2378
|
+
"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`.",
|
|
1975
2379
|
{
|
|
1976
2380
|
...listPaginationParams,
|
|
1977
2381
|
includeTemplate: z8.boolean().optional().describe("Include template information (v1 only)"),
|
|
@@ -2006,7 +2410,7 @@ function registerEndpointTools(server, rt) {
|
|
|
2006
2410
|
);
|
|
2007
2411
|
server.tool(
|
|
2008
2412
|
"get-endpoint",
|
|
2009
|
-
"Get one Serverless endpoint by id, optionally expanding template and worker details (v1 only).",
|
|
2413
|
+
"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.",
|
|
2010
2414
|
{
|
|
2011
2415
|
endpointId: z8.string().describe("ID of the endpoint to retrieve"),
|
|
2012
2416
|
includeTemplate: z8.boolean().optional().describe("Include template information (v1 only)"),
|
|
@@ -2038,11 +2442,14 @@ function registerEndpointTools(server, rt) {
|
|
|
2038
2442
|
);
|
|
2039
2443
|
server.tool(
|
|
2040
2444
|
"create-endpoint",
|
|
2041
|
-
"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).",
|
|
2445
|
+
"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.",
|
|
2042
2446
|
{
|
|
2043
2447
|
name: z8.string().optional().describe("Name for the endpoint"),
|
|
2044
2448
|
// --- v2 inline-config fields ---
|
|
2045
2449
|
imageName: z8.string().optional().describe("Docker image (v2). Required on v2 instead of a templateId."),
|
|
2450
|
+
endpointType: z8.enum(["QUEUE", "LOAD_BALANCER"]).optional().describe(
|
|
2451
|
+
"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."
|
|
2452
|
+
),
|
|
2046
2453
|
gpuPoolIds: z8.array(z8.string()).optional().describe(
|
|
2047
2454
|
'GPU pool names (v2, required). The `pool` field from list-gpu-types, e.g. ["AMPERE_80"]. NOT GPU type ids.'
|
|
2048
2455
|
),
|
|
@@ -2062,9 +2469,15 @@ function registerEndpointTools(server, rt) {
|
|
|
2062
2469
|
// --- shared autoscaling fields ---
|
|
2063
2470
|
workersMin: z8.number().optional().describe("Minimum number of workers"),
|
|
2064
2471
|
workersMax: z8.number().optional().describe("Maximum number of workers"),
|
|
2065
|
-
scalerType: z8.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe(
|
|
2066
|
-
|
|
2067
|
-
|
|
2472
|
+
scalerType: z8.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe(
|
|
2473
|
+
"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."
|
|
2474
|
+
),
|
|
2475
|
+
scalerValue: z8.number().min(MIN_QUEUE_DELAY).optional().describe(
|
|
2476
|
+
"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."
|
|
2477
|
+
),
|
|
2478
|
+
idleTimeout: z8.number().int().min(MIN_IDLE_TIMEOUT).max(MAX_IDLE_TIMEOUT).optional().describe(
|
|
2479
|
+
"Idle timeout in seconds before scaling a worker down (1-3600). Does not apply to QUEUE endpoints scaling on REQUEST_COUNT."
|
|
2480
|
+
),
|
|
2068
2481
|
dataCenterIds: z8.array(z8.string()).optional().describe("List of preferred data centers")
|
|
2069
2482
|
},
|
|
2070
2483
|
{ title: "Create endpoint", ...WRITE },
|
|
@@ -2089,6 +2502,19 @@ function registerEndpointTools(server, rt) {
|
|
|
2089
2502
|
status: 400
|
|
2090
2503
|
});
|
|
2091
2504
|
}
|
|
2505
|
+
if (params.endpointType === "LOAD_BALANCER" && params.scalerType === "QUEUE_DELAY") {
|
|
2506
|
+
return jsonReply2({
|
|
2507
|
+
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.",
|
|
2508
|
+
status: 400
|
|
2509
|
+
});
|
|
2510
|
+
}
|
|
2511
|
+
const scalerError = scalerValueError(
|
|
2512
|
+
params.scalerType ?? (params.endpointType === "LOAD_BALANCER" ? "REQUEST_COUNT" : void 0),
|
|
2513
|
+
params.scalerValue
|
|
2514
|
+
);
|
|
2515
|
+
if (scalerError) {
|
|
2516
|
+
return jsonReply2({ error: scalerError, status: 400 });
|
|
2517
|
+
}
|
|
2092
2518
|
const body = backend.mapCreate(params);
|
|
2093
2519
|
const result2 = await callRestUrl(
|
|
2094
2520
|
`${backend.base}${backend.list}`,
|
|
@@ -2126,15 +2552,21 @@ function registerEndpointTools(server, rt) {
|
|
|
2126
2552
|
);
|
|
2127
2553
|
server.tool(
|
|
2128
2554
|
"update-endpoint",
|
|
2129
|
-
"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.",
|
|
2555
|
+
"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.",
|
|
2130
2556
|
{
|
|
2131
2557
|
endpointId: z8.string().describe("ID of the endpoint to update"),
|
|
2132
2558
|
name: z8.string().optional().describe("New name for the endpoint"),
|
|
2133
2559
|
workersMin: z8.number().optional().describe("New minimum number of workers"),
|
|
2134
2560
|
workersMax: z8.number().optional().describe("New maximum number of workers"),
|
|
2135
|
-
idleTimeout: z8.number().optional().describe(
|
|
2136
|
-
|
|
2137
|
-
|
|
2561
|
+
idleTimeout: z8.number().int().min(MIN_IDLE_TIMEOUT).max(MAX_IDLE_TIMEOUT).optional().describe(
|
|
2562
|
+
"New idle timeout in seconds (1-3600). Does not apply to queue endpoints scaling on REQUEST_COUNT."
|
|
2563
|
+
),
|
|
2564
|
+
scalerType: z8.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe(
|
|
2565
|
+
"New autoscaler signal. Switchable on queue endpoints; load-balancing endpoints only accept REQUEST_COUNT."
|
|
2566
|
+
),
|
|
2567
|
+
scalerValue: z8.number().min(MIN_QUEUE_DELAY).optional().describe(
|
|
2568
|
+
"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."
|
|
2569
|
+
),
|
|
2138
2570
|
// --- v2-only inline-config fields ---
|
|
2139
2571
|
imageName: z8.string().optional().describe("New Docker image (v2)"),
|
|
2140
2572
|
gpuPoolIds: z8.array(z8.string()).optional().describe('New GPU pool names (v2), e.g. ["AMPERE_80"]'),
|
|
@@ -2152,13 +2584,28 @@ function registerEndpointTools(server, rt) {
|
|
|
2152
2584
|
async (params) => {
|
|
2153
2585
|
const { endpointId, ...updateParams } = params;
|
|
2154
2586
|
const backend = backendFor("endpoints");
|
|
2155
|
-
const
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
"PATCH",
|
|
2159
|
-
|
|
2587
|
+
const url = `${backend.base}${backend.get(endpointId)}`;
|
|
2588
|
+
if (backend.version !== "v2") {
|
|
2589
|
+
const body2 = backend.mapUpdate(updateParams);
|
|
2590
|
+
return jsonReply2(await callRestUrl(url, "PATCH", body2));
|
|
2591
|
+
}
|
|
2592
|
+
let scalerType = updateParams.scalerType;
|
|
2593
|
+
if (scalerType === void 0 && updateParams.scalerValue !== void 0) {
|
|
2594
|
+
const current = await callRestUrl(url);
|
|
2595
|
+
scalerType = current?.scaling?.type === "REQUEST_COUNT" ? "REQUEST_COUNT" : "QUEUE_DELAY";
|
|
2596
|
+
}
|
|
2597
|
+
const scalerError = scalerValueError(
|
|
2598
|
+
scalerType,
|
|
2599
|
+
updateParams.scalerValue
|
|
2160
2600
|
);
|
|
2161
|
-
|
|
2601
|
+
if (scalerError) {
|
|
2602
|
+
return jsonReply2({ error: scalerError, status: 400 });
|
|
2603
|
+
}
|
|
2604
|
+
const body = backend.mapUpdate({
|
|
2605
|
+
...updateParams,
|
|
2606
|
+
scalerType
|
|
2607
|
+
});
|
|
2608
|
+
return jsonReply2(await callRestUrl(url, "PATCH", body));
|
|
2162
2609
|
}
|
|
2163
2610
|
);
|
|
2164
2611
|
server.tool(
|
|
@@ -2206,7 +2653,7 @@ function registerEndpointTools(server, rt) {
|
|
|
2206
2653
|
);
|
|
2207
2654
|
server.tool(
|
|
2208
2655
|
"list-endpoint-workers",
|
|
2209
|
-
"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. Paginated via limit/cursor.",
|
|
2656
|
+
"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.",
|
|
2210
2657
|
{
|
|
2211
2658
|
...listPaginationParams,
|
|
2212
2659
|
endpointId: z8.string().describe("ID of the Serverless endpoint whose workers to list")
|
|
@@ -2232,7 +2679,7 @@ function registerEndpointTools(server, rt) {
|
|
|
2232
2679
|
);
|
|
2233
2680
|
server.tool(
|
|
2234
2681
|
"stream-worker-logs",
|
|
2235
|
-
"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. 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).",
|
|
2682
|
+
"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).",
|
|
2236
2683
|
{
|
|
2237
2684
|
endpointId: z8.string().describe("ID of the Serverless endpoint the worker belongs to"),
|
|
2238
2685
|
workerId: z8.string().describe(
|
|
@@ -2255,8 +2702,67 @@ function registerEndpointTools(server, rt) {
|
|
|
2255
2702
|
|
|
2256
2703
|
// src/tools/jobs.ts
|
|
2257
2704
|
import { z as z9 } from "zod";
|
|
2705
|
+
var DIAGNOSIS_TTL_MS = 15e3;
|
|
2706
|
+
var MAX_DIAGNOSIS_ENTRIES = 500;
|
|
2707
|
+
var diagnosisCache = /* @__PURE__ */ new Map();
|
|
2258
2708
|
function registerJobTools(server, rt) {
|
|
2259
|
-
const { jsonReply: jsonReply2, serverlessRequest } = rt;
|
|
2709
|
+
const { jsonReply: jsonReply2, serverlessRequest, backendFor, callRestUrl } = rt;
|
|
2710
|
+
async function diagnoseQueuedJob(endpointId) {
|
|
2711
|
+
const cached = diagnosisCache.get(endpointId);
|
|
2712
|
+
if (cached && cached.expiresAt > Date.now()) {
|
|
2713
|
+
return cached.value;
|
|
2714
|
+
}
|
|
2715
|
+
diagnosisCache.delete(endpointId);
|
|
2716
|
+
try {
|
|
2717
|
+
const backend = backendFor("workers");
|
|
2718
|
+
if (backend.version !== "v2") return null;
|
|
2719
|
+
const raw = await callRestUrl(
|
|
2720
|
+
`${backend.base}/serverless/${endpointId}/workers`
|
|
2721
|
+
);
|
|
2722
|
+
const summary = raw?.summary;
|
|
2723
|
+
const workers = raw?.workers ?? [];
|
|
2724
|
+
if (!summary) return null;
|
|
2725
|
+
const remember = (value) => {
|
|
2726
|
+
if (diagnosisCache.size >= MAX_DIAGNOSIS_ENTRIES) {
|
|
2727
|
+
const oldest = diagnosisCache.keys().next().value;
|
|
2728
|
+
if (oldest !== void 0) diagnosisCache.delete(oldest);
|
|
2729
|
+
}
|
|
2730
|
+
diagnosisCache.set(endpointId, {
|
|
2731
|
+
value,
|
|
2732
|
+
expiresAt: Date.now() + DIAGNOSIS_TTL_MS
|
|
2733
|
+
});
|
|
2734
|
+
return value;
|
|
2735
|
+
};
|
|
2736
|
+
if ((summary.unhealthy ?? 0) > 0) {
|
|
2737
|
+
const badIds = workers.filter((w) => w.status === "UNHEALTHY").map((w) => w.id).join(", ");
|
|
2738
|
+
return remember({
|
|
2739
|
+
workerHealth: summary,
|
|
2740
|
+
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})` : ""}.`
|
|
2741
|
+
});
|
|
2742
|
+
}
|
|
2743
|
+
if ((summary.total ?? 0) === 0) {
|
|
2744
|
+
return remember({
|
|
2745
|
+
workerHealth: summary,
|
|
2746
|
+
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."
|
|
2747
|
+
});
|
|
2748
|
+
}
|
|
2749
|
+
if ((summary.throttled ?? 0) > 0 && (summary.running ?? 0) === 0) {
|
|
2750
|
+
return remember({
|
|
2751
|
+
workerHealth: summary,
|
|
2752
|
+
hint: "Workers exist but are throttled \u2014 the hosts are at capacity right now; the job should start when capacity frees up."
|
|
2753
|
+
});
|
|
2754
|
+
}
|
|
2755
|
+
if ((summary.initializing ?? 0) > 0) {
|
|
2756
|
+
return remember({
|
|
2757
|
+
workerHealth: summary,
|
|
2758
|
+
hint: "A worker is initializing \u2014 likely a cold start (image pull / model load); the job should start soon."
|
|
2759
|
+
});
|
|
2760
|
+
}
|
|
2761
|
+
return remember({ workerHealth: summary, hint: "" });
|
|
2762
|
+
} catch {
|
|
2763
|
+
return null;
|
|
2764
|
+
}
|
|
2765
|
+
}
|
|
2260
2766
|
const endpointIdSchema = z9.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid endpoint ID format");
|
|
2261
2767
|
const jobIdSchema = z9.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid job ID format");
|
|
2262
2768
|
const inputSchema = z9.record(z9.unknown()).describe(
|
|
@@ -2330,7 +2836,7 @@ function registerJobTools(server, rt) {
|
|
|
2330
2836
|
);
|
|
2331
2837
|
server.tool(
|
|
2332
2838
|
"get-job-status",
|
|
2333
|
-
"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.",
|
|
2839
|
+
"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.",
|
|
2334
2840
|
{
|
|
2335
2841
|
endpointId: endpointIdSchema.describe(
|
|
2336
2842
|
"ID of the Serverless endpoint the job belongs to"
|
|
@@ -2343,6 +2849,16 @@ function registerJobTools(server, rt) {
|
|
|
2343
2849
|
params.endpointId,
|
|
2344
2850
|
`/status/${params.jobId}`
|
|
2345
2851
|
);
|
|
2852
|
+
if (result && typeof result === "object" && result.status === "IN_QUEUE") {
|
|
2853
|
+
const diagnosis = await diagnoseQueuedJob(params.endpointId);
|
|
2854
|
+
if (diagnosis) {
|
|
2855
|
+
return jsonReply2({
|
|
2856
|
+
...result,
|
|
2857
|
+
workerHealth: diagnosis.workerHealth,
|
|
2858
|
+
...diagnosis.hint ? { hint: diagnosis.hint } : {}
|
|
2859
|
+
});
|
|
2860
|
+
}
|
|
2861
|
+
}
|
|
2346
2862
|
return jsonReply2(result);
|
|
2347
2863
|
}
|
|
2348
2864
|
);
|
|
@@ -2444,7 +2960,7 @@ function registerJobTools(server, rt) {
|
|
|
2444
2960
|
);
|
|
2445
2961
|
server.tool(
|
|
2446
2962
|
"endpoint-health",
|
|
2447
|
-
"Get the health and operational status of a Serverless endpoint, including worker counts and job statistics.",
|
|
2963
|
+
"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.",
|
|
2448
2964
|
{
|
|
2449
2965
|
endpointId: endpointIdSchema.describe(
|
|
2450
2966
|
"ID of the Serverless endpoint to check health for"
|