@runpod/mcp-server 1.1.0 → 1.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/index.mjs CHANGED
@@ -5,25 +5,77 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
6
  import { z } from "zod";
7
7
  import fetch from "node-fetch";
8
+ import { randomUUID } from "crypto";
8
9
  var API_BASE_URL = "https://rest.runpod.io/v1";
9
10
  var API_KEY = process.env.RUNPOD_API_KEY;
10
11
  if (!API_KEY) {
11
12
  console.error("RUNPOD_API_KEY environment variable is required");
12
13
  process.exit(1);
13
14
  }
15
+ var MCP_SERVER_NAME = "RunPod API Server";
16
+ var MCP_SERVER_VERSION = true ? "1.2.0" : "dev";
17
+ var MCP_TRANSPORT = "stdio";
18
+ function setTransport(t) {
19
+ MCP_TRANSPORT = t;
20
+ }
14
21
  var server = new McpServer({
15
- name: "RunPod API Server",
16
- version: "1.0.0",
22
+ name: MCP_SERVER_NAME,
23
+ version: MCP_SERVER_VERSION,
17
24
  capabilities: {
18
25
  resources: {},
19
26
  tools: {}
20
27
  }
21
28
  });
29
+ var SESSION_ID = randomUUID();
30
+ function resolveClientInfo() {
31
+ const info = server.server.getClientVersion();
32
+ if (info?.name) {
33
+ return { name: info.name, version: info.version || "unknown" };
34
+ }
35
+ return { name: "unknown", version: "unknown" };
36
+ }
37
+ function sanitizeUaToken(value) {
38
+ return value.replace(/[()<>@,;:\\"/\[\]?={}\s]/g, "_").slice(0, 64);
39
+ }
40
+ function buildUserAgent() {
41
+ const { name, version } = resolveClientInfo();
42
+ const safeName = sanitizeUaToken(name);
43
+ const safeVersion = sanitizeUaToken(version);
44
+ return `runpod-mcp-server/${MCP_SERVER_VERSION} (caller=mcp; client=${safeName}; client_version=${safeVersion}; transport=${MCP_TRANSPORT})`;
45
+ }
46
+ function trackingHeaders() {
47
+ return {
48
+ "User-Agent": buildUserAgent(),
49
+ "X-Runpod-Session-Id": SESSION_ID
50
+ };
51
+ }
52
+ var GRAPHQL_URL = "https://api.runpod.io/graphql";
53
+ async function graphqlRequest(query) {
54
+ const response = await fetch(GRAPHQL_URL, {
55
+ method: "POST",
56
+ headers: {
57
+ "Content-Type": "application/json",
58
+ ...trackingHeaders()
59
+ },
60
+ body: JSON.stringify({ query })
61
+ });
62
+ const result = await response.json();
63
+ if (result.errors && result.errors.length > 0) {
64
+ throw new Error(
65
+ `GraphQL Error: ${result.errors.map((e) => e.message).join(", ")}`
66
+ );
67
+ }
68
+ if (!result.data) {
69
+ throw new Error("No data returned from GraphQL query");
70
+ }
71
+ return result.data;
72
+ }
22
73
  async function runpodRequest(endpoint, method = "GET", body) {
23
74
  const url = `${API_BASE_URL}${endpoint}`;
24
75
  const headers = {
25
76
  Authorization: `Bearer ${API_KEY}`,
26
- "Content-Type": "application/json"
77
+ "Content-Type": "application/json",
78
+ ...trackingHeaders()
27
79
  };
28
80
  const options = {
29
81
  method,
@@ -48,6 +100,156 @@ async function runpodRequest(endpoint, method = "GET", body) {
48
100
  throw error;
49
101
  }
50
102
  }
103
+ server.tool(
104
+ "list-gpu-types",
105
+ {
106
+ minMemoryGb: z.number().optional().describe("Filter to GPUs with at least this much VRAM in GB"),
107
+ secureCloudOnly: z.boolean().optional().describe("Filter to only GPUs available in secure cloud"),
108
+ communityCloudOnly: z.boolean().optional().describe("Filter to only GPUs available in community cloud"),
109
+ searchTerm: z.string().optional().describe(
110
+ "Search term to filter GPUs by name (e.g., 'A100', 'RTX 4090')"
111
+ ),
112
+ includeUnavailable: z.boolean().optional().describe(
113
+ "Include GPUs that are currently out of stock. Default is false"
114
+ )
115
+ },
116
+ async (params) => {
117
+ const data = await graphqlRequest(`
118
+ query {
119
+ gpuTypes {
120
+ id
121
+ displayName
122
+ memoryInGb
123
+ secureCloud
124
+ communityCloud
125
+ lowestPrice(input: { gpuCount: 1 }) {
126
+ stockStatus
127
+ }
128
+ }
129
+ }
130
+ `);
131
+ const stockPriority = {
132
+ High: 3,
133
+ Medium: 2,
134
+ Low: 1
135
+ };
136
+ const isAvailable = (gpu) => {
137
+ const status = gpu.lowestPrice?.stockStatus;
138
+ return !!status && status !== "Out";
139
+ };
140
+ let gpuTypes = data.gpuTypes.filter((gpu) => gpu.id !== "unknown");
141
+ if (!params.includeUnavailable) {
142
+ gpuTypes = gpuTypes.filter(isAvailable);
143
+ }
144
+ if (params.minMemoryGb) {
145
+ gpuTypes = gpuTypes.filter(
146
+ (gpu) => gpu.memoryInGb >= params.minMemoryGb
147
+ );
148
+ }
149
+ if (params.secureCloudOnly) {
150
+ gpuTypes = gpuTypes.filter((gpu) => gpu.secureCloud);
151
+ }
152
+ if (params.communityCloudOnly) {
153
+ gpuTypes = gpuTypes.filter((gpu) => gpu.communityCloud);
154
+ }
155
+ if (params.searchTerm) {
156
+ const term = params.searchTerm.toLowerCase();
157
+ gpuTypes = gpuTypes.filter(
158
+ (gpu) => gpu.id.toLowerCase().includes(term) || gpu.displayName.toLowerCase().includes(term)
159
+ );
160
+ }
161
+ gpuTypes.sort((a, b) => {
162
+ const aP = stockPriority[a.lowestPrice?.stockStatus || ""] || 0;
163
+ const bP = stockPriority[b.lowestPrice?.stockStatus || ""] || 0;
164
+ if (bP !== aP) return bP - aP;
165
+ return b.memoryInGb - a.memoryInGb;
166
+ });
167
+ const result = gpuTypes.map((gpu) => ({
168
+ id: gpu.id,
169
+ displayName: gpu.displayName,
170
+ memoryGb: gpu.memoryInGb,
171
+ secureCloud: gpu.secureCloud,
172
+ communityCloud: gpu.communityCloud,
173
+ stockStatus: gpu.lowestPrice?.stockStatus || "unavailable",
174
+ available: isAvailable(gpu)
175
+ }));
176
+ return {
177
+ content: [
178
+ {
179
+ type: "text",
180
+ text: JSON.stringify(result, null, 2)
181
+ }
182
+ ]
183
+ };
184
+ }
185
+ );
186
+ server.tool(
187
+ "list-data-centers",
188
+ {
189
+ region: z.string().optional().describe(
190
+ "Filter by region/location (e.g., 'United States', 'Europe', 'Canada')"
191
+ )
192
+ },
193
+ async (params) => {
194
+ const data = await graphqlRequest(`
195
+ query {
196
+ dataCenters {
197
+ id
198
+ name
199
+ location
200
+ }
201
+ }
202
+ `);
203
+ let dataCenters = data.dataCenters;
204
+ if (params.region) {
205
+ const term = params.region.toLowerCase();
206
+ dataCenters = dataCenters.filter(
207
+ (dc) => dc.location.toLowerCase().includes(term)
208
+ );
209
+ }
210
+ return {
211
+ content: [
212
+ {
213
+ type: "text",
214
+ text: JSON.stringify(dataCenters, null, 2)
215
+ }
216
+ ]
217
+ };
218
+ }
219
+ );
220
+ var SERVERLESS_API_BASE_URL = "https://api.runpod.ai/v2";
221
+ async function serverlessRequest(endpointId, path, method = "GET", body) {
222
+ const url = `${SERVERLESS_API_BASE_URL}/${endpointId}${path}`;
223
+ const headers = {
224
+ Authorization: `Bearer ${API_KEY}`,
225
+ "Content-Type": "application/json",
226
+ ...trackingHeaders()
227
+ };
228
+ const options = {
229
+ method,
230
+ headers
231
+ };
232
+ if (body && (method === "POST" || method === "PATCH")) {
233
+ options.body = JSON.stringify(body);
234
+ }
235
+ try {
236
+ const response = await fetch(url, options);
237
+ if (!response.ok) {
238
+ const errorText = await response.text();
239
+ throw new Error(
240
+ `RunPod Serverless API Error: ${response.status} - ${errorText}`
241
+ );
242
+ }
243
+ const contentType = response.headers.get("content-type");
244
+ if (contentType && contentType.includes("application/json")) {
245
+ return await response.json();
246
+ }
247
+ return { success: true, status: response.status };
248
+ } catch (error) {
249
+ console.error("Error calling RunPod Serverless API:", error);
250
+ throw error;
251
+ }
252
+ }
51
253
  server.tool(
52
254
  "list-pods",
53
255
  {
@@ -118,6 +320,7 @@ server.tool(
118
320
  );
119
321
  server.tool(
120
322
  "create-pod",
323
+ 'Create a new GPU/CPU pod on RunPod. If the user does not specify an image, recommend the "Runpod Pytorch 2.8.0" image (runpod/pytorch:1.0.2-cu1281-torch280-ubuntu2404) as the default \u2014 it has the most up-to-date CUDA and PyTorch versions.',
121
324
  {
122
325
  name: z.string().optional().describe("Name for the pod"),
123
326
  imageName: z.string().describe("Docker image to use"),
@@ -342,17 +545,298 @@ server.tool(
342
545
  };
343
546
  }
344
547
  );
345
- server.tool("list-templates", {}, async () => {
346
- const result = await runpodRequest("/templates");
347
- return {
348
- content: [
349
- {
350
- type: "text",
351
- text: JSON.stringify(result, null, 2)
548
+ var endpointIdSchema = z.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid endpoint ID format");
549
+ var jobIdSchema = z.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid job ID format");
550
+ var inputSchema = z.record(z.unknown()).describe(
551
+ "Input payload for the worker handler. The expected fields depend on the deployed model or worker."
552
+ );
553
+ var webhookSchema = z.string().url().optional().describe(
554
+ "Webhook URL to receive job completion notifications instead of polling"
555
+ );
556
+ var policySchema = z.object({
557
+ executionTimeout: z.number().optional().describe("Maximum execution time in milliseconds"),
558
+ lowPriority: z.boolean().optional().describe("Submit as a low-priority job"),
559
+ ttl: z.number().optional().describe("Time-to-live for the job result in milliseconds")
560
+ }).optional().describe("Execution policy options");
561
+ var s3ConfigSchema = z.object({
562
+ accessId: z.string().describe("S3 access key ID"),
563
+ accessSecret: z.string().describe("S3 secret access key"),
564
+ bucketName: z.string().describe("S3 bucket name"),
565
+ endpointUrl: z.string().describe("S3 endpoint URL")
566
+ }).optional().describe("S3-compatible storage config for large outputs");
567
+ server.tool(
568
+ "run-endpoint",
569
+ "Submit an asynchronous job to a Serverless endpoint. Returns a job ID immediately \u2014 use get-job-status to poll for results. Async results are available for 30 minutes after completion.",
570
+ {
571
+ endpointId: endpointIdSchema.describe(
572
+ "ID of the Serverless endpoint to run"
573
+ ),
574
+ input: inputSchema,
575
+ webhook: webhookSchema,
576
+ policy: policySchema,
577
+ s3Config: s3ConfigSchema
578
+ },
579
+ async (params) => {
580
+ const { endpointId, ...body } = params;
581
+ const result = await serverlessRequest(
582
+ endpointId,
583
+ "/run",
584
+ "POST",
585
+ body
586
+ );
587
+ return {
588
+ content: [
589
+ {
590
+ type: "text",
591
+ text: JSON.stringify(result, null, 2)
592
+ }
593
+ ]
594
+ };
595
+ }
596
+ );
597
+ server.tool(
598
+ "runsync-endpoint",
599
+ "Submit a synchronous job to a Serverless endpoint and wait for the result. Best for tasks completing within 90 seconds. If processing exceeds 90 seconds, the response returns a job ID to poll with get-job-status. Max payload: 20 MB. Results expire after 1 minute. Use the wait parameter to extend the server-side wait up to 5 minutes (300000 ms).",
600
+ {
601
+ endpointId: endpointIdSchema.describe(
602
+ "ID of the Serverless endpoint to run synchronously"
603
+ ),
604
+ input: inputSchema,
605
+ wait: z.number().min(1e3).max(3e5).optional().describe(
606
+ "How long in milliseconds the server should wait for a result before returning a job ID to poll (1000\u2013300000). Defaults to 90000 (90 seconds)."
607
+ ),
608
+ webhook: webhookSchema,
609
+ policy: policySchema,
610
+ s3Config: s3ConfigSchema
611
+ },
612
+ async (params) => {
613
+ const { endpointId, wait, ...body } = params;
614
+ const path = wait ? `/runsync?wait=${wait}` : "/runsync";
615
+ const result = await serverlessRequest(
616
+ endpointId,
617
+ path,
618
+ "POST",
619
+ body
620
+ );
621
+ return {
622
+ content: [
623
+ {
624
+ type: "text",
625
+ text: JSON.stringify(result, null, 2)
626
+ }
627
+ ]
628
+ };
629
+ }
630
+ );
631
+ server.tool(
632
+ "get-job-status",
633
+ "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.",
634
+ {
635
+ endpointId: endpointIdSchema.describe(
636
+ "ID of the Serverless endpoint the job belongs to"
637
+ ),
638
+ jobId: jobIdSchema.describe("ID of the job to check")
639
+ },
640
+ async (params) => {
641
+ const result = await serverlessRequest(
642
+ params.endpointId,
643
+ `/status/${params.jobId}`
644
+ );
645
+ return {
646
+ content: [
647
+ {
648
+ type: "text",
649
+ text: JSON.stringify(result, null, 2)
650
+ }
651
+ ]
652
+ };
653
+ }
654
+ );
655
+ server.tool(
656
+ "stream-job",
657
+ "Retrieve all streaming output from a Serverless job by polling until the job reaches a terminal state. The worker must support streaming output. Polls /stream/{jobId} repeatedly and collects every chunk until status is COMPLETED, FAILED, CANCELLED, or TIMED_OUT.",
658
+ {
659
+ endpointId: endpointIdSchema.describe(
660
+ "ID of the Serverless endpoint the job belongs to"
661
+ ),
662
+ jobId: jobIdSchema.describe("ID of the job to stream results from")
663
+ },
664
+ async (params) => {
665
+ const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
666
+ "COMPLETED",
667
+ "FAILED",
668
+ "CANCELLED",
669
+ "TIMED_OUT"
670
+ ]);
671
+ const MAX_POLL_TIME_MS = 5 * 60 * 1e3;
672
+ const POLL_INTERVAL_MS = 1e3;
673
+ const MAX_CONSECUTIVE_ERRORS = 5;
674
+ const allChunks = [];
675
+ let finalResult = {};
676
+ let consecutiveErrors = 0;
677
+ const startTime = Date.now();
678
+ while (true) {
679
+ try {
680
+ const result = await serverlessRequest(
681
+ params.endpointId,
682
+ `/stream/${params.jobId}`
683
+ );
684
+ consecutiveErrors = 0;
685
+ if (Array.isArray(result.stream)) {
686
+ allChunks.push(...result.stream);
687
+ }
688
+ finalResult = result;
689
+ if (TERMINAL_STATUSES.has(result.status)) {
690
+ break;
691
+ }
692
+ } catch (error) {
693
+ consecutiveErrors++;
694
+ if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
695
+ finalResult.error = `Polling aborted after ${MAX_CONSECUTIVE_ERRORS} consecutive errors: ${error instanceof Error ? error.message : String(error)}`;
696
+ break;
697
+ }
352
698
  }
353
- ]
354
- };
355
- });
699
+ if (Date.now() - startTime > MAX_POLL_TIME_MS) {
700
+ finalResult.pollingTimedOut = true;
701
+ finalResult.note = "Polling timed out after 5 minutes. Use get-job-status to check the job later.";
702
+ break;
703
+ }
704
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
705
+ }
706
+ return {
707
+ content: [
708
+ {
709
+ type: "text",
710
+ text: JSON.stringify({ ...finalResult, stream: allChunks }, null, 2)
711
+ }
712
+ ]
713
+ };
714
+ }
715
+ );
716
+ server.tool(
717
+ "cancel-job",
718
+ "Cancel a Serverless job that is queued or in progress.",
719
+ {
720
+ endpointId: endpointIdSchema.describe(
721
+ "ID of the Serverless endpoint the job belongs to"
722
+ ),
723
+ jobId: jobIdSchema.describe("ID of the job to cancel")
724
+ },
725
+ async (params) => {
726
+ const result = await serverlessRequest(
727
+ params.endpointId,
728
+ `/cancel/${params.jobId}`,
729
+ "POST"
730
+ );
731
+ return {
732
+ content: [
733
+ {
734
+ type: "text",
735
+ text: JSON.stringify(result, null, 2)
736
+ }
737
+ ]
738
+ };
739
+ }
740
+ );
741
+ server.tool(
742
+ "retry-job",
743
+ "Retry a failed or timed-out Serverless job. Only works for jobs with FAILED or TIMED_OUT status. The previous output is removed and the job is requeued.",
744
+ {
745
+ endpointId: endpointIdSchema.describe(
746
+ "ID of the Serverless endpoint the job belongs to"
747
+ ),
748
+ jobId: jobIdSchema.describe("ID of the job to retry")
749
+ },
750
+ async (params) => {
751
+ const result = await serverlessRequest(
752
+ params.endpointId,
753
+ `/retry/${params.jobId}`,
754
+ "POST"
755
+ );
756
+ return {
757
+ content: [
758
+ {
759
+ type: "text",
760
+ text: JSON.stringify(result, null, 2)
761
+ }
762
+ ]
763
+ };
764
+ }
765
+ );
766
+ server.tool(
767
+ "endpoint-health",
768
+ "Get the health and operational status of a Serverless endpoint, including worker counts and job statistics.",
769
+ {
770
+ endpointId: endpointIdSchema.describe(
771
+ "ID of the Serverless endpoint to check health for"
772
+ )
773
+ },
774
+ async (params) => {
775
+ const result = await serverlessRequest(params.endpointId, "/health");
776
+ return {
777
+ content: [
778
+ {
779
+ type: "text",
780
+ text: JSON.stringify(result, null, 2)
781
+ }
782
+ ]
783
+ };
784
+ }
785
+ );
786
+ server.tool(
787
+ "purge-endpoint-queue",
788
+ "Remove all pending jobs from a Serverless endpoint queue. Only affects queued jobs \u2014 in-progress jobs continue running. Use this for error recovery or clearing outdated requests.",
789
+ {
790
+ endpointId: endpointIdSchema.describe(
791
+ "ID of the Serverless endpoint to purge the queue for"
792
+ )
793
+ },
794
+ async (params) => {
795
+ const result = await serverlessRequest(
796
+ params.endpointId,
797
+ "/purge-queue",
798
+ "POST"
799
+ );
800
+ return {
801
+ content: [
802
+ {
803
+ type: "text",
804
+ text: JSON.stringify(result, null, 2)
805
+ }
806
+ ]
807
+ };
808
+ }
809
+ );
810
+ server.tool(
811
+ "list-templates",
812
+ `List available templates. By default returns only the user's own templates. Use includeRunpodTemplates to also include official RunPod templates. The recommended default template for new pods is "Runpod Pytorch 2.8.0" (ID: runpod-torch-v280) \u2014 it has the latest CUDA and PyTorch versions.`,
813
+ {
814
+ includeRunpodTemplates: z.boolean().optional().describe("Include official RunPod templates in the response"),
815
+ includePublicTemplates: z.boolean().optional().describe("Include community-made public templates in the response"),
816
+ includeEndpointBoundTemplates: z.boolean().optional().describe(
817
+ "Include templates bound to Serverless endpoints in the response"
818
+ )
819
+ },
820
+ async (params) => {
821
+ const queryParams = new URLSearchParams();
822
+ if (params.includeRunpodTemplates)
823
+ queryParams.set("includeRunpodTemplates", "true");
824
+ if (params.includePublicTemplates)
825
+ queryParams.set("includePublicTemplates", "true");
826
+ if (params.includeEndpointBoundTemplates)
827
+ queryParams.set("includeEndpointBoundTemplates", "true");
828
+ const query = queryParams.toString();
829
+ const result = await runpodRequest(`/templates${query ? `?${query}` : ""}`);
830
+ return {
831
+ content: [
832
+ {
833
+ type: "text",
834
+ text: JSON.stringify(result, null, 2)
835
+ }
836
+ ]
837
+ };
838
+ }
839
+ );
356
840
  server.tool(
357
841
  "get-template",
358
842
  {
@@ -612,4 +1096,7 @@ server.tool(
612
1096
  );
613
1097
  var transport = new StdioServerTransport();
614
1098
  server.connect(transport);
1099
+ export {
1100
+ setTransport
1101
+ };
615
1102
  //# sourceMappingURL=index.mjs.map