@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/dist/stdio.cjs CHANGED
@@ -506,15 +506,27 @@ function mapPodUpdateToV2(params) {
506
506
  ...compact({ name: params.name })
507
507
  };
508
508
  }
509
- function nestedOrUndefined(obj) {
510
- const c = compact(obj);
511
- return Object.keys(c).length ? c : void 0;
509
+ var DEFAULT_ENDPOINT_TYPE = "QUEUE";
510
+ var DEFAULT_SCALER_VALUE = 4;
511
+ function defaultScalerType(endpointType) {
512
+ return endpointType === "LOAD_BALANCER" ? "REQUEST_COUNT" : "QUEUE_DELAY";
513
+ }
514
+ function endpointScaling(scalerType, value) {
515
+ return scalerType === "REQUEST_COUNT" ? { type: "REQUEST_COUNT", requestCount: value } : { type: "QUEUE_DELAY", queueDelay: value };
512
516
  }
513
517
  function endpointGpuConfig(pools, count) {
514
518
  if (!pools?.length) return void 0;
515
519
  return compact({ pools, count });
516
520
  }
517
- function mapEndpointToV2(params) {
521
+ function endpointWorkers(params) {
522
+ const workers = compact({
523
+ min: params.workersMin,
524
+ max: params.workersMax,
525
+ idleTimeout: params.idleTimeout
526
+ });
527
+ return Object.keys(workers).length ? workers : void 0;
528
+ }
529
+ function endpointCommonToV2(params) {
518
530
  return compact({
519
531
  name: params.name,
520
532
  image: params.imageName,
@@ -524,23 +536,33 @@ function mapEndpointToV2(params) {
524
536
  env: params.env,
525
537
  registry: params.containerRegistryAuthId,
526
538
  gpu: endpointGpuConfig(params.gpuPoolIds, params.gpuCount),
527
- workers: nestedOrUndefined({
528
- min: params.workersMin,
529
- max: params.workersMax
530
- }),
531
- scaling: nestedOrUndefined({
532
- type: params.scalerType,
533
- value: params.scalerValue,
534
- idleTimeout: params.idleTimeout
535
- }),
539
+ workers: endpointWorkers(params),
536
540
  dataCenterIds: params.dataCenterIds?.length ? params.dataCenterIds : void 0,
537
541
  networkVolumes: params.networkVolumeIds?.length ? params.networkVolumeIds : void 0,
538
542
  timeout: params.executionTimeoutMs,
539
543
  flashboot: params.flashboot
540
544
  });
541
545
  }
542
- var mapEndpointCreateToV2 = mapEndpointToV2;
543
- var mapEndpointUpdateToV2 = mapEndpointToV2;
546
+ function mapEndpointCreateToV2(params) {
547
+ const endpointType = params.endpointType ?? DEFAULT_ENDPOINT_TYPE;
548
+ return compact({
549
+ ...endpointCommonToV2(params),
550
+ type: endpointType,
551
+ scaling: endpointScaling(
552
+ params.scalerType ?? defaultScalerType(endpointType),
553
+ params.scalerValue ?? DEFAULT_SCALER_VALUE
554
+ )
555
+ });
556
+ }
557
+ function mapEndpointUpdateToV2(params) {
558
+ return compact({
559
+ ...endpointCommonToV2(params),
560
+ scaling: params.scalerType ? endpointScaling(
561
+ params.scalerType,
562
+ params.scalerValue ?? DEFAULT_SCALER_VALUE
563
+ ) : void 0
564
+ });
565
+ }
544
566
  function mapNetworkVolumeCreateToV2(params) {
545
567
  return compact({
546
568
  name: params.name,
@@ -624,7 +646,7 @@ function restV1Base(env) {
624
646
  return env.RUNPOD_REST_API_URL ?? "https://rest.runpod.io/v1";
625
647
  }
626
648
  function restV2Base(env) {
627
- return env.RUNPOD_REST_V2_API_URL ?? "https://v2-rest.runpod.io/v2";
649
+ return env.RUNPOD_REST_V2_API_URL ?? "https://api.runpod.io/v2";
628
650
  }
629
651
  function serverlessBase(env) {
630
652
  return env.RUNPOD_SERVERLESS_API_URL ?? "https://api.runpod.ai/v2";
@@ -846,27 +868,176 @@ function resolveBackend(opts) {
846
868
 
847
869
  // src/server.ts
848
870
  var SERVER_NAME = "Runpod API Server";
849
- var SERVER_VERSION = true ? "3.0.0" : "dev";
871
+ var SERVER_VERSION = true ? "3.2.0" : "dev";
872
+ 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.
873
+
874
+ 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.`;
850
875
  function createServer(version = SERVER_VERSION) {
851
- return new import_mcp.McpServer({
852
- name: SERVER_NAME,
853
- version: `${version} [${restVersionSummary(process.env)}]`,
854
- capabilities: {
855
- resources: {},
856
- tools: {}
876
+ return new import_mcp.McpServer(
877
+ {
878
+ name: SERVER_NAME,
879
+ version: `${version} [${restVersionSummary(process.env)}]`
880
+ },
881
+ {
882
+ // Only advertise capabilities the server implements. It registers
883
+ // tools and no resources — advertising `resources` would invite
884
+ // `resources/list` calls that answer -32601.
885
+ capabilities: {
886
+ tools: {}
887
+ },
888
+ instructions: SERVER_INSTRUCTIONS
857
889
  }
858
- });
890
+ );
859
891
  }
860
892
 
861
893
  // src/tools/runtime.ts
862
894
  var import_node_fetch = __toESM(require("node-fetch"), 1);
863
895
  var import_node_crypto = require("crypto");
864
896
 
897
+ // src/_shared/rate-limit.ts
898
+ var GENERIC_RATE_LIMIT_HINT = "rate limited \u2014 back off before retrying, and pace bulk operations";
899
+ var MAX_PLAUSIBLE_WAIT_S = 7 * 86400;
900
+ function remainingRequests(raw) {
901
+ const value = raw?.trim();
902
+ return value && /^\d+$/.test(value) ? Number(value) : null;
903
+ }
904
+ function waitSeconds(raw) {
905
+ const value = raw?.trim();
906
+ if (!value || !/^\d+$/.test(value)) return null;
907
+ const seconds = Number(value);
908
+ return seconds <= MAX_PLAUSIBLE_WAIT_S ? seconds : null;
909
+ }
910
+ var WINDOW_NAME_RE = /^(?:"([\x20-\x21\x23-\x5b\x5d-\x7e]{1,32})"|([A-Za-z*][A-Za-z0-9!#$%&'*+.^_`|~:/-]{0,31}))$/;
911
+ function windowName(raw) {
912
+ const match = WINDOW_NAME_RE.exec(raw.trim());
913
+ return match ? match[1] ?? match[2] : null;
914
+ }
915
+ var QUOTED_VALUE_RE = /^"(?:[\x20-\x21\x23-\x5b\x5d-\x7e]|\\["\\])*"$/;
916
+ var DISPLAY_VALUE_RE = /^%"(?:[\x20-\x21\x23-\x24\x26-\x5b\x5d-\x7e]|\\|%[0-9a-f]{2})*"$/;
917
+ function isWellFormedParam(param) {
918
+ const eq = param.indexOf("=");
919
+ const key = (eq === -1 ? param : param.slice(0, eq)).trim();
920
+ if (key.includes('"')) return false;
921
+ if (eq === -1) return true;
922
+ const value = param.slice(eq + 1).trim();
923
+ if (value.startsWith('"')) return QUOTED_VALUE_RE.test(value);
924
+ if (value.startsWith('%"')) return DISPLAY_VALUE_RE.test(value);
925
+ return !/[\s"]/.test(value);
926
+ }
927
+ function splitOutsideStrings(input, sep) {
928
+ const parts = [];
929
+ let current = "";
930
+ let inString = false;
931
+ let inDisplay = false;
932
+ let escaped = false;
933
+ let prev = "";
934
+ for (const ch of input) {
935
+ if (escaped) escaped = false;
936
+ else if (inString && !inDisplay && ch === "\\") escaped = true;
937
+ else if (ch === '"') {
938
+ if (!inString) inDisplay = prev === "%";
939
+ inString = !inString;
940
+ } else if (ch === sep && !inString) {
941
+ parts.push(current);
942
+ current = "";
943
+ prev = ch;
944
+ continue;
945
+ }
946
+ current += ch;
947
+ prev = ch;
948
+ }
949
+ parts.push(current);
950
+ return parts;
951
+ }
952
+ function readParams(params) {
953
+ const values = /* @__PURE__ */ new Map();
954
+ let unreadable = false;
955
+ let valuelessAt = -1;
956
+ for (const [index, param] of params.entries()) {
957
+ const eq = param.indexOf("=");
958
+ const key = (eq === -1 ? param : param.slice(0, eq)).trim().toLowerCase();
959
+ if (!key) continue;
960
+ if (eq === -1) {
961
+ if (key === "r") unreadable = true;
962
+ if (key === "t") values.delete("t");
963
+ valuelessAt = index;
964
+ continue;
965
+ }
966
+ if ((key === "r" || key === "t") && (values.has(key) || valuelessAt !== -1 && index > valuelessAt)) {
967
+ unreadable = true;
968
+ }
969
+ values.set(key, param.slice(eq + 1));
970
+ }
971
+ return { values, unreadable };
972
+ }
973
+ function parseExhaustedWindows(header) {
974
+ if (!header) return { windows: [], dropped: false };
975
+ const windows = [];
976
+ let dropped = false;
977
+ for (const item of splitOutsideStrings(header, ",")) {
978
+ if (item.trim() === "") continue;
979
+ const [rawName, ...params] = splitOutsideStrings(item, ";");
980
+ if (!params.every(isWellFormedParam)) {
981
+ dropped = true;
982
+ continue;
983
+ }
984
+ const { values, unreadable } = readParams(params);
985
+ if (unreadable) {
986
+ dropped = true;
987
+ continue;
988
+ }
989
+ const remaining = remainingRequests(values.get("r"));
990
+ if (remaining === null) {
991
+ dropped = true;
992
+ continue;
993
+ }
994
+ if (remaining !== 0) continue;
995
+ windows.push({
996
+ window: windowName(rawName),
997
+ resetS: waitSeconds(values.get("t"))
998
+ });
999
+ }
1000
+ return { windows, dropped };
1001
+ }
1002
+ function humanWait(seconds) {
1003
+ if (seconds < 120) return `~${seconds}s`;
1004
+ if (seconds < 3600)
1005
+ return `~${Math.ceil(seconds / 60)} minutes (${seconds}s)`;
1006
+ if (seconds < 2 * 86400) {
1007
+ const hours = Math.ceil(seconds / 3600);
1008
+ return `~${hours} hour${hours === 1 ? "" : "s"} (${seconds}s)`;
1009
+ }
1010
+ return `~${Math.ceil(seconds / 86400)} days (${seconds}s)`;
1011
+ }
1012
+ function rateLimitHint(rateLimitHeader, retryAfterHeader) {
1013
+ const { windows, dropped } = parseExhaustedWindows(rateLimitHeader);
1014
+ windows.sort((a, b) => (b.resetS ?? -1) - (a.resetS ?? -1));
1015
+ const longestWindow = windows[0];
1016
+ const waitCandidates = [
1017
+ waitSeconds(retryAfterHeader),
1018
+ longestWindow?.resetS
1019
+ ].filter((n) => typeof n === "number" && n > 0);
1020
+ const waitS = waitCandidates.length ? Math.max(...waitCandidates) : null;
1021
+ const retryAfterUnreadable = typeof retryAfterHeader === "string" && retryAfterHeader.trim() !== "" && waitSeconds(retryAfterHeader) === null;
1022
+ if (!longestWindow && waitS === null) {
1023
+ if (!retryAfterUnreadable) return GENERIC_RATE_LIMIT_HINT;
1024
+ }
1025
+ const namedClause = longestWindow?.window ? `the ${longestWindow.window} quota is exhausted` : "";
1026
+ if (waitS === null) {
1027
+ const cause = namedClause ? `${namedClause}, but the response gave no usable reset time` : "the response gave no usable reset time";
1028
+ return `rate limited \u2014 ${cause}; back off substantially before retrying, and pace bulk operations`;
1029
+ }
1030
+ const hedge = dropped || retryAfterUnreadable || windows.some((w) => w.resetS === null) ? "at least " : "";
1031
+ const wait = `wait ${hedge}${humanWait(waitS)} before retrying, and pace bulk operations`;
1032
+ return `rate limited \u2014 ${namedClause ? `${namedClause}; ` : ""}${wait}`;
1033
+ }
1034
+
865
1035
  // src/_shared/http.ts
1036
+ 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";
866
1037
  var HttpError = class extends Error {
867
- constructor(prefix, status, body) {
868
- const hint = status === 401 ? " (the Runpod API rejected the credential \u2014 the API key may be expired or revoked; re-authenticate or update RUNPOD_API_KEY)" : "";
869
- super(`${prefix}: ${status} - ${body}${hint}`);
1038
+ constructor(prefix, status, body, hint) {
1039
+ const shownBody = body.length > 2048 ? `${body.slice(0, 2048)}\u2026 [truncated ${body.length - 2048} chars]` : body;
1040
+ super(`${prefix}: ${status} - ${shownBody}${hint ? ` (${hint})` : ""}`);
870
1041
  this.name = "HttpError";
871
1042
  this.status = status;
872
1043
  this.body = body;
@@ -901,7 +1072,11 @@ function createHttpClient(deps) {
901
1072
  throw new HttpError(
902
1073
  deps.errorPrefix,
903
1074
  response.status,
904
- await response.text()
1075
+ await response.text(),
1076
+ response.status === 429 ? rateLimitHint(
1077
+ response.headers.get("ratelimit"),
1078
+ response.headers.get("retry-after")
1079
+ ) : response.status === 401 ? EXPIRED_CREDENTIAL_HINT : void 0
905
1080
  );
906
1081
  }
907
1082
  return isJsonContentType(response.headers.get("content-type")) ? response.json() : { success: true, status: response.status };
@@ -960,7 +1135,15 @@ async function readSseSnapshot(fetchImpl, url, headers, opts) {
960
1135
  throw new HttpError(
961
1136
  "Runpod API Error",
962
1137
  res.status,
963
- await res.text().catch(() => "")
1138
+ await res.text().catch(() => ""),
1139
+ // This throw bypasses createHttpClient, so the status hints are built
1140
+ // here too or these two tools alone return a bare 429/401. The 401
1141
+ // hint applies: this request always carries Authorization (see the
1142
+ // headers bound in runtime.ts streamSse).
1143
+ res.status === 429 ? rateLimitHint(
1144
+ res.headers.get("ratelimit"),
1145
+ res.headers.get("retry-after")
1146
+ ) : res.status === 401 ? EXPIRED_CREDENTIAL_HINT : void 0
964
1147
  );
965
1148
  }
966
1149
  for await (const chunk of res.body ?? []) {
@@ -1023,7 +1206,7 @@ async function streamLogsReply(rt, tool, params) {
1023
1206
  }
1024
1207
 
1025
1208
  // src/tools/runtime.ts
1026
- var MCP_SERVER_VERSION = true ? "3.0.0" : "dev";
1209
+ var MCP_SERVER_VERSION = true ? "3.2.0" : "dev";
1027
1210
  var SESSION_ID = (0, import_node_crypto.randomUUID)();
1028
1211
  function trackingHeaders(server, ctx) {
1029
1212
  const info = server.server.getClientVersion();
@@ -1073,6 +1256,36 @@ async function graphqlRequest(query, tracking, fetchImpl, url, options) {
1073
1256
  ...options?.variables ? { variables: options.variables } : {}
1074
1257
  })
1075
1258
  });
1259
+ if (!response.ok) {
1260
+ const bodyText = await response.text();
1261
+ let gqlErrors;
1262
+ try {
1263
+ gqlErrors = JSON.parse(bodyText).errors;
1264
+ } catch {
1265
+ }
1266
+ if (Array.isArray(gqlErrors) && gqlErrors.length > 0 && response.status !== 401 && response.status !== 429) {
1267
+ throw new HttpError(
1268
+ "Runpod GraphQL Error",
1269
+ response.status,
1270
+ gqlErrors.map((e) => String(e?.message ?? JSON.stringify(e))).join(", ")
1271
+ );
1272
+ }
1273
+ throw new HttpError(
1274
+ "Runpod GraphQL Error",
1275
+ response.status,
1276
+ bodyText,
1277
+ response.status === 429 ? rateLimitHint(
1278
+ response.headers.get("ratelimit"),
1279
+ response.headers.get("retry-after")
1280
+ ) : (
1281
+ // Only when this request actually carried the caller's API key: the
1282
+ // public path sends no Authorization header, so a 401 from that
1283
+ // host (WAF, misconfigured RUNPOD_PUBLIC_GRAPHQL_URL) says nothing
1284
+ // about the credential — same rationale as observeUnauthorized.
1285
+ response.status === 401 && options?.apiKey ? EXPIRED_CREDENTIAL_HINT : void 0
1286
+ )
1287
+ );
1288
+ }
1076
1289
  const result = await response.json();
1077
1290
  if (result.errors && result.errors.length > 0) {
1078
1291
  throw new Error(
@@ -1489,6 +1702,178 @@ function registerCatalogTools(server, rt) {
1489
1702
  return jsonReply2(result);
1490
1703
  }
1491
1704
  );
1705
+ server.tool(
1706
+ "get-capacity",
1707
+ "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.",
1708
+ {
1709
+ ...listPaginationParams,
1710
+ cudaVersions: import_zod3.z.array(import_zod3.z.string().regex(/^\d{1,2}\.\d{1,2}$/)).min(1).max(12).optional().describe(
1711
+ '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.'
1712
+ ),
1713
+ includeUnavailable: import_zod3.z.boolean().optional().describe(
1714
+ '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.'
1715
+ ),
1716
+ gpuTypeIds: import_zod3.z.array(import_zod3.z.string()).optional().describe(
1717
+ "Filter to GPU types matching any of these ids or display names (case-insensitive substring, e.g. ['NVIDIA GeForce RTX 4090'] or ['4090', 'H200'])."
1718
+ ),
1719
+ gpuCount: import_zod3.z.number().int().min(1).max(8).optional().describe("GPUs per worker/pod to check stock for (default 1)."),
1720
+ secureCloudOnly: import_zod3.z.boolean().optional().describe("Restrict the stock lookup to Secure Cloud hosts.")
1721
+ },
1722
+ { title: "Get GPU capacity by CUDA version", ...READ_ONLY },
1723
+ async (params) => {
1724
+ const gpuCount = Math.min(
1725
+ 8,
1726
+ Math.max(1, Math.floor(Number(params.gpuCount)) || 1)
1727
+ );
1728
+ const secureArg = params.secureCloudOnly ? ", secureCloud: true" : "";
1729
+ const filterTerms = (params.gpuTypeIds ?? []).filter((t) => typeof t === "string" && t.trim().length > 0).map((t) => t.toLowerCase());
1730
+ const matchesFilter = (gpu) => {
1731
+ if (filterTerms.length === 0) return true;
1732
+ const id = gpu.id.toLowerCase();
1733
+ const name = gpu.displayName.toLowerCase();
1734
+ return filterTerms.some(
1735
+ (term) => id.includes(term) || name.includes(term)
1736
+ );
1737
+ };
1738
+ const stockPriority = {
1739
+ High: 3,
1740
+ Medium: 2,
1741
+ Low: 1
1742
+ };
1743
+ if (!params.cudaVersions?.length) {
1744
+ const data = await graphql(`
1745
+ query {
1746
+ gpuTypes {
1747
+ id
1748
+ displayName
1749
+ memoryInGb
1750
+ secureCloud
1751
+ communityCloud
1752
+ lowestPrice(input: { gpuCount: ${gpuCount}${secureArg} }) {
1753
+ stockStatus
1754
+ uninterruptablePrice
1755
+ gpuTypeCudaVersions {
1756
+ cudaVersion
1757
+ availability
1758
+ }
1759
+ }
1760
+ }
1761
+ }
1762
+ `);
1763
+ let rows2 = data.gpuTypes.filter((gpu) => gpu.id !== "unknown" && matchesFilter(gpu)).map((gpu) => {
1764
+ const cuda = {};
1765
+ for (const c of gpu.lowestPrice?.gpuTypeCudaVersions ?? []) {
1766
+ cuda[c.cudaVersion] = c.availability;
1767
+ }
1768
+ return {
1769
+ id: gpu.id,
1770
+ displayName: gpu.displayName,
1771
+ memoryGb: gpu.memoryInGb,
1772
+ secureCloud: gpu.secureCloud,
1773
+ communityCloud: gpu.communityCloud,
1774
+ stockStatus: gpu.lowestPrice?.stockStatus || "unavailable",
1775
+ pricePerHr: gpu.lowestPrice?.uninterruptablePrice ?? null,
1776
+ cudaVersions: cuda
1777
+ };
1778
+ });
1779
+ const availableCount = (r) => Object.values(r.cudaVersions).filter((a) => a === "AVAILABLE").length;
1780
+ if (params.includeUnavailable === false)
1781
+ rows2 = rows2.filter((r) => availableCount(r) > 0);
1782
+ rows2.sort((a, b) => {
1783
+ const diff = availableCount(b) - availableCount(a);
1784
+ if (diff !== 0) return diff;
1785
+ const stockDiff = (stockPriority[b.stockStatus] || 0) - (stockPriority[a.stockStatus] || 0);
1786
+ if (stockDiff !== 0) return stockDiff;
1787
+ return b.memoryGb - a.memoryGb;
1788
+ });
1789
+ return capListResult(rows2, {
1790
+ limit: params.limit,
1791
+ cursor: params.cursor
1792
+ });
1793
+ }
1794
+ const versions = [...new Set(params.cudaVersions)].slice(0, 12);
1795
+ const invalid = versions.filter((v) => !/^\d{1,2}\.\d{1,2}$/.test(v));
1796
+ if (invalid.length > 0) {
1797
+ return jsonReply2({
1798
+ error: `Invalid CUDA version format: ${invalid.join(", ")}. Use "major.minor" strings like "12.8".`,
1799
+ status: 400
1800
+ });
1801
+ }
1802
+ const perVersion = await Promise.allSettled(
1803
+ versions.map(
1804
+ (v) => graphql(`
1805
+ query {
1806
+ gpuTypes {
1807
+ id
1808
+ displayName
1809
+ memoryInGb
1810
+ secureCloud
1811
+ communityCloud
1812
+ lowestPrice(input: { gpuCount: ${gpuCount}, allowedCudaVersions: ["${v}"]${secureArg} }) {
1813
+ stockStatus
1814
+ uninterruptablePrice
1815
+ }
1816
+ }
1817
+ }
1818
+ `)
1819
+ )
1820
+ );
1821
+ const probeErrors = {};
1822
+ const byId = /* @__PURE__ */ new Map();
1823
+ versions.forEach((v, i) => {
1824
+ const settled = perVersion[i];
1825
+ if (settled.status === "rejected") {
1826
+ probeErrors[v] = settled.reason instanceof Error ? settled.reason.message : String(settled.reason);
1827
+ return;
1828
+ }
1829
+ for (const gpu of settled.value.gpuTypes) {
1830
+ if (gpu.id === "unknown" || !matchesFilter(gpu)) continue;
1831
+ let row = byId.get(gpu.id);
1832
+ if (!row) {
1833
+ row = {
1834
+ id: gpu.id,
1835
+ displayName: gpu.displayName,
1836
+ memoryGb: gpu.memoryInGb,
1837
+ secureCloud: gpu.secureCloud,
1838
+ communityCloud: gpu.communityCloud,
1839
+ cudaVersions: {}
1840
+ };
1841
+ byId.set(gpu.id, row);
1842
+ }
1843
+ const stock = gpu.lowestPrice?.stockStatus;
1844
+ row.cudaVersions[v] = !stock || stock === "Out" ? { stock: "Out", pricePerHr: null } : {
1845
+ stock,
1846
+ pricePerHr: gpu.lowestPrice?.uninterruptablePrice ?? null
1847
+ };
1848
+ }
1849
+ });
1850
+ let rows = [...byId.values()];
1851
+ const inStockCount = (r) => Object.values(r.cudaVersions).filter((c) => c.stock !== "Out").length;
1852
+ if (params.includeUnavailable === false)
1853
+ rows = rows.filter((r) => inStockCount(r) > 0);
1854
+ rows.sort((a, b) => {
1855
+ const diff = inStockCount(b) - inStockCount(a);
1856
+ if (diff !== 0) return diff;
1857
+ const best = (r) => Math.max(
1858
+ 0,
1859
+ ...Object.values(r.cudaVersions).map(
1860
+ (c) => stockPriority[c.stock] || 0
1861
+ )
1862
+ );
1863
+ const bestDiff = best(b) - best(a);
1864
+ if (bestDiff !== 0) return bestDiff;
1865
+ return b.memoryGb - a.memoryGb;
1866
+ });
1867
+ return capListResult(
1868
+ rows,
1869
+ { limit: params.limit, cursor: params.cursor },
1870
+ {
1871
+ probedCudaVersions: versions,
1872
+ ...Object.keys(probeErrors).length > 0 ? { probeErrors } : {}
1873
+ }
1874
+ );
1875
+ }
1876
+ );
1492
1877
  server.tool(
1493
1878
  "get-data-center",
1494
1879
  "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).",
@@ -2173,7 +2558,9 @@ function registerPodTools(server, rt) {
2173
2558
  "create-pod",
2174
2559
  '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.',
2175
2560
  {
2176
- name: import_zod7.z.string().optional().describe("Name for the pod"),
2561
+ name: import_zod7.z.string().optional().describe(
2562
+ "Name for the pod. Required on v2 unless deploying from a templateId (the template supplies its name as the default)."
2563
+ ),
2177
2564
  imageName: import_zod7.z.string().optional().describe("Docker image to use. Optional when templateId is provided."),
2178
2565
  templateId: import_zod7.z.string().optional().describe(
2179
2566
  "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."
@@ -2232,6 +2619,12 @@ function registerPodTools(server, rt) {
2232
2619
  status: 400
2233
2620
  });
2234
2621
  }
2622
+ if (!wantsCpu && !params.name && !params.templateId) {
2623
+ return jsonReply2({
2624
+ error: "Provide a name for the pod (deploying from a templateId inherits the template name).",
2625
+ status: 400
2626
+ });
2627
+ }
2235
2628
  if (wantsCpu) {
2236
2629
  if (params.templateId) {
2237
2630
  return jsonReply2({
@@ -2409,11 +2802,22 @@ function registerPodTools(server, rt) {
2409
2802
 
2410
2803
  // src/tools/endpoints.ts
2411
2804
  var import_zod8 = require("zod");
2805
+ var MIN_QUEUE_DELAY = 0.5;
2806
+ var MIN_REQUEST_COUNT = 1;
2807
+ var MIN_IDLE_TIMEOUT = 1;
2808
+ var MAX_IDLE_TIMEOUT = 3600;
2809
+ function scalerValueError(scalerType, scalerValue) {
2810
+ if (scalerType !== "REQUEST_COUNT" || scalerValue === void 0) return;
2811
+ if (!Number.isInteger(scalerValue) || scalerValue < MIN_REQUEST_COUNT) {
2812
+ 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}.`;
2813
+ }
2814
+ return;
2815
+ }
2412
2816
  function registerEndpointTools(server, rt) {
2413
2817
  const { jsonReply: jsonReply2, callRestUrl, backendFor } = rt;
2414
2818
  server.tool(
2415
2819
  "list-endpoints",
2416
- "List your Serverless endpoints, optionally expanding template and worker details (v1 only). Paginated via limit/cursor.",
2820
+ "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`.",
2417
2821
  {
2418
2822
  ...listPaginationParams,
2419
2823
  includeTemplate: import_zod8.z.boolean().optional().describe("Include template information (v1 only)"),
@@ -2448,7 +2852,7 @@ function registerEndpointTools(server, rt) {
2448
2852
  );
2449
2853
  server.tool(
2450
2854
  "get-endpoint",
2451
- "Get one Serverless endpoint by id, optionally expanding template and worker details (v1 only).",
2855
+ "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.",
2452
2856
  {
2453
2857
  endpointId: import_zod8.z.string().describe("ID of the endpoint to retrieve"),
2454
2858
  includeTemplate: import_zod8.z.boolean().optional().describe("Include template information (v1 only)"),
@@ -2480,11 +2884,14 @@ function registerEndpointTools(server, rt) {
2480
2884
  );
2481
2885
  server.tool(
2482
2886
  "create-endpoint",
2483
- "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).",
2887
+ "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.",
2484
2888
  {
2485
2889
  name: import_zod8.z.string().optional().describe("Name for the endpoint"),
2486
2890
  // --- v2 inline-config fields ---
2487
2891
  imageName: import_zod8.z.string().optional().describe("Docker image (v2). Required on v2 instead of a templateId."),
2892
+ endpointType: import_zod8.z.enum(["QUEUE", "LOAD_BALANCER"]).optional().describe(
2893
+ "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."
2894
+ ),
2488
2895
  gpuPoolIds: import_zod8.z.array(import_zod8.z.string()).optional().describe(
2489
2896
  'GPU pool names (v2, required). The `pool` field from list-gpu-types, e.g. ["AMPERE_80"]. NOT GPU type ids.'
2490
2897
  ),
@@ -2504,9 +2911,15 @@ function registerEndpointTools(server, rt) {
2504
2911
  // --- shared autoscaling fields ---
2505
2912
  workersMin: import_zod8.z.number().optional().describe("Minimum number of workers"),
2506
2913
  workersMax: import_zod8.z.number().optional().describe("Maximum number of workers"),
2507
- scalerType: import_zod8.z.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe("Autoscaler type"),
2508
- scalerValue: import_zod8.z.number().optional().describe("Autoscaler target value"),
2509
- idleTimeout: import_zod8.z.number().optional().describe("Idle timeout in seconds before scaling a worker down"),
2914
+ scalerType: import_zod8.z.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe(
2915
+ "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."
2916
+ ),
2917
+ scalerValue: import_zod8.z.number().min(MIN_QUEUE_DELAY).optional().describe(
2918
+ "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."
2919
+ ),
2920
+ idleTimeout: import_zod8.z.number().int().min(MIN_IDLE_TIMEOUT).max(MAX_IDLE_TIMEOUT).optional().describe(
2921
+ "Idle timeout in seconds before scaling a worker down (1-3600). Does not apply to QUEUE endpoints scaling on REQUEST_COUNT."
2922
+ ),
2510
2923
  dataCenterIds: import_zod8.z.array(import_zod8.z.string()).optional().describe("List of preferred data centers")
2511
2924
  },
2512
2925
  { title: "Create endpoint", ...WRITE },
@@ -2531,6 +2944,19 @@ function registerEndpointTools(server, rt) {
2531
2944
  status: 400
2532
2945
  });
2533
2946
  }
2947
+ if (params.endpointType === "LOAD_BALANCER" && params.scalerType === "QUEUE_DELAY") {
2948
+ return jsonReply2({
2949
+ 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.",
2950
+ status: 400
2951
+ });
2952
+ }
2953
+ const scalerError = scalerValueError(
2954
+ params.scalerType ?? (params.endpointType === "LOAD_BALANCER" ? "REQUEST_COUNT" : void 0),
2955
+ params.scalerValue
2956
+ );
2957
+ if (scalerError) {
2958
+ return jsonReply2({ error: scalerError, status: 400 });
2959
+ }
2534
2960
  const body = backend.mapCreate(params);
2535
2961
  const result2 = await callRestUrl(
2536
2962
  `${backend.base}${backend.list}`,
@@ -2568,15 +2994,21 @@ function registerEndpointTools(server, rt) {
2568
2994
  );
2569
2995
  server.tool(
2570
2996
  "update-endpoint",
2571
- "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.",
2997
+ "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.",
2572
2998
  {
2573
2999
  endpointId: import_zod8.z.string().describe("ID of the endpoint to update"),
2574
3000
  name: import_zod8.z.string().optional().describe("New name for the endpoint"),
2575
3001
  workersMin: import_zod8.z.number().optional().describe("New minimum number of workers"),
2576
3002
  workersMax: import_zod8.z.number().optional().describe("New maximum number of workers"),
2577
- idleTimeout: import_zod8.z.number().optional().describe("New idle timeout in seconds"),
2578
- scalerType: import_zod8.z.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe("Scaler type"),
2579
- scalerValue: import_zod8.z.number().optional().describe("Scaler value"),
3003
+ idleTimeout: import_zod8.z.number().int().min(MIN_IDLE_TIMEOUT).max(MAX_IDLE_TIMEOUT).optional().describe(
3004
+ "New idle timeout in seconds (1-3600). Does not apply to queue endpoints scaling on REQUEST_COUNT."
3005
+ ),
3006
+ scalerType: import_zod8.z.enum(["QUEUE_DELAY", "REQUEST_COUNT"]).optional().describe(
3007
+ "New autoscaler signal. Switchable on queue endpoints; load-balancing endpoints only accept REQUEST_COUNT."
3008
+ ),
3009
+ scalerValue: import_zod8.z.number().min(MIN_QUEUE_DELAY).optional().describe(
3010
+ "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."
3011
+ ),
2580
3012
  // --- v2-only inline-config fields ---
2581
3013
  imageName: import_zod8.z.string().optional().describe("New Docker image (v2)"),
2582
3014
  gpuPoolIds: import_zod8.z.array(import_zod8.z.string()).optional().describe('New GPU pool names (v2), e.g. ["AMPERE_80"]'),
@@ -2594,13 +3026,28 @@ function registerEndpointTools(server, rt) {
2594
3026
  async (params) => {
2595
3027
  const { endpointId, ...updateParams } = params;
2596
3028
  const backend = backendFor("endpoints");
2597
- const body = backend.mapUpdate(updateParams);
2598
- const result = await callRestUrl(
2599
- `${backend.base}${backend.get(endpointId)}`,
2600
- "PATCH",
2601
- body
3029
+ const url = `${backend.base}${backend.get(endpointId)}`;
3030
+ if (backend.version !== "v2") {
3031
+ const body2 = backend.mapUpdate(updateParams);
3032
+ return jsonReply2(await callRestUrl(url, "PATCH", body2));
3033
+ }
3034
+ let scalerType = updateParams.scalerType;
3035
+ if (scalerType === void 0 && updateParams.scalerValue !== void 0) {
3036
+ const current = await callRestUrl(url);
3037
+ scalerType = current?.scaling?.type === "REQUEST_COUNT" ? "REQUEST_COUNT" : "QUEUE_DELAY";
3038
+ }
3039
+ const scalerError = scalerValueError(
3040
+ scalerType,
3041
+ updateParams.scalerValue
2602
3042
  );
2603
- return jsonReply2(result);
3043
+ if (scalerError) {
3044
+ return jsonReply2({ error: scalerError, status: 400 });
3045
+ }
3046
+ const body = backend.mapUpdate({
3047
+ ...updateParams,
3048
+ scalerType
3049
+ });
3050
+ return jsonReply2(await callRestUrl(url, "PATCH", body));
2604
3051
  }
2605
3052
  );
2606
3053
  server.tool(
@@ -2648,7 +3095,7 @@ function registerEndpointTools(server, rt) {
2648
3095
  );
2649
3096
  server.tool(
2650
3097
  "list-endpoint-workers",
2651
- "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.",
3098
+ "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.",
2652
3099
  {
2653
3100
  ...listPaginationParams,
2654
3101
  endpointId: import_zod8.z.string().describe("ID of the Serverless endpoint whose workers to list")
@@ -2674,7 +3121,7 @@ function registerEndpointTools(server, rt) {
2674
3121
  );
2675
3122
  server.tool(
2676
3123
  "stream-worker-logs",
2677
- "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).",
3124
+ "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).",
2678
3125
  {
2679
3126
  endpointId: import_zod8.z.string().describe("ID of the Serverless endpoint the worker belongs to"),
2680
3127
  workerId: import_zod8.z.string().describe(
@@ -2697,8 +3144,67 @@ function registerEndpointTools(server, rt) {
2697
3144
 
2698
3145
  // src/tools/jobs.ts
2699
3146
  var import_zod9 = require("zod");
3147
+ var DIAGNOSIS_TTL_MS = 15e3;
3148
+ var MAX_DIAGNOSIS_ENTRIES = 500;
3149
+ var diagnosisCache = /* @__PURE__ */ new Map();
2700
3150
  function registerJobTools(server, rt) {
2701
- const { jsonReply: jsonReply2, serverlessRequest } = rt;
3151
+ const { jsonReply: jsonReply2, serverlessRequest, backendFor, callRestUrl } = rt;
3152
+ async function diagnoseQueuedJob(endpointId) {
3153
+ const cached = diagnosisCache.get(endpointId);
3154
+ if (cached && cached.expiresAt > Date.now()) {
3155
+ return cached.value;
3156
+ }
3157
+ diagnosisCache.delete(endpointId);
3158
+ try {
3159
+ const backend = backendFor("workers");
3160
+ if (backend.version !== "v2") return null;
3161
+ const raw = await callRestUrl(
3162
+ `${backend.base}/serverless/${endpointId}/workers`
3163
+ );
3164
+ const summary = raw?.summary;
3165
+ const workers = raw?.workers ?? [];
3166
+ if (!summary) return null;
3167
+ const remember = (value) => {
3168
+ if (diagnosisCache.size >= MAX_DIAGNOSIS_ENTRIES) {
3169
+ const oldest = diagnosisCache.keys().next().value;
3170
+ if (oldest !== void 0) diagnosisCache.delete(oldest);
3171
+ }
3172
+ diagnosisCache.set(endpointId, {
3173
+ value,
3174
+ expiresAt: Date.now() + DIAGNOSIS_TTL_MS
3175
+ });
3176
+ return value;
3177
+ };
3178
+ if ((summary.unhealthy ?? 0) > 0) {
3179
+ const badIds = workers.filter((w) => w.status === "UNHEALTHY").map((w) => w.id).join(", ");
3180
+ return remember({
3181
+ workerHealth: summary,
3182
+ 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})` : ""}.`
3183
+ });
3184
+ }
3185
+ if ((summary.total ?? 0) === 0) {
3186
+ return remember({
3187
+ workerHealth: summary,
3188
+ 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."
3189
+ });
3190
+ }
3191
+ if ((summary.throttled ?? 0) > 0 && (summary.running ?? 0) === 0) {
3192
+ return remember({
3193
+ workerHealth: summary,
3194
+ hint: "Workers exist but are throttled \u2014 the hosts are at capacity right now; the job should start when capacity frees up."
3195
+ });
3196
+ }
3197
+ if ((summary.initializing ?? 0) > 0) {
3198
+ return remember({
3199
+ workerHealth: summary,
3200
+ hint: "A worker is initializing \u2014 likely a cold start (image pull / model load); the job should start soon."
3201
+ });
3202
+ }
3203
+ return remember({ workerHealth: summary, hint: "" });
3204
+ } catch {
3205
+ return null;
3206
+ }
3207
+ }
2702
3208
  const endpointIdSchema = import_zod9.z.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid endpoint ID format");
2703
3209
  const jobIdSchema = import_zod9.z.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid job ID format");
2704
3210
  const inputSchema = import_zod9.z.record(import_zod9.z.unknown()).describe(
@@ -2772,7 +3278,7 @@ function registerJobTools(server, rt) {
2772
3278
  );
2773
3279
  server.tool(
2774
3280
  "get-job-status",
2775
- "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.",
3281
+ "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.",
2776
3282
  {
2777
3283
  endpointId: endpointIdSchema.describe(
2778
3284
  "ID of the Serverless endpoint the job belongs to"
@@ -2785,6 +3291,16 @@ function registerJobTools(server, rt) {
2785
3291
  params.endpointId,
2786
3292
  `/status/${params.jobId}`
2787
3293
  );
3294
+ if (result && typeof result === "object" && result.status === "IN_QUEUE") {
3295
+ const diagnosis = await diagnoseQueuedJob(params.endpointId);
3296
+ if (diagnosis) {
3297
+ return jsonReply2({
3298
+ ...result,
3299
+ workerHealth: diagnosis.workerHealth,
3300
+ ...diagnosis.hint ? { hint: diagnosis.hint } : {}
3301
+ });
3302
+ }
3303
+ }
2788
3304
  return jsonReply2(result);
2789
3305
  }
2790
3306
  );
@@ -2886,7 +3402,7 @@ function registerJobTools(server, rt) {
2886
3402
  );
2887
3403
  server.tool(
2888
3404
  "endpoint-health",
2889
- "Get the health and operational status of a Serverless endpoint, including worker counts and job statistics.",
3405
+ "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.",
2890
3406
  {
2891
3407
  endpointId: endpointIdSchema.describe(
2892
3408
  "ID of the Serverless endpoint to check health for"