@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
|
@@ -2,11 +2,150 @@
|
|
|
2
2
|
import fetch from "node-fetch";
|
|
3
3
|
import { randomUUID } from "crypto";
|
|
4
4
|
|
|
5
|
+
// src/_shared/rate-limit.ts
|
|
6
|
+
var GENERIC_RATE_LIMIT_HINT = "rate limited \u2014 back off before retrying, and pace bulk operations";
|
|
7
|
+
var MAX_PLAUSIBLE_WAIT_S = 7 * 86400;
|
|
8
|
+
function remainingRequests(raw) {
|
|
9
|
+
const value = raw?.trim();
|
|
10
|
+
return value && /^\d+$/.test(value) ? Number(value) : null;
|
|
11
|
+
}
|
|
12
|
+
function waitSeconds(raw) {
|
|
13
|
+
const value = raw?.trim();
|
|
14
|
+
if (!value || !/^\d+$/.test(value)) return null;
|
|
15
|
+
const seconds = Number(value);
|
|
16
|
+
return seconds <= MAX_PLAUSIBLE_WAIT_S ? seconds : null;
|
|
17
|
+
}
|
|
18
|
+
var WINDOW_NAME_RE = /^(?:"([\x20-\x21\x23-\x5b\x5d-\x7e]{1,32})"|([A-Za-z*][A-Za-z0-9!#$%&'*+.^_`|~:/-]{0,31}))$/;
|
|
19
|
+
function windowName(raw) {
|
|
20
|
+
const match = WINDOW_NAME_RE.exec(raw.trim());
|
|
21
|
+
return match ? match[1] ?? match[2] : null;
|
|
22
|
+
}
|
|
23
|
+
var QUOTED_VALUE_RE = /^"(?:[\x20-\x21\x23-\x5b\x5d-\x7e]|\\["\\])*"$/;
|
|
24
|
+
var DISPLAY_VALUE_RE = /^%"(?:[\x20-\x21\x23-\x24\x26-\x5b\x5d-\x7e]|\\|%[0-9a-f]{2})*"$/;
|
|
25
|
+
function isWellFormedParam(param) {
|
|
26
|
+
const eq = param.indexOf("=");
|
|
27
|
+
const key = (eq === -1 ? param : param.slice(0, eq)).trim();
|
|
28
|
+
if (key.includes('"')) return false;
|
|
29
|
+
if (eq === -1) return true;
|
|
30
|
+
const value = param.slice(eq + 1).trim();
|
|
31
|
+
if (value.startsWith('"')) return QUOTED_VALUE_RE.test(value);
|
|
32
|
+
if (value.startsWith('%"')) return DISPLAY_VALUE_RE.test(value);
|
|
33
|
+
return !/[\s"]/.test(value);
|
|
34
|
+
}
|
|
35
|
+
function splitOutsideStrings(input, sep) {
|
|
36
|
+
const parts = [];
|
|
37
|
+
let current = "";
|
|
38
|
+
let inString = false;
|
|
39
|
+
let inDisplay = false;
|
|
40
|
+
let escaped = false;
|
|
41
|
+
let prev = "";
|
|
42
|
+
for (const ch of input) {
|
|
43
|
+
if (escaped) escaped = false;
|
|
44
|
+
else if (inString && !inDisplay && ch === "\\") escaped = true;
|
|
45
|
+
else if (ch === '"') {
|
|
46
|
+
if (!inString) inDisplay = prev === "%";
|
|
47
|
+
inString = !inString;
|
|
48
|
+
} else if (ch === sep && !inString) {
|
|
49
|
+
parts.push(current);
|
|
50
|
+
current = "";
|
|
51
|
+
prev = ch;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
current += ch;
|
|
55
|
+
prev = ch;
|
|
56
|
+
}
|
|
57
|
+
parts.push(current);
|
|
58
|
+
return parts;
|
|
59
|
+
}
|
|
60
|
+
function readParams(params) {
|
|
61
|
+
const values = /* @__PURE__ */ new Map();
|
|
62
|
+
let unreadable = false;
|
|
63
|
+
let valuelessAt = -1;
|
|
64
|
+
for (const [index, param] of params.entries()) {
|
|
65
|
+
const eq = param.indexOf("=");
|
|
66
|
+
const key = (eq === -1 ? param : param.slice(0, eq)).trim().toLowerCase();
|
|
67
|
+
if (!key) continue;
|
|
68
|
+
if (eq === -1) {
|
|
69
|
+
if (key === "r") unreadable = true;
|
|
70
|
+
if (key === "t") values.delete("t");
|
|
71
|
+
valuelessAt = index;
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if ((key === "r" || key === "t") && (values.has(key) || valuelessAt !== -1 && index > valuelessAt)) {
|
|
75
|
+
unreadable = true;
|
|
76
|
+
}
|
|
77
|
+
values.set(key, param.slice(eq + 1));
|
|
78
|
+
}
|
|
79
|
+
return { values, unreadable };
|
|
80
|
+
}
|
|
81
|
+
function parseExhaustedWindows(header) {
|
|
82
|
+
if (!header) return { windows: [], dropped: false };
|
|
83
|
+
const windows = [];
|
|
84
|
+
let dropped = false;
|
|
85
|
+
for (const item of splitOutsideStrings(header, ",")) {
|
|
86
|
+
if (item.trim() === "") continue;
|
|
87
|
+
const [rawName, ...params] = splitOutsideStrings(item, ";");
|
|
88
|
+
if (!params.every(isWellFormedParam)) {
|
|
89
|
+
dropped = true;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const { values, unreadable } = readParams(params);
|
|
93
|
+
if (unreadable) {
|
|
94
|
+
dropped = true;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
const remaining = remainingRequests(values.get("r"));
|
|
98
|
+
if (remaining === null) {
|
|
99
|
+
dropped = true;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (remaining !== 0) continue;
|
|
103
|
+
windows.push({
|
|
104
|
+
window: windowName(rawName),
|
|
105
|
+
resetS: waitSeconds(values.get("t"))
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
return { windows, dropped };
|
|
109
|
+
}
|
|
110
|
+
function humanWait(seconds) {
|
|
111
|
+
if (seconds < 120) return `~${seconds}s`;
|
|
112
|
+
if (seconds < 3600)
|
|
113
|
+
return `~${Math.ceil(seconds / 60)} minutes (${seconds}s)`;
|
|
114
|
+
if (seconds < 2 * 86400) {
|
|
115
|
+
const hours = Math.ceil(seconds / 3600);
|
|
116
|
+
return `~${hours} hour${hours === 1 ? "" : "s"} (${seconds}s)`;
|
|
117
|
+
}
|
|
118
|
+
return `~${Math.ceil(seconds / 86400)} days (${seconds}s)`;
|
|
119
|
+
}
|
|
120
|
+
function rateLimitHint(rateLimitHeader, retryAfterHeader) {
|
|
121
|
+
const { windows, dropped } = parseExhaustedWindows(rateLimitHeader);
|
|
122
|
+
windows.sort((a, b) => (b.resetS ?? -1) - (a.resetS ?? -1));
|
|
123
|
+
const longestWindow = windows[0];
|
|
124
|
+
const waitCandidates = [
|
|
125
|
+
waitSeconds(retryAfterHeader),
|
|
126
|
+
longestWindow?.resetS
|
|
127
|
+
].filter((n) => typeof n === "number" && n > 0);
|
|
128
|
+
const waitS = waitCandidates.length ? Math.max(...waitCandidates) : null;
|
|
129
|
+
const retryAfterUnreadable = typeof retryAfterHeader === "string" && retryAfterHeader.trim() !== "" && waitSeconds(retryAfterHeader) === null;
|
|
130
|
+
if (!longestWindow && waitS === null) {
|
|
131
|
+
if (!retryAfterUnreadable) return GENERIC_RATE_LIMIT_HINT;
|
|
132
|
+
}
|
|
133
|
+
const namedClause = longestWindow?.window ? `the ${longestWindow.window} quota is exhausted` : "";
|
|
134
|
+
if (waitS === null) {
|
|
135
|
+
const cause = namedClause ? `${namedClause}, but the response gave no usable reset time` : "the response gave no usable reset time";
|
|
136
|
+
return `rate limited \u2014 ${cause}; back off substantially before retrying, and pace bulk operations`;
|
|
137
|
+
}
|
|
138
|
+
const hedge = dropped || retryAfterUnreadable || windows.some((w) => w.resetS === null) ? "at least " : "";
|
|
139
|
+
const wait = `wait ${hedge}${humanWait(waitS)} before retrying, and pace bulk operations`;
|
|
140
|
+
return `rate limited \u2014 ${namedClause ? `${namedClause}; ` : ""}${wait}`;
|
|
141
|
+
}
|
|
142
|
+
|
|
5
143
|
// src/_shared/http.ts
|
|
144
|
+
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";
|
|
6
145
|
var HttpError = class extends Error {
|
|
7
|
-
constructor(prefix, status, body) {
|
|
8
|
-
const
|
|
9
|
-
super(`${prefix}: ${status} - ${
|
|
146
|
+
constructor(prefix, status, body, hint) {
|
|
147
|
+
const shownBody = body.length > 2048 ? `${body.slice(0, 2048)}\u2026 [truncated ${body.length - 2048} chars]` : body;
|
|
148
|
+
super(`${prefix}: ${status} - ${shownBody}${hint ? ` (${hint})` : ""}`);
|
|
10
149
|
this.name = "HttpError";
|
|
11
150
|
this.status = status;
|
|
12
151
|
this.body = body;
|
|
@@ -41,7 +180,11 @@ function createHttpClient(deps) {
|
|
|
41
180
|
throw new HttpError(
|
|
42
181
|
deps.errorPrefix,
|
|
43
182
|
response.status,
|
|
44
|
-
await response.text()
|
|
183
|
+
await response.text(),
|
|
184
|
+
response.status === 429 ? rateLimitHint(
|
|
185
|
+
response.headers.get("ratelimit"),
|
|
186
|
+
response.headers.get("retry-after")
|
|
187
|
+
) : response.status === 401 ? EXPIRED_CREDENTIAL_HINT : void 0
|
|
45
188
|
);
|
|
46
189
|
}
|
|
47
190
|
return isJsonContentType(response.headers.get("content-type")) ? response.json() : { success: true, status: response.status };
|
|
@@ -100,7 +243,15 @@ async function readSseSnapshot(fetchImpl, url, headers, opts) {
|
|
|
100
243
|
throw new HttpError(
|
|
101
244
|
"Runpod API Error",
|
|
102
245
|
res.status,
|
|
103
|
-
await res.text().catch(() => "")
|
|
246
|
+
await res.text().catch(() => ""),
|
|
247
|
+
// This throw bypasses createHttpClient, so the status hints are built
|
|
248
|
+
// here too or these two tools alone return a bare 429/401. The 401
|
|
249
|
+
// hint applies: this request always carries Authorization (see the
|
|
250
|
+
// headers bound in runtime.ts streamSse).
|
|
251
|
+
res.status === 429 ? rateLimitHint(
|
|
252
|
+
res.headers.get("ratelimit"),
|
|
253
|
+
res.headers.get("retry-after")
|
|
254
|
+
) : res.status === 401 ? EXPIRED_CREDENTIAL_HINT : void 0
|
|
104
255
|
);
|
|
105
256
|
}
|
|
106
257
|
for await (const chunk of res.body ?? []) {
|
|
@@ -219,15 +370,27 @@ function mapPodUpdateToV2(params) {
|
|
|
219
370
|
...compact({ name: params.name })
|
|
220
371
|
};
|
|
221
372
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
373
|
+
var DEFAULT_ENDPOINT_TYPE = "QUEUE";
|
|
374
|
+
var DEFAULT_SCALER_VALUE = 4;
|
|
375
|
+
function defaultScalerType(endpointType) {
|
|
376
|
+
return endpointType === "LOAD_BALANCER" ? "REQUEST_COUNT" : "QUEUE_DELAY";
|
|
377
|
+
}
|
|
378
|
+
function endpointScaling(scalerType, value) {
|
|
379
|
+
return scalerType === "REQUEST_COUNT" ? { type: "REQUEST_COUNT", requestCount: value } : { type: "QUEUE_DELAY", queueDelay: value };
|
|
225
380
|
}
|
|
226
381
|
function endpointGpuConfig(pools, count) {
|
|
227
382
|
if (!pools?.length) return void 0;
|
|
228
383
|
return compact({ pools, count });
|
|
229
384
|
}
|
|
230
|
-
function
|
|
385
|
+
function endpointWorkers(params) {
|
|
386
|
+
const workers = compact({
|
|
387
|
+
min: params.workersMin,
|
|
388
|
+
max: params.workersMax,
|
|
389
|
+
idleTimeout: params.idleTimeout
|
|
390
|
+
});
|
|
391
|
+
return Object.keys(workers).length ? workers : void 0;
|
|
392
|
+
}
|
|
393
|
+
function endpointCommonToV2(params) {
|
|
231
394
|
return compact({
|
|
232
395
|
name: params.name,
|
|
233
396
|
image: params.imageName,
|
|
@@ -237,23 +400,33 @@ function mapEndpointToV2(params) {
|
|
|
237
400
|
env: params.env,
|
|
238
401
|
registry: params.containerRegistryAuthId,
|
|
239
402
|
gpu: endpointGpuConfig(params.gpuPoolIds, params.gpuCount),
|
|
240
|
-
workers:
|
|
241
|
-
min: params.workersMin,
|
|
242
|
-
max: params.workersMax
|
|
243
|
-
}),
|
|
244
|
-
scaling: nestedOrUndefined({
|
|
245
|
-
type: params.scalerType,
|
|
246
|
-
value: params.scalerValue,
|
|
247
|
-
idleTimeout: params.idleTimeout
|
|
248
|
-
}),
|
|
403
|
+
workers: endpointWorkers(params),
|
|
249
404
|
dataCenterIds: params.dataCenterIds?.length ? params.dataCenterIds : void 0,
|
|
250
405
|
networkVolumes: params.networkVolumeIds?.length ? params.networkVolumeIds : void 0,
|
|
251
406
|
timeout: params.executionTimeoutMs,
|
|
252
407
|
flashboot: params.flashboot
|
|
253
408
|
});
|
|
254
409
|
}
|
|
255
|
-
|
|
256
|
-
|
|
410
|
+
function mapEndpointCreateToV2(params) {
|
|
411
|
+
const endpointType = params.endpointType ?? DEFAULT_ENDPOINT_TYPE;
|
|
412
|
+
return compact({
|
|
413
|
+
...endpointCommonToV2(params),
|
|
414
|
+
type: endpointType,
|
|
415
|
+
scaling: endpointScaling(
|
|
416
|
+
params.scalerType ?? defaultScalerType(endpointType),
|
|
417
|
+
params.scalerValue ?? DEFAULT_SCALER_VALUE
|
|
418
|
+
)
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
function mapEndpointUpdateToV2(params) {
|
|
422
|
+
return compact({
|
|
423
|
+
...endpointCommonToV2(params),
|
|
424
|
+
scaling: params.scalerType ? endpointScaling(
|
|
425
|
+
params.scalerType,
|
|
426
|
+
params.scalerValue ?? DEFAULT_SCALER_VALUE
|
|
427
|
+
) : void 0
|
|
428
|
+
});
|
|
429
|
+
}
|
|
257
430
|
function mapNetworkVolumeCreateToV2(params) {
|
|
258
431
|
return compact({
|
|
259
432
|
name: params.name,
|
|
@@ -337,7 +510,7 @@ function restV1Base(env) {
|
|
|
337
510
|
return env.RUNPOD_REST_API_URL ?? "https://rest.runpod.io/v1";
|
|
338
511
|
}
|
|
339
512
|
function restV2Base(env) {
|
|
340
|
-
return env.RUNPOD_REST_V2_API_URL ?? "https://
|
|
513
|
+
return env.RUNPOD_REST_V2_API_URL ?? "https://api.runpod.io/v2";
|
|
341
514
|
}
|
|
342
515
|
function serverlessBase(env) {
|
|
343
516
|
return env.RUNPOD_SERVERLESS_API_URL ?? "https://api.runpod.ai/v2";
|
|
@@ -508,7 +681,7 @@ function resolveBackend(opts) {
|
|
|
508
681
|
}
|
|
509
682
|
|
|
510
683
|
// src/tools/runtime.ts
|
|
511
|
-
var MCP_SERVER_VERSION = true ? "3.
|
|
684
|
+
var MCP_SERVER_VERSION = true ? "3.2.0" : "dev";
|
|
512
685
|
var SESSION_ID = randomUUID();
|
|
513
686
|
function trackingHeaders(server, ctx) {
|
|
514
687
|
const info = server.server.getClientVersion();
|
|
@@ -558,6 +731,36 @@ async function graphqlRequest(query, tracking, fetchImpl, url, options) {
|
|
|
558
731
|
...options?.variables ? { variables: options.variables } : {}
|
|
559
732
|
})
|
|
560
733
|
});
|
|
734
|
+
if (!response.ok) {
|
|
735
|
+
const bodyText = await response.text();
|
|
736
|
+
let gqlErrors;
|
|
737
|
+
try {
|
|
738
|
+
gqlErrors = JSON.parse(bodyText).errors;
|
|
739
|
+
} catch {
|
|
740
|
+
}
|
|
741
|
+
if (Array.isArray(gqlErrors) && gqlErrors.length > 0 && response.status !== 401 && response.status !== 429) {
|
|
742
|
+
throw new HttpError(
|
|
743
|
+
"Runpod GraphQL Error",
|
|
744
|
+
response.status,
|
|
745
|
+
gqlErrors.map((e) => String(e?.message ?? JSON.stringify(e))).join(", ")
|
|
746
|
+
);
|
|
747
|
+
}
|
|
748
|
+
throw new HttpError(
|
|
749
|
+
"Runpod GraphQL Error",
|
|
750
|
+
response.status,
|
|
751
|
+
bodyText,
|
|
752
|
+
response.status === 429 ? rateLimitHint(
|
|
753
|
+
response.headers.get("ratelimit"),
|
|
754
|
+
response.headers.get("retry-after")
|
|
755
|
+
) : (
|
|
756
|
+
// Only when this request actually carried the caller's API key: the
|
|
757
|
+
// public path sends no Authorization header, so a 401 from that
|
|
758
|
+
// host (WAF, misconfigured RUNPOD_PUBLIC_GRAPHQL_URL) says nothing
|
|
759
|
+
// about the credential — same rationale as observeUnauthorized.
|
|
760
|
+
response.status === 401 && options?.apiKey ? EXPIRED_CREDENTIAL_HINT : void 0
|
|
761
|
+
)
|
|
762
|
+
);
|
|
763
|
+
}
|
|
561
764
|
const result = await response.json();
|
|
562
765
|
if (result.errors && result.errors.length > 0) {
|
|
563
766
|
throw new Error(
|
|
@@ -974,6 +1177,178 @@ function registerCatalogTools(server, rt) {
|
|
|
974
1177
|
return jsonReply2(result);
|
|
975
1178
|
}
|
|
976
1179
|
);
|
|
1180
|
+
server.tool(
|
|
1181
|
+
"get-capacity",
|
|
1182
|
+
"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.",
|
|
1183
|
+
{
|
|
1184
|
+
...listPaginationParams,
|
|
1185
|
+
cudaVersions: z3.array(z3.string().regex(/^\d{1,2}\.\d{1,2}$/)).min(1).max(12).optional().describe(
|
|
1186
|
+
'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.'
|
|
1187
|
+
),
|
|
1188
|
+
includeUnavailable: z3.boolean().optional().describe(
|
|
1189
|
+
'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.'
|
|
1190
|
+
),
|
|
1191
|
+
gpuTypeIds: z3.array(z3.string()).optional().describe(
|
|
1192
|
+
"Filter to GPU types matching any of these ids or display names (case-insensitive substring, e.g. ['NVIDIA GeForce RTX 4090'] or ['4090', 'H200'])."
|
|
1193
|
+
),
|
|
1194
|
+
gpuCount: z3.number().int().min(1).max(8).optional().describe("GPUs per worker/pod to check stock for (default 1)."),
|
|
1195
|
+
secureCloudOnly: z3.boolean().optional().describe("Restrict the stock lookup to Secure Cloud hosts.")
|
|
1196
|
+
},
|
|
1197
|
+
{ title: "Get GPU capacity by CUDA version", ...READ_ONLY },
|
|
1198
|
+
async (params) => {
|
|
1199
|
+
const gpuCount = Math.min(
|
|
1200
|
+
8,
|
|
1201
|
+
Math.max(1, Math.floor(Number(params.gpuCount)) || 1)
|
|
1202
|
+
);
|
|
1203
|
+
const secureArg = params.secureCloudOnly ? ", secureCloud: true" : "";
|
|
1204
|
+
const filterTerms = (params.gpuTypeIds ?? []).filter((t) => typeof t === "string" && t.trim().length > 0).map((t) => t.toLowerCase());
|
|
1205
|
+
const matchesFilter = (gpu) => {
|
|
1206
|
+
if (filterTerms.length === 0) return true;
|
|
1207
|
+
const id = gpu.id.toLowerCase();
|
|
1208
|
+
const name = gpu.displayName.toLowerCase();
|
|
1209
|
+
return filterTerms.some(
|
|
1210
|
+
(term) => id.includes(term) || name.includes(term)
|
|
1211
|
+
);
|
|
1212
|
+
};
|
|
1213
|
+
const stockPriority = {
|
|
1214
|
+
High: 3,
|
|
1215
|
+
Medium: 2,
|
|
1216
|
+
Low: 1
|
|
1217
|
+
};
|
|
1218
|
+
if (!params.cudaVersions?.length) {
|
|
1219
|
+
const data = await graphql(`
|
|
1220
|
+
query {
|
|
1221
|
+
gpuTypes {
|
|
1222
|
+
id
|
|
1223
|
+
displayName
|
|
1224
|
+
memoryInGb
|
|
1225
|
+
secureCloud
|
|
1226
|
+
communityCloud
|
|
1227
|
+
lowestPrice(input: { gpuCount: ${gpuCount}${secureArg} }) {
|
|
1228
|
+
stockStatus
|
|
1229
|
+
uninterruptablePrice
|
|
1230
|
+
gpuTypeCudaVersions {
|
|
1231
|
+
cudaVersion
|
|
1232
|
+
availability
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
`);
|
|
1238
|
+
let rows2 = data.gpuTypes.filter((gpu) => gpu.id !== "unknown" && matchesFilter(gpu)).map((gpu) => {
|
|
1239
|
+
const cuda = {};
|
|
1240
|
+
for (const c of gpu.lowestPrice?.gpuTypeCudaVersions ?? []) {
|
|
1241
|
+
cuda[c.cudaVersion] = c.availability;
|
|
1242
|
+
}
|
|
1243
|
+
return {
|
|
1244
|
+
id: gpu.id,
|
|
1245
|
+
displayName: gpu.displayName,
|
|
1246
|
+
memoryGb: gpu.memoryInGb,
|
|
1247
|
+
secureCloud: gpu.secureCloud,
|
|
1248
|
+
communityCloud: gpu.communityCloud,
|
|
1249
|
+
stockStatus: gpu.lowestPrice?.stockStatus || "unavailable",
|
|
1250
|
+
pricePerHr: gpu.lowestPrice?.uninterruptablePrice ?? null,
|
|
1251
|
+
cudaVersions: cuda
|
|
1252
|
+
};
|
|
1253
|
+
});
|
|
1254
|
+
const availableCount = (r) => Object.values(r.cudaVersions).filter((a) => a === "AVAILABLE").length;
|
|
1255
|
+
if (params.includeUnavailable === false)
|
|
1256
|
+
rows2 = rows2.filter((r) => availableCount(r) > 0);
|
|
1257
|
+
rows2.sort((a, b) => {
|
|
1258
|
+
const diff = availableCount(b) - availableCount(a);
|
|
1259
|
+
if (diff !== 0) return diff;
|
|
1260
|
+
const stockDiff = (stockPriority[b.stockStatus] || 0) - (stockPriority[a.stockStatus] || 0);
|
|
1261
|
+
if (stockDiff !== 0) return stockDiff;
|
|
1262
|
+
return b.memoryGb - a.memoryGb;
|
|
1263
|
+
});
|
|
1264
|
+
return capListResult(rows2, {
|
|
1265
|
+
limit: params.limit,
|
|
1266
|
+
cursor: params.cursor
|
|
1267
|
+
});
|
|
1268
|
+
}
|
|
1269
|
+
const versions = [...new Set(params.cudaVersions)].slice(0, 12);
|
|
1270
|
+
const invalid = versions.filter((v) => !/^\d{1,2}\.\d{1,2}$/.test(v));
|
|
1271
|
+
if (invalid.length > 0) {
|
|
1272
|
+
return jsonReply2({
|
|
1273
|
+
error: `Invalid CUDA version format: ${invalid.join(", ")}. Use "major.minor" strings like "12.8".`,
|
|
1274
|
+
status: 400
|
|
1275
|
+
});
|
|
1276
|
+
}
|
|
1277
|
+
const perVersion = await Promise.allSettled(
|
|
1278
|
+
versions.map(
|
|
1279
|
+
(v) => graphql(`
|
|
1280
|
+
query {
|
|
1281
|
+
gpuTypes {
|
|
1282
|
+
id
|
|
1283
|
+
displayName
|
|
1284
|
+
memoryInGb
|
|
1285
|
+
secureCloud
|
|
1286
|
+
communityCloud
|
|
1287
|
+
lowestPrice(input: { gpuCount: ${gpuCount}, allowedCudaVersions: ["${v}"]${secureArg} }) {
|
|
1288
|
+
stockStatus
|
|
1289
|
+
uninterruptablePrice
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
`)
|
|
1294
|
+
)
|
|
1295
|
+
);
|
|
1296
|
+
const probeErrors = {};
|
|
1297
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1298
|
+
versions.forEach((v, i) => {
|
|
1299
|
+
const settled = perVersion[i];
|
|
1300
|
+
if (settled.status === "rejected") {
|
|
1301
|
+
probeErrors[v] = settled.reason instanceof Error ? settled.reason.message : String(settled.reason);
|
|
1302
|
+
return;
|
|
1303
|
+
}
|
|
1304
|
+
for (const gpu of settled.value.gpuTypes) {
|
|
1305
|
+
if (gpu.id === "unknown" || !matchesFilter(gpu)) continue;
|
|
1306
|
+
let row = byId.get(gpu.id);
|
|
1307
|
+
if (!row) {
|
|
1308
|
+
row = {
|
|
1309
|
+
id: gpu.id,
|
|
1310
|
+
displayName: gpu.displayName,
|
|
1311
|
+
memoryGb: gpu.memoryInGb,
|
|
1312
|
+
secureCloud: gpu.secureCloud,
|
|
1313
|
+
communityCloud: gpu.communityCloud,
|
|
1314
|
+
cudaVersions: {}
|
|
1315
|
+
};
|
|
1316
|
+
byId.set(gpu.id, row);
|
|
1317
|
+
}
|
|
1318
|
+
const stock = gpu.lowestPrice?.stockStatus;
|
|
1319
|
+
row.cudaVersions[v] = !stock || stock === "Out" ? { stock: "Out", pricePerHr: null } : {
|
|
1320
|
+
stock,
|
|
1321
|
+
pricePerHr: gpu.lowestPrice?.uninterruptablePrice ?? null
|
|
1322
|
+
};
|
|
1323
|
+
}
|
|
1324
|
+
});
|
|
1325
|
+
let rows = [...byId.values()];
|
|
1326
|
+
const inStockCount = (r) => Object.values(r.cudaVersions).filter((c) => c.stock !== "Out").length;
|
|
1327
|
+
if (params.includeUnavailable === false)
|
|
1328
|
+
rows = rows.filter((r) => inStockCount(r) > 0);
|
|
1329
|
+
rows.sort((a, b) => {
|
|
1330
|
+
const diff = inStockCount(b) - inStockCount(a);
|
|
1331
|
+
if (diff !== 0) return diff;
|
|
1332
|
+
const best = (r) => Math.max(
|
|
1333
|
+
0,
|
|
1334
|
+
...Object.values(r.cudaVersions).map(
|
|
1335
|
+
(c) => stockPriority[c.stock] || 0
|
|
1336
|
+
)
|
|
1337
|
+
);
|
|
1338
|
+
const bestDiff = best(b) - best(a);
|
|
1339
|
+
if (bestDiff !== 0) return bestDiff;
|
|
1340
|
+
return b.memoryGb - a.memoryGb;
|
|
1341
|
+
});
|
|
1342
|
+
return capListResult(
|
|
1343
|
+
rows,
|
|
1344
|
+
{ limit: params.limit, cursor: params.cursor },
|
|
1345
|
+
{
|
|
1346
|
+
probedCudaVersions: versions,
|
|
1347
|
+
...Object.keys(probeErrors).length > 0 ? { probeErrors } : {}
|
|
1348
|
+
}
|
|
1349
|
+
);
|
|
1350
|
+
}
|
|
1351
|
+
);
|
|
977
1352
|
server.tool(
|
|
978
1353
|
"get-data-center",
|
|
979
1354
|
"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).",
|
|
@@ -1658,7 +2033,9 @@ function registerPodTools(server, rt) {
|
|
|
1658
2033
|
"create-pod",
|
|
1659
2034
|
'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.',
|
|
1660
2035
|
{
|
|
1661
|
-
name: z7.string().optional().describe(
|
|
2036
|
+
name: z7.string().optional().describe(
|
|
2037
|
+
"Name for the pod. Required on v2 unless deploying from a templateId (the template supplies its name as the default)."
|
|
2038
|
+
),
|
|
1662
2039
|
imageName: z7.string().optional().describe("Docker image to use. Optional when templateId is provided."),
|
|
1663
2040
|
templateId: z7.string().optional().describe(
|
|
1664
2041
|
"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."
|
|
@@ -1717,6 +2094,12 @@ function registerPodTools(server, rt) {
|
|
|
1717
2094
|
status: 400
|
|
1718
2095
|
});
|
|
1719
2096
|
}
|
|
2097
|
+
if (!wantsCpu && !params.name && !params.templateId) {
|
|
2098
|
+
return jsonReply2({
|
|
2099
|
+
error: "Provide a name for the pod (deploying from a templateId inherits the template name).",
|
|
2100
|
+
status: 400
|
|
2101
|
+
});
|
|
2102
|
+
}
|
|
1720
2103
|
if (wantsCpu) {
|
|
1721
2104
|
if (params.templateId) {
|
|
1722
2105
|
return jsonReply2({
|
|
@@ -1894,11 +2277,22 @@ function registerPodTools(server, rt) {
|
|
|
1894
2277
|
|
|
1895
2278
|
// src/tools/endpoints.ts
|
|
1896
2279
|
import { z as z8 } from "zod";
|
|
2280
|
+
var MIN_QUEUE_DELAY = 0.5;
|
|
2281
|
+
var MIN_REQUEST_COUNT = 1;
|
|
2282
|
+
var MIN_IDLE_TIMEOUT = 1;
|
|
2283
|
+
var MAX_IDLE_TIMEOUT = 3600;
|
|
2284
|
+
function scalerValueError(scalerType, scalerValue) {
|
|
2285
|
+
if (scalerType !== "REQUEST_COUNT" || scalerValue === void 0) return;
|
|
2286
|
+
if (!Number.isInteger(scalerValue) || scalerValue < MIN_REQUEST_COUNT) {
|
|
2287
|
+
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}.`;
|
|
2288
|
+
}
|
|
2289
|
+
return;
|
|
2290
|
+
}
|
|
1897
2291
|
function registerEndpointTools(server, rt) {
|
|
1898
2292
|
const { jsonReply: jsonReply2, callRestUrl, backendFor } = rt;
|
|
1899
2293
|
server.tool(
|
|
1900
2294
|
"list-endpoints",
|
|
1901
|
-
"List your Serverless endpoints, optionally expanding template and worker details (v1 only). Paginated via limit/cursor.",
|
|
2295
|
+
"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`.",
|
|
1902
2296
|
{
|
|
1903
2297
|
...listPaginationParams,
|
|
1904
2298
|
includeTemplate: z8.boolean().optional().describe("Include template information (v1 only)"),
|
|
@@ -1933,7 +2327,7 @@ function registerEndpointTools(server, rt) {
|
|
|
1933
2327
|
);
|
|
1934
2328
|
server.tool(
|
|
1935
2329
|
"get-endpoint",
|
|
1936
|
-
"Get one Serverless endpoint by id, optionally expanding template and worker details (v1 only).",
|
|
2330
|
+
"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.",
|
|
1937
2331
|
{
|
|
1938
2332
|
endpointId: z8.string().describe("ID of the endpoint to retrieve"),
|
|
1939
2333
|
includeTemplate: z8.boolean().optional().describe("Include template information (v1 only)"),
|
|
@@ -1965,11 +2359,14 @@ function registerEndpointTools(server, rt) {
|
|
|
1965
2359
|
);
|
|
1966
2360
|
server.tool(
|
|
1967
2361
|
"create-endpoint",
|
|
1968
|
-
"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).",
|
|
2362
|
+
"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.",
|
|
1969
2363
|
{
|
|
1970
2364
|
name: z8.string().optional().describe("Name for the endpoint"),
|
|
1971
2365
|
// --- v2 inline-config fields ---
|
|
1972
2366
|
imageName: z8.string().optional().describe("Docker image (v2). Required on v2 instead of a templateId."),
|
|
2367
|
+
endpointType: z8.enum(["QUEUE", "LOAD_BALANCER"]).optional().describe(
|
|
2368
|
+
"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."
|
|
2369
|
+
),
|
|
1973
2370
|
gpuPoolIds: z8.array(z8.string()).optional().describe(
|
|
1974
2371
|
'GPU pool names (v2, required). The `pool` field from list-gpu-types, e.g. ["AMPERE_80"]. NOT GPU type ids.'
|
|
1975
2372
|
),
|
|
@@ -1989,9 +2386,15 @@ function registerEndpointTools(server, rt) {
|
|
|
1989
2386
|
// --- shared autoscaling fields ---
|
|
1990
2387
|
workersMin: z8.number().optional().describe("Minimum number of workers"),
|
|
1991
2388
|
workersMax: z8.number().optional().describe("Maximum number of workers"),
|
|
1992
|
-
scalerType: z8.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe(
|
|
1993
|
-
|
|
1994
|
-
|
|
2389
|
+
scalerType: z8.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe(
|
|
2390
|
+
"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."
|
|
2391
|
+
),
|
|
2392
|
+
scalerValue: z8.number().min(MIN_QUEUE_DELAY).optional().describe(
|
|
2393
|
+
"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."
|
|
2394
|
+
),
|
|
2395
|
+
idleTimeout: z8.number().int().min(MIN_IDLE_TIMEOUT).max(MAX_IDLE_TIMEOUT).optional().describe(
|
|
2396
|
+
"Idle timeout in seconds before scaling a worker down (1-3600). Does not apply to QUEUE endpoints scaling on REQUEST_COUNT."
|
|
2397
|
+
),
|
|
1995
2398
|
dataCenterIds: z8.array(z8.string()).optional().describe("List of preferred data centers")
|
|
1996
2399
|
},
|
|
1997
2400
|
{ title: "Create endpoint", ...WRITE },
|
|
@@ -2016,6 +2419,19 @@ function registerEndpointTools(server, rt) {
|
|
|
2016
2419
|
status: 400
|
|
2017
2420
|
});
|
|
2018
2421
|
}
|
|
2422
|
+
if (params.endpointType === "LOAD_BALANCER" && params.scalerType === "QUEUE_DELAY") {
|
|
2423
|
+
return jsonReply2({
|
|
2424
|
+
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.",
|
|
2425
|
+
status: 400
|
|
2426
|
+
});
|
|
2427
|
+
}
|
|
2428
|
+
const scalerError = scalerValueError(
|
|
2429
|
+
params.scalerType ?? (params.endpointType === "LOAD_BALANCER" ? "REQUEST_COUNT" : void 0),
|
|
2430
|
+
params.scalerValue
|
|
2431
|
+
);
|
|
2432
|
+
if (scalerError) {
|
|
2433
|
+
return jsonReply2({ error: scalerError, status: 400 });
|
|
2434
|
+
}
|
|
2019
2435
|
const body = backend.mapCreate(params);
|
|
2020
2436
|
const result2 = await callRestUrl(
|
|
2021
2437
|
`${backend.base}${backend.list}`,
|
|
@@ -2053,15 +2469,21 @@ function registerEndpointTools(server, rt) {
|
|
|
2053
2469
|
);
|
|
2054
2470
|
server.tool(
|
|
2055
2471
|
"update-endpoint",
|
|
2056
|
-
"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.",
|
|
2472
|
+
"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.",
|
|
2057
2473
|
{
|
|
2058
2474
|
endpointId: z8.string().describe("ID of the endpoint to update"),
|
|
2059
2475
|
name: z8.string().optional().describe("New name for the endpoint"),
|
|
2060
2476
|
workersMin: z8.number().optional().describe("New minimum number of workers"),
|
|
2061
2477
|
workersMax: z8.number().optional().describe("New maximum number of workers"),
|
|
2062
|
-
idleTimeout: z8.number().optional().describe(
|
|
2063
|
-
|
|
2064
|
-
|
|
2478
|
+
idleTimeout: z8.number().int().min(MIN_IDLE_TIMEOUT).max(MAX_IDLE_TIMEOUT).optional().describe(
|
|
2479
|
+
"New idle timeout in seconds (1-3600). Does not apply to queue endpoints scaling on REQUEST_COUNT."
|
|
2480
|
+
),
|
|
2481
|
+
scalerType: z8.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe(
|
|
2482
|
+
"New autoscaler signal. Switchable on queue endpoints; load-balancing endpoints only accept REQUEST_COUNT."
|
|
2483
|
+
),
|
|
2484
|
+
scalerValue: z8.number().min(MIN_QUEUE_DELAY).optional().describe(
|
|
2485
|
+
"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."
|
|
2486
|
+
),
|
|
2065
2487
|
// --- v2-only inline-config fields ---
|
|
2066
2488
|
imageName: z8.string().optional().describe("New Docker image (v2)"),
|
|
2067
2489
|
gpuPoolIds: z8.array(z8.string()).optional().describe('New GPU pool names (v2), e.g. ["AMPERE_80"]'),
|
|
@@ -2079,13 +2501,28 @@ function registerEndpointTools(server, rt) {
|
|
|
2079
2501
|
async (params) => {
|
|
2080
2502
|
const { endpointId, ...updateParams } = params;
|
|
2081
2503
|
const backend = backendFor("endpoints");
|
|
2082
|
-
const
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
"PATCH",
|
|
2086
|
-
|
|
2504
|
+
const url = `${backend.base}${backend.get(endpointId)}`;
|
|
2505
|
+
if (backend.version !== "v2") {
|
|
2506
|
+
const body2 = backend.mapUpdate(updateParams);
|
|
2507
|
+
return jsonReply2(await callRestUrl(url, "PATCH", body2));
|
|
2508
|
+
}
|
|
2509
|
+
let scalerType = updateParams.scalerType;
|
|
2510
|
+
if (scalerType === void 0 && updateParams.scalerValue !== void 0) {
|
|
2511
|
+
const current = await callRestUrl(url);
|
|
2512
|
+
scalerType = current?.scaling?.type === "REQUEST_COUNT" ? "REQUEST_COUNT" : "QUEUE_DELAY";
|
|
2513
|
+
}
|
|
2514
|
+
const scalerError = scalerValueError(
|
|
2515
|
+
scalerType,
|
|
2516
|
+
updateParams.scalerValue
|
|
2087
2517
|
);
|
|
2088
|
-
|
|
2518
|
+
if (scalerError) {
|
|
2519
|
+
return jsonReply2({ error: scalerError, status: 400 });
|
|
2520
|
+
}
|
|
2521
|
+
const body = backend.mapUpdate({
|
|
2522
|
+
...updateParams,
|
|
2523
|
+
scalerType
|
|
2524
|
+
});
|
|
2525
|
+
return jsonReply2(await callRestUrl(url, "PATCH", body));
|
|
2089
2526
|
}
|
|
2090
2527
|
);
|
|
2091
2528
|
server.tool(
|
|
@@ -2133,7 +2570,7 @@ function registerEndpointTools(server, rt) {
|
|
|
2133
2570
|
);
|
|
2134
2571
|
server.tool(
|
|
2135
2572
|
"list-endpoint-workers",
|
|
2136
|
-
"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.",
|
|
2573
|
+
"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.",
|
|
2137
2574
|
{
|
|
2138
2575
|
...listPaginationParams,
|
|
2139
2576
|
endpointId: z8.string().describe("ID of the Serverless endpoint whose workers to list")
|
|
@@ -2159,7 +2596,7 @@ function registerEndpointTools(server, rt) {
|
|
|
2159
2596
|
);
|
|
2160
2597
|
server.tool(
|
|
2161
2598
|
"stream-worker-logs",
|
|
2162
|
-
"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).",
|
|
2599
|
+
"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).",
|
|
2163
2600
|
{
|
|
2164
2601
|
endpointId: z8.string().describe("ID of the Serverless endpoint the worker belongs to"),
|
|
2165
2602
|
workerId: z8.string().describe(
|
|
@@ -2182,8 +2619,67 @@ function registerEndpointTools(server, rt) {
|
|
|
2182
2619
|
|
|
2183
2620
|
// src/tools/jobs.ts
|
|
2184
2621
|
import { z as z9 } from "zod";
|
|
2622
|
+
var DIAGNOSIS_TTL_MS = 15e3;
|
|
2623
|
+
var MAX_DIAGNOSIS_ENTRIES = 500;
|
|
2624
|
+
var diagnosisCache = /* @__PURE__ */ new Map();
|
|
2185
2625
|
function registerJobTools(server, rt) {
|
|
2186
|
-
const { jsonReply: jsonReply2, serverlessRequest } = rt;
|
|
2626
|
+
const { jsonReply: jsonReply2, serverlessRequest, backendFor, callRestUrl } = rt;
|
|
2627
|
+
async function diagnoseQueuedJob(endpointId) {
|
|
2628
|
+
const cached = diagnosisCache.get(endpointId);
|
|
2629
|
+
if (cached && cached.expiresAt > Date.now()) {
|
|
2630
|
+
return cached.value;
|
|
2631
|
+
}
|
|
2632
|
+
diagnosisCache.delete(endpointId);
|
|
2633
|
+
try {
|
|
2634
|
+
const backend = backendFor("workers");
|
|
2635
|
+
if (backend.version !== "v2") return null;
|
|
2636
|
+
const raw = await callRestUrl(
|
|
2637
|
+
`${backend.base}/serverless/${endpointId}/workers`
|
|
2638
|
+
);
|
|
2639
|
+
const summary = raw?.summary;
|
|
2640
|
+
const workers = raw?.workers ?? [];
|
|
2641
|
+
if (!summary) return null;
|
|
2642
|
+
const remember = (value) => {
|
|
2643
|
+
if (diagnosisCache.size >= MAX_DIAGNOSIS_ENTRIES) {
|
|
2644
|
+
const oldest = diagnosisCache.keys().next().value;
|
|
2645
|
+
if (oldest !== void 0) diagnosisCache.delete(oldest);
|
|
2646
|
+
}
|
|
2647
|
+
diagnosisCache.set(endpointId, {
|
|
2648
|
+
value,
|
|
2649
|
+
expiresAt: Date.now() + DIAGNOSIS_TTL_MS
|
|
2650
|
+
});
|
|
2651
|
+
return value;
|
|
2652
|
+
};
|
|
2653
|
+
if ((summary.unhealthy ?? 0) > 0) {
|
|
2654
|
+
const badIds = workers.filter((w) => w.status === "UNHEALTHY").map((w) => w.id).join(", ");
|
|
2655
|
+
return remember({
|
|
2656
|
+
workerHealth: summary,
|
|
2657
|
+
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})` : ""}.`
|
|
2658
|
+
});
|
|
2659
|
+
}
|
|
2660
|
+
if ((summary.total ?? 0) === 0) {
|
|
2661
|
+
return remember({
|
|
2662
|
+
workerHealth: summary,
|
|
2663
|
+
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."
|
|
2664
|
+
});
|
|
2665
|
+
}
|
|
2666
|
+
if ((summary.throttled ?? 0) > 0 && (summary.running ?? 0) === 0) {
|
|
2667
|
+
return remember({
|
|
2668
|
+
workerHealth: summary,
|
|
2669
|
+
hint: "Workers exist but are throttled \u2014 the hosts are at capacity right now; the job should start when capacity frees up."
|
|
2670
|
+
});
|
|
2671
|
+
}
|
|
2672
|
+
if ((summary.initializing ?? 0) > 0) {
|
|
2673
|
+
return remember({
|
|
2674
|
+
workerHealth: summary,
|
|
2675
|
+
hint: "A worker is initializing \u2014 likely a cold start (image pull / model load); the job should start soon."
|
|
2676
|
+
});
|
|
2677
|
+
}
|
|
2678
|
+
return remember({ workerHealth: summary, hint: "" });
|
|
2679
|
+
} catch {
|
|
2680
|
+
return null;
|
|
2681
|
+
}
|
|
2682
|
+
}
|
|
2187
2683
|
const endpointIdSchema = z9.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid endpoint ID format");
|
|
2188
2684
|
const jobIdSchema = z9.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid job ID format");
|
|
2189
2685
|
const inputSchema = z9.record(z9.unknown()).describe(
|
|
@@ -2257,7 +2753,7 @@ function registerJobTools(server, rt) {
|
|
|
2257
2753
|
);
|
|
2258
2754
|
server.tool(
|
|
2259
2755
|
"get-job-status",
|
|
2260
|
-
"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.",
|
|
2756
|
+
"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.",
|
|
2261
2757
|
{
|
|
2262
2758
|
endpointId: endpointIdSchema.describe(
|
|
2263
2759
|
"ID of the Serverless endpoint the job belongs to"
|
|
@@ -2270,6 +2766,16 @@ function registerJobTools(server, rt) {
|
|
|
2270
2766
|
params.endpointId,
|
|
2271
2767
|
`/status/${params.jobId}`
|
|
2272
2768
|
);
|
|
2769
|
+
if (result && typeof result === "object" && result.status === "IN_QUEUE") {
|
|
2770
|
+
const diagnosis = await diagnoseQueuedJob(params.endpointId);
|
|
2771
|
+
if (diagnosis) {
|
|
2772
|
+
return jsonReply2({
|
|
2773
|
+
...result,
|
|
2774
|
+
workerHealth: diagnosis.workerHealth,
|
|
2775
|
+
...diagnosis.hint ? { hint: diagnosis.hint } : {}
|
|
2776
|
+
});
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2273
2779
|
return jsonReply2(result);
|
|
2274
2780
|
}
|
|
2275
2781
|
);
|
|
@@ -2371,7 +2877,7 @@ function registerJobTools(server, rt) {
|
|
|
2371
2877
|
);
|
|
2372
2878
|
server.tool(
|
|
2373
2879
|
"endpoint-health",
|
|
2374
|
-
"Get the health and operational status of a Serverless endpoint, including worker counts and job statistics.",
|
|
2880
|
+
"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.",
|
|
2375
2881
|
{
|
|
2376
2882
|
endpointId: endpointIdSchema.describe(
|
|
2377
2883
|
"ID of the Serverless endpoint to check health for"
|
|
@@ -2875,4 +3381,4 @@ export {
|
|
|
2875
3381
|
restVersionSummary,
|
|
2876
3382
|
registerTools
|
|
2877
3383
|
};
|
|
2878
|
-
//# sourceMappingURL=chunk-
|
|
3384
|
+
//# sourceMappingURL=chunk-WGK7D2YR.mjs.map
|