@runpod/mcp-server 1.2.0 → 1.3.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 +29 -0
- package/README.md +154 -93
- package/dist/chunk-CRHHCQRI.mjs +1108 -0
- package/dist/chunk-CRHHCQRI.mjs.map +1 -0
- package/dist/http.cjs +1224 -0
- package/dist/http.cjs.map +1 -0
- package/dist/http.d.cts +18 -0
- package/dist/http.d.ts +18 -0
- package/dist/http.mjs +88 -0
- package/dist/http.mjs.map +1 -0
- package/dist/stdio.cjs +1158 -0
- package/dist/stdio.cjs.map +1 -0
- package/dist/stdio.d.cts +2 -0
- package/dist/stdio.d.ts +2 -0
- package/dist/stdio.mjs +1135 -0
- package/dist/stdio.mjs.map +1 -0
- package/dist/tools.cjs +1142 -0
- package/dist/tools.cjs.map +1 -0
- package/dist/tools.d.cts +21 -0
- package/dist/tools.d.ts +21 -0
- package/dist/tools.mjs +7 -0
- package/dist/tools.mjs.map +1 -0
- package/package.json +28 -13
- package/dist/index.d.cts +0 -3
- package/dist/index.d.ts +0 -3
- package/dist/index.js +0 -1136
- package/dist/index.js.map +0 -1
- package/dist/index.mjs +0 -1102
- package/dist/index.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/http.ts","../src/server.ts","../src/tools.ts"],"sourcesContent":["import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport { createServer } from './server.js';\nimport { registerTools } from './tools.js';\nimport { IncomingMessage, ServerResponse } from 'node:http';\n\n/**\n * Extract the bearer token from an HTTP request's Authorization header.\n * Returns null if the header is missing or malformed.\n */\nfunction extractBearerToken(req: IncomingMessage): string | null {\n const authHeader = req.headers.authorization;\n if (!authHeader) return null;\n const parts = authHeader.split(' ');\n if (parts.length !== 2 || parts[0].toLowerCase() !== 'bearer') return null;\n return parts[1];\n}\n\nfunction getBaseUrl(req: IncomingMessage): string {\n const proto =\n (req.headers['x-forwarded-proto'] as string | undefined)?.split(',')[0] ??\n 'https';\n const host = req.headers.host;\n if (!host) {\n throw new Error('Missing Host header');\n }\n\n return `${proto}://${host}`;\n}\n\nfunction writeUnauthorized(\n req: IncomingMessage,\n res: ServerResponse,\n error: string\n): void {\n // Always advertise the protected-resource metadata so OAuth-capable clients\n // (e.g. Claude) know to start the \"Sign in with Runpod\" flow. Callers who\n // bring their own API key as the bearer token simply never hit this path.\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'WWW-Authenticate': `Bearer realm=\"mcp\", resource_metadata=\"${getBaseUrl(\n req\n )}/.well-known/oauth-protected-resource\"`,\n };\n\n res.writeHead(401, headers);\n res.end(JSON.stringify({ error }));\n}\n\n/**\n * Handle an incoming HTTP request as a streamable MCP session.\n *\n * Each request gets its own McpServer + transport. The caller's Bearer token\n * is forwarded directly to the Runpod API as the credential — it may be a\n * Runpod API key (set manually by the caller) or a token obtained through the\n * OAuth \"Sign in with Runpod\" flow. The server holds no credential of its own\n * and never shares one across users.\n */\nexport async function handleMcpRequest(\n req: IncomingMessage,\n res: ServerResponse,\n opts: { serverVersion?: string } = {}\n): Promise<void> {\n const bearerToken = extractBearerToken(req);\n console.log('mcp_request', {\n method: req.method,\n url: req.url,\n hasBearerToken: !!bearerToken,\n });\n if (!bearerToken) {\n writeUnauthorized(\n req,\n res,\n 'Missing or invalid Authorization header. Provide a Bearer token.'\n );\n return;\n }\n\n const server = createServer(opts.serverVersion);\n // In stateless HTTP, a tools/call is a separate request from `initialize`, so\n // the per-request server never sees the MCP `clientInfo`. Fall back to the\n // inbound HTTP User-Agent so caller-tracking still attributes the client.\n registerTools(server, {\n apiKey: bearerToken,\n transport: 'http',\n clientUserAgent: req.headers['user-agent'],\n serverVersion: opts.serverVersion,\n });\n\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — no session persistence\n });\n\n // This per-request server/transport pair is single-use; dispose it when the\n // response closes so listeners don't accumulate on a warm serverless instance.\n res.on('close', () => {\n transport.close().catch(() => {});\n server.close().catch(() => {});\n });\n\n await server.connect(transport);\n // Pass the already-parsed body when the host provides one (e.g. Vercel's\n // VercelRequest exposes `req.body`); the SDK reads the raw stream otherwise.\n await transport.handleRequest(req, res, (req as { body?: unknown }).body);\n}\n\nexport { registerTools } from './tools.js';\nexport type { ToolContext } from './tools.js';\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\n// `__PACKAGE_VERSION__` is replaced at build time by tsup's `define` with the\n// current `version` from package.json. Falls back to `'dev'` when the\n// substitution doesn't happen (e.g. running via tsx).\ndeclare const __PACKAGE_VERSION__: string;\n\nexport const SERVER_NAME = 'Runpod API Server';\nexport const SERVER_VERSION =\n typeof __PACKAGE_VERSION__ !== 'undefined' ? __PACKAGE_VERSION__ : 'dev';\n\n// `version` defaults to the build-time value (correct for the npm/stdio build).\n// The hosted entrypoint passes a runtime value read from package.json, since\n// tsup's define doesn't run when Vercel compiles api/index.ts.\nexport function createServer(version: string = SERVER_VERSION): McpServer {\n return new McpServer({\n name: SERVER_NAME,\n version,\n capabilities: {\n resources: {},\n tools: {},\n },\n });\n}\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport fetch, { type RequestInit as NodeFetchRequestInit } from 'node-fetch';\nimport { randomUUID } from 'node:crypto';\n\n// Base URL for Runpod REST API. Override via RUNPOD_REST_API_URL to point at a\n// non-production environment (e.g. when authenticating with a dev API key).\nconst API_BASE_URL =\n process.env.RUNPOD_REST_API_URL ?? 'https://rest.runpod.io/v1';\n\n// Serverless API base URL for endpoint runtime operations (run, status, cancel, etc.).\n// Override via RUNPOD_SERVERLESS_API_URL for non-production environments.\nconst SERVERLESS_API_BASE_URL =\n process.env.RUNPOD_SERVERLESS_API_URL ?? 'https://api.runpod.ai/v2';\n\n// GraphQL endpoint for public queries (GPU types, data centers). Override via\n// RUNPOD_PUBLIC_GRAPHQL_URL for non-production environments. This is distinct\n// from the flash auth backend (RUNPOD_GRAPHQL_URL, used only by the OAuth flow\n// in api/index.ts).\nconst GRAPHQL_URL =\n process.env.RUNPOD_PUBLIC_GRAPHQL_URL ?? 'https://api.runpod.io/graphql';\n\n// ============== CALLER TRACKING ==============\n// Adds structured caller identification to every outbound API call so the\n// Runpod platform can attribute traffic to a specific MCP client (Claude Code,\n// Cursor, Codex, Gemini CLI, etc.) and count distinct agent sessions. Pure\n// observability — no tool behavior changes.\n//\n// `__PACKAGE_VERSION__` is replaced at build time by tsup's `define` with the\n// current `version` from package.json. Falls back to `'dev'` when the\n// substitution doesn't happen (e.g. `pnpm dev` via tsx).\ndeclare const __PACKAGE_VERSION__: string;\nconst MCP_SERVER_VERSION =\n typeof __PACKAGE_VERSION__ !== 'undefined' ? __PACKAGE_VERSION__ : 'dev';\n\n// One session ID per server process. Anonymous; lets the data side count\n// distinct agent sessions without per-user attribution.\nconst SESSION_ID = randomUUID();\n\n/**\n * Sanitizes a value for inclusion in a User-Agent token. RFC 7230 reserves\n * parens and a few other chars; strip them so the structured UA stays\n * parseable, and bound the length so a hostile client can't blow up a header.\n */\nfunction sanitizeUaToken(value: string): string {\n return value.replace(/[()<>@,;:\\\\\"/[\\]?={}\\s]/g, '_').slice(0, 64);\n}\n\n/**\n * Builds the headers that identify the calling MCP client and session on every\n * outbound HTTP call. Client identity comes from the `initialize` handshake's\n * `clientInfo` (exposed by the SDK via `server.server.getClientVersion()`),\n * which works for the long-lived stdio server. In stateless HTTP that handshake\n * is on a different request, so we fall back to the inbound HTTP User-Agent.\n */\nfunction trackingHeaders(\n server: McpServer,\n ctx: ToolContext\n): Record<string, string> {\n const info = server.server.getClientVersion();\n const fallbackName = ctx.clientUserAgent || 'unknown';\n const name = sanitizeUaToken(info?.name || fallbackName);\n const version = sanitizeUaToken(info?.version || 'unknown');\n // Prefer a server version supplied by the caller (the hosted entrypoint reads\n // it from package.json at runtime, since tsup's build-time define does not\n // run when Vercel compiles api/index.ts). Fall back to the build-time value.\n const serverVersion = ctx.serverVersion || MCP_SERVER_VERSION;\n const userAgent = `runpod-mcp-server/${serverVersion} (caller=mcp; client=${name}; client_version=${version}; transport=${ctx.transport})`;\n return {\n 'User-Agent': userAgent,\n 'X-Runpod-Session-Id': SESSION_ID,\n };\n}\n\n/**\n * Context passed to every tool handler. Contains the API key used to\n * authenticate against the Runpod REST and Serverless APIs, the transport the\n * server is running under, and (for stateless HTTP) the inbound client\n * User-Agent — all used for outbound caller-tracking headers.\n */\nexport interface ToolContext {\n apiKey: string;\n transport: 'stdio' | 'http';\n clientUserAgent?: string;\n serverVersion?: string;\n}\n\n// Helper function to make GraphQL requests to Runpod (public, no auth required)\nasync function graphqlRequest<T>(\n query: string,\n tracking: () => Record<string, string>\n): Promise<T> {\n const response = await fetch(GRAPHQL_URL, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...tracking(),\n },\n body: JSON.stringify({ query }),\n });\n\n const result = (await response.json()) as {\n data?: T;\n errors?: Array<{ message: string }>;\n };\n\n if (result.errors && result.errors.length > 0) {\n throw new Error(\n `GraphQL Error: ${result.errors.map((e) => e.message).join(', ')}`\n );\n }\n\n if (!result.data) {\n throw new Error('No data returned from GraphQL query');\n }\n\n return result.data;\n}\n\n// Helper function to make authenticated API requests to Runpod REST API\nfunction createRunpodRequest(\n apiKey: string,\n tracking: () => Record<string, string>\n) {\n return async function runpodRequest(\n endpoint: string,\n method: string = 'GET',\n body?: Record<string, unknown>\n ) {\n const url = `${API_BASE_URL}${endpoint}`;\n const headers = {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n ...tracking(),\n };\n\n const options: NodeFetchRequestInit = {\n method,\n headers,\n };\n\n if (body && (method === 'POST' || method === 'PATCH')) {\n options.body = JSON.stringify(body);\n }\n\n try {\n const response = await fetch(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Runpod API Error: ${response.status} - ${errorText}`);\n }\n\n // Some endpoints might not return JSON\n const contentType = response.headers.get('content-type');\n if (contentType && contentType.includes('application/json')) {\n return await response.json();\n }\n\n return { success: true, status: response.status };\n } catch (error) {\n console.error('Error calling Runpod API:', error);\n throw error;\n }\n };\n}\n\n// Helper function to make authenticated requests to the Serverless runtime API\nfunction createServerlessRequest(\n apiKey: string,\n tracking: () => Record<string, string>\n) {\n return async function serverlessRequest(\n endpointId: string,\n path: string,\n method: string = 'GET',\n body?: Record<string, unknown>\n ) {\n const url = `${SERVERLESS_API_BASE_URL}/${endpointId}${path}`;\n const headers: Record<string, string> = {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n ...tracking(),\n };\n\n const options: NodeFetchRequestInit = {\n method,\n headers,\n };\n\n if (body && (method === 'POST' || method === 'PATCH')) {\n options.body = JSON.stringify(body);\n }\n\n try {\n const response = await fetch(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Runpod Serverless API Error: ${response.status} - ${errorText}`\n );\n }\n\n const contentType = response.headers.get('content-type');\n if (contentType && contentType.includes('application/json')) {\n return await response.json();\n }\n\n return { success: true, status: response.status };\n } catch (error) {\n console.error('Error calling Runpod Serverless API:', error);\n throw error;\n }\n };\n}\n\n/**\n * Register all Runpod tools on the given MCP server instance. The provided\n * context supplies the API key that authenticated request helpers will use.\n */\nexport function registerTools(server: McpServer, ctx: ToolContext): void {\n const tracking = () => trackingHeaders(server, ctx);\n const runpodRequest = createRunpodRequest(ctx.apiKey, tracking);\n const serverlessRequest = createServerlessRequest(ctx.apiKey, tracking);\n\n // ============== INFRASTRUCTURE TOOLS ==============\n\n // List GPU Types\n server.tool(\n 'list-gpu-types',\n {\n minMemoryGb: z\n .number()\n .optional()\n .describe('Filter to GPUs with at least this much VRAM in GB'),\n secureCloudOnly: z\n .boolean()\n .optional()\n .describe('Filter to only GPUs available in secure cloud'),\n communityCloudOnly: z\n .boolean()\n .optional()\n .describe('Filter to only GPUs available in community cloud'),\n searchTerm: z\n .string()\n .optional()\n .describe(\n \"Search term to filter GPUs by name (e.g., 'A100', 'RTX 4090')\"\n ),\n includeUnavailable: z\n .boolean()\n .optional()\n .describe(\n 'Include GPUs that are currently out of stock. Default is false'\n ),\n },\n async (params) => {\n interface GpuTypesResponse {\n gpuTypes: Array<{\n id: string;\n displayName: string;\n memoryInGb: number;\n secureCloud: boolean;\n communityCloud: boolean;\n lowestPrice?: { stockStatus: string | null } | null;\n }>;\n }\n\n const data = await graphqlRequest<GpuTypesResponse>(\n `\n query {\n gpuTypes {\n id\n displayName\n memoryInGb\n secureCloud\n communityCloud\n lowestPrice(input: { gpuCount: 1 }) {\n stockStatus\n }\n }\n }\n `,\n tracking\n );\n\n const stockPriority: Record<string, number> = {\n High: 3,\n Medium: 2,\n Low: 1,\n };\n\n const isAvailable = (gpu: GpuTypesResponse['gpuTypes'][number]) => {\n const status = gpu.lowestPrice?.stockStatus;\n return !!status && status !== 'Out';\n };\n\n let gpuTypes = data.gpuTypes.filter((gpu) => gpu.id !== 'unknown');\n\n if (!params.includeUnavailable) {\n gpuTypes = gpuTypes.filter(isAvailable);\n }\n if (params.minMemoryGb) {\n gpuTypes = gpuTypes.filter(\n (gpu) => gpu.memoryInGb >= params.minMemoryGb!\n );\n }\n if (params.secureCloudOnly) {\n gpuTypes = gpuTypes.filter((gpu) => gpu.secureCloud);\n }\n if (params.communityCloudOnly) {\n gpuTypes = gpuTypes.filter((gpu) => gpu.communityCloud);\n }\n if (params.searchTerm) {\n const term = params.searchTerm.toLowerCase();\n gpuTypes = gpuTypes.filter(\n (gpu) =>\n gpu.id.toLowerCase().includes(term) ||\n gpu.displayName.toLowerCase().includes(term)\n );\n }\n\n gpuTypes.sort((a, b) => {\n const aP = stockPriority[a.lowestPrice?.stockStatus || ''] || 0;\n const bP = stockPriority[b.lowestPrice?.stockStatus || ''] || 0;\n if (bP !== aP) return bP - aP;\n return b.memoryInGb - a.memoryInGb;\n });\n\n const result = gpuTypes.map((gpu) => ({\n id: gpu.id,\n displayName: gpu.displayName,\n memoryGb: gpu.memoryInGb,\n secureCloud: gpu.secureCloud,\n communityCloud: gpu.communityCloud,\n stockStatus: gpu.lowestPrice?.stockStatus || 'unavailable',\n available: isAvailable(gpu),\n }));\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // List Data Centers\n server.tool(\n 'list-data-centers',\n {\n region: z\n .string()\n .optional()\n .describe(\n \"Filter by region/location (e.g., 'United States', 'Europe', 'Canada')\"\n ),\n },\n async (params) => {\n interface DataCentersResponse {\n dataCenters: Array<{\n id: string;\n name: string;\n location: string;\n }>;\n }\n\n const data = await graphqlRequest<DataCentersResponse>(\n `\n query {\n dataCenters {\n id\n name\n location\n }\n }\n `,\n tracking\n );\n\n let dataCenters = data.dataCenters;\n\n if (params.region) {\n const term = params.region.toLowerCase();\n dataCenters = dataCenters.filter((dc) =>\n dc.location.toLowerCase().includes(term)\n );\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(dataCenters, null, 2),\n },\n ],\n };\n }\n );\n\n // ============== POD MANAGEMENT TOOLS ==============\n\n // List Pods\n server.tool(\n 'list-pods',\n {\n computeType: z\n .enum(['GPU', 'CPU'])\n .optional()\n .describe('Filter to only GPU or only CPU Pods'),\n gpuTypeId: z\n .array(z.string())\n .optional()\n .describe('Filter to Pods with any of the listed GPU types'),\n dataCenterId: z\n .array(z.string())\n .optional()\n .describe('Filter to Pods in any of the provided data centers'),\n name: z\n .string()\n .optional()\n .describe('Filter to Pods with the provided name'),\n includeMachine: z\n .boolean()\n .optional()\n .describe('Include information about the machine'),\n includeNetworkVolume: z\n .boolean()\n .optional()\n .describe('Include information about attached network volumes'),\n },\n async (params) => {\n const queryParams = new URLSearchParams();\n\n if (params.computeType)\n queryParams.append('computeType', params.computeType);\n if (params.gpuTypeId)\n params.gpuTypeId.forEach((type) =>\n queryParams.append('gpuTypeId', type)\n );\n if (params.dataCenterId)\n params.dataCenterId.forEach((dc) =>\n queryParams.append('dataCenterId', dc)\n );\n if (params.name) queryParams.append('name', params.name);\n if (params.includeMachine)\n queryParams.append('includeMachine', params.includeMachine.toString());\n if (params.includeNetworkVolume)\n queryParams.append(\n 'includeNetworkVolume',\n params.includeNetworkVolume.toString()\n );\n\n const queryString = queryParams.toString()\n ? `?${queryParams.toString()}`\n : '';\n const result = await runpodRequest(`/pods${queryString}`);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Get Pod Details\n server.tool(\n 'get-pod',\n {\n podId: z.string().describe('ID of the pod to retrieve'),\n includeMachine: z\n .boolean()\n .optional()\n .describe('Include information about the machine'),\n includeNetworkVolume: z\n .boolean()\n .optional()\n .describe('Include information about attached network volumes'),\n },\n async (params) => {\n const queryParams = new URLSearchParams();\n\n if (params.includeMachine)\n queryParams.append('includeMachine', params.includeMachine.toString());\n if (params.includeNetworkVolume)\n queryParams.append(\n 'includeNetworkVolume',\n params.includeNetworkVolume.toString()\n );\n\n const queryString = queryParams.toString()\n ? `?${queryParams.toString()}`\n : '';\n const result = await runpodRequest(`/pods/${params.podId}${queryString}`);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Create Pod\n server.tool(\n 'create-pod',\n '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 — it has the most up-to-date CUDA and PyTorch versions.',\n {\n name: z.string().optional().describe('Name for the pod'),\n imageName: z.string().describe('Docker image to use'),\n cloudType: z\n .enum(['SECURE', 'COMMUNITY'])\n .optional()\n .describe('SECURE or COMMUNITY cloud'),\n gpuTypeIds: z\n .array(z.string())\n .optional()\n .describe('List of acceptable GPU types'),\n gpuCount: z.number().optional().describe('Number of GPUs'),\n containerDiskInGb: z\n .number()\n .optional()\n .describe('Container disk size in GB'),\n volumeInGb: z.number().optional().describe('Volume size in GB'),\n volumeMountPath: z\n .string()\n .optional()\n .describe('Path to mount the volume'),\n ports: z\n .array(z.string())\n .optional()\n .describe(\"Ports to expose (e.g., '8888/http', '22/tcp')\"),\n env: z.record(z.string()).optional().describe('Environment variables'),\n dataCenterIds: z\n .array(z.string())\n .optional()\n .describe('List of data centers'),\n },\n async (params) => {\n const result = await runpodRequest('/pods', 'POST', params);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Update Pod\n server.tool(\n 'update-pod',\n {\n podId: z.string().describe('ID of the pod to update'),\n name: z.string().optional().describe('New name for the pod'),\n imageName: z.string().optional().describe('New Docker image'),\n containerDiskInGb: z\n .number()\n .optional()\n .describe('New container disk size in GB'),\n volumeInGb: z.number().optional().describe('New volume size in GB'),\n volumeMountPath: z\n .string()\n .optional()\n .describe('New path to mount the volume'),\n ports: z.array(z.string()).optional().describe('New ports to expose'),\n env: z\n .record(z.string())\n .optional()\n .describe('New environment variables'),\n },\n async (params) => {\n const { podId, ...updateParams } = params;\n const result = await runpodRequest(\n `/pods/${podId}`,\n 'PATCH',\n updateParams\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Start Pod\n server.tool(\n 'start-pod',\n {\n podId: z.string().describe('ID of the pod to start'),\n },\n async (params) => {\n const result = await runpodRequest(`/pods/${params.podId}/start`, 'POST');\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Stop Pod\n server.tool(\n 'stop-pod',\n {\n podId: z.string().describe('ID of the pod to stop'),\n },\n async (params) => {\n const result = await runpodRequest(`/pods/${params.podId}/stop`, 'POST');\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Delete Pod\n server.tool(\n 'delete-pod',\n {\n podId: z.string().describe('ID of the pod to delete'),\n },\n async (params) => {\n const result = await runpodRequest(`/pods/${params.podId}`, 'DELETE');\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // ============== ENDPOINT MANAGEMENT TOOLS ==============\n\n // List Endpoints\n server.tool(\n 'list-endpoints',\n {\n includeTemplate: z\n .boolean()\n .optional()\n .describe('Include template information'),\n includeWorkers: z\n .boolean()\n .optional()\n .describe('Include information about workers'),\n },\n async (params) => {\n const queryParams = new URLSearchParams();\n\n if (params.includeTemplate)\n queryParams.append(\n 'includeTemplate',\n params.includeTemplate.toString()\n );\n if (params.includeWorkers)\n queryParams.append('includeWorkers', params.includeWorkers.toString());\n\n const queryString = queryParams.toString()\n ? `?${queryParams.toString()}`\n : '';\n const result = await runpodRequest(`/endpoints${queryString}`);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Get Endpoint Details\n server.tool(\n 'get-endpoint',\n {\n endpointId: z.string().describe('ID of the endpoint to retrieve'),\n includeTemplate: z\n .boolean()\n .optional()\n .describe('Include template information'),\n includeWorkers: z\n .boolean()\n .optional()\n .describe('Include information about workers'),\n },\n async (params) => {\n const queryParams = new URLSearchParams();\n\n if (params.includeTemplate)\n queryParams.append(\n 'includeTemplate',\n params.includeTemplate.toString()\n );\n if (params.includeWorkers)\n queryParams.append('includeWorkers', params.includeWorkers.toString());\n\n const queryString = queryParams.toString()\n ? `?${queryParams.toString()}`\n : '';\n const result = await runpodRequest(\n `/endpoints/${params.endpointId}${queryString}`\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Create Endpoint\n server.tool(\n 'create-endpoint',\n {\n name: z.string().optional().describe('Name for the endpoint'),\n templateId: z.string().describe('Template ID to use'),\n computeType: z\n .enum(['GPU', 'CPU'])\n .optional()\n .describe('GPU or CPU endpoint'),\n gpuTypeIds: z\n .array(z.string())\n .optional()\n .describe('List of acceptable GPU types'),\n gpuCount: z.number().optional().describe('Number of GPUs per worker'),\n workersMin: z.number().optional().describe('Minimum number of workers'),\n workersMax: z.number().optional().describe('Maximum number of workers'),\n dataCenterIds: z\n .array(z.string())\n .optional()\n .describe('List of data centers'),\n },\n async (params) => {\n const result = await runpodRequest('/endpoints', 'POST', params);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Update Endpoint\n server.tool(\n 'update-endpoint',\n {\n endpointId: z.string().describe('ID of the endpoint to update'),\n name: z.string().optional().describe('New name for the endpoint'),\n workersMin: z\n .number()\n .optional()\n .describe('New minimum number of workers'),\n workersMax: z\n .number()\n .optional()\n .describe('New maximum number of workers'),\n idleTimeout: z\n .number()\n .optional()\n .describe('New idle timeout in seconds'),\n scalerType: z\n .enum(['QUEUE_DELAY', 'REQUEST_COUNT'])\n .optional()\n .describe('Scaler type'),\n scalerValue: z.number().optional().describe('Scaler value'),\n },\n async (params) => {\n const { endpointId, ...updateParams } = params;\n const result = await runpodRequest(\n `/endpoints/${endpointId}`,\n 'PATCH',\n updateParams\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Delete Endpoint\n server.tool(\n 'delete-endpoint',\n {\n endpointId: z.string().describe('ID of the endpoint to delete'),\n },\n async (params) => {\n const result = await runpodRequest(\n `/endpoints/${params.endpointId}`,\n 'DELETE'\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // ============== SERVERLESS RUNTIME TOOLS ==============\n\n // Shared schemas for serverless tools\n const endpointIdSchema = z\n .string()\n .regex(/^[a-zA-Z0-9_-]+$/, 'Invalid endpoint ID format');\n\n const jobIdSchema = z\n .string()\n .regex(/^[a-zA-Z0-9_-]+$/, 'Invalid job ID format');\n\n const inputSchema = z\n .record(z.unknown())\n .describe(\n 'Input payload for the worker handler. The expected fields depend on the deployed model or worker.'\n );\n\n const webhookSchema = z\n .string()\n .url()\n .optional()\n .describe(\n 'Webhook URL to receive job completion notifications instead of polling'\n );\n\n const policySchema = z\n .object({\n executionTimeout: z\n .number()\n .optional()\n .describe('Maximum execution time in milliseconds'),\n lowPriority: z\n .boolean()\n .optional()\n .describe('Submit as a low-priority job'),\n ttl: z\n .number()\n .optional()\n .describe('Time-to-live for the job result in milliseconds'),\n })\n .optional()\n .describe('Execution policy options');\n\n const s3ConfigSchema = z\n .object({\n accessId: z.string().describe('S3 access key ID'),\n accessSecret: z.string().describe('S3 secret access key'),\n bucketName: z.string().describe('S3 bucket name'),\n endpointUrl: z.string().describe('S3 endpoint URL'),\n })\n .optional()\n .describe('S3-compatible storage config for large outputs');\n\n // Run Endpoint (Async)\n server.tool(\n 'run-endpoint',\n 'Submit an asynchronous job to a Serverless endpoint. Returns a job ID immediately — use get-job-status to poll for results. Async results are available for 30 minutes after completion.',\n {\n endpointId: endpointIdSchema.describe(\n 'ID of the Serverless endpoint to run'\n ),\n input: inputSchema,\n webhook: webhookSchema,\n policy: policySchema,\n s3Config: s3ConfigSchema,\n },\n async (params) => {\n const { endpointId, ...body } = params;\n const result = await serverlessRequest(\n endpointId,\n '/run',\n 'POST',\n body as Record<string, unknown>\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Run Endpoint Sync\n server.tool(\n 'runsync-endpoint',\n '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).',\n {\n endpointId: endpointIdSchema.describe(\n 'ID of the Serverless endpoint to run synchronously'\n ),\n input: inputSchema,\n wait: z\n .number()\n .min(1000)\n .max(300000)\n .optional()\n .describe(\n 'How long in milliseconds the server should wait for a result before returning a job ID to poll (1000–300000). Defaults to 90000 (90 seconds).'\n ),\n webhook: webhookSchema,\n policy: policySchema,\n s3Config: s3ConfigSchema,\n },\n async (params) => {\n const { endpointId, wait, ...body } = params;\n const path = wait ? `/runsync?wait=${wait}` : '/runsync';\n const result = await serverlessRequest(\n endpointId,\n path,\n 'POST',\n body as Record<string, unknown>\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Get Job Status\n server.tool(\n 'get-job-status',\n '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.',\n {\n endpointId: endpointIdSchema.describe(\n 'ID of the Serverless endpoint the job belongs to'\n ),\n jobId: jobIdSchema.describe('ID of the job to check'),\n },\n async (params) => {\n const result = await serverlessRequest(\n params.endpointId,\n `/status/${params.jobId}`\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Stream Job Results\n server.tool(\n 'stream-job',\n '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.',\n {\n endpointId: endpointIdSchema.describe(\n 'ID of the Serverless endpoint the job belongs to'\n ),\n jobId: jobIdSchema.describe('ID of the job to stream results from'),\n },\n async (params) => {\n const TERMINAL_STATUSES = new Set([\n 'COMPLETED',\n 'FAILED',\n 'CANCELLED',\n 'TIMED_OUT',\n ]);\n const MAX_POLL_TIME_MS = 5 * 60 * 1000; // 5 minutes\n const POLL_INTERVAL_MS = 1000;\n const MAX_CONSECUTIVE_ERRORS = 5;\n const allChunks: unknown[] = [];\n let finalResult: Record<string, unknown> = {};\n let consecutiveErrors = 0;\n let lastError: string | undefined;\n const startTime = Date.now();\n\n while (true) {\n try {\n const result = (await serverlessRequest(\n params.endpointId,\n `/stream/${params.jobId}`\n )) as Record<string, unknown>;\n\n consecutiveErrors = 0;\n\n if (Array.isArray(result.stream)) {\n allChunks.push(...result.stream);\n }\n\n finalResult = result;\n\n if (TERMINAL_STATUSES.has(result.status as string)) {\n break;\n }\n } catch (error) {\n consecutiveErrors++;\n lastError = error instanceof Error ? error.message : String(error);\n if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {\n finalResult.error = `Polling aborted after ${MAX_CONSECUTIVE_ERRORS} consecutive errors: ${lastError}`;\n break;\n }\n }\n\n if (Date.now() - startTime > MAX_POLL_TIME_MS) {\n finalResult.pollingTimedOut = true;\n finalResult.note =\n 'Polling timed out after 5 minutes. Use get-job-status to check the job later.';\n // Surface the most recent error (if any) instead of discarding it —\n // the last poll may have been failing (e.g. job expired) even though\n // earlier polls succeeded.\n if (lastError) finalResult.lastError = lastError;\n break;\n }\n\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n { ...finalResult, stream: allChunks },\n null,\n 2\n ),\n },\n ],\n };\n }\n );\n\n // Cancel Job\n server.tool(\n 'cancel-job',\n 'Cancel a Serverless job that is queued or in progress.',\n {\n endpointId: endpointIdSchema.describe(\n 'ID of the Serverless endpoint the job belongs to'\n ),\n jobId: jobIdSchema.describe('ID of the job to cancel'),\n },\n async (params) => {\n const result = await serverlessRequest(\n params.endpointId,\n `/cancel/${params.jobId}`,\n 'POST'\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Retry Job\n server.tool(\n 'retry-job',\n '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.',\n {\n endpointId: endpointIdSchema.describe(\n 'ID of the Serverless endpoint the job belongs to'\n ),\n jobId: jobIdSchema.describe('ID of the job to retry'),\n },\n async (params) => {\n const result = await serverlessRequest(\n params.endpointId,\n `/retry/${params.jobId}`,\n 'POST'\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Endpoint Health\n server.tool(\n 'endpoint-health',\n 'Get the health and operational status of a Serverless endpoint, including worker counts and job statistics.',\n {\n endpointId: endpointIdSchema.describe(\n 'ID of the Serverless endpoint to check health for'\n ),\n },\n async (params) => {\n const result = await serverlessRequest(params.endpointId, '/health');\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Purge Endpoint Queue\n server.tool(\n 'purge-endpoint-queue',\n 'Remove all pending jobs from a Serverless endpoint queue. Only affects queued jobs — in-progress jobs continue running. Use this for error recovery or clearing outdated requests.',\n {\n endpointId: endpointIdSchema.describe(\n 'ID of the Serverless endpoint to purge the queue for'\n ),\n },\n async (params) => {\n const result = await serverlessRequest(\n params.endpointId,\n '/purge-queue',\n 'POST'\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // ============== TEMPLATE MANAGEMENT TOOLS ==============\n\n // List Templates\n server.tool(\n 'list-templates',\n '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) — it has the latest CUDA and PyTorch versions.',\n {\n includeRunpodTemplates: z\n .boolean()\n .optional()\n .describe('Include official Runpod templates in the response'),\n includePublicTemplates: z\n .boolean()\n .optional()\n .describe('Include community-made public templates in the response'),\n includeEndpointBoundTemplates: z\n .boolean()\n .optional()\n .describe(\n 'Include templates bound to Serverless endpoints in the response'\n ),\n },\n async (params) => {\n const queryParams = new URLSearchParams();\n if (params.includeRunpodTemplates)\n queryParams.set('includeRunpodTemplates', 'true');\n if (params.includePublicTemplates)\n queryParams.set('includePublicTemplates', 'true');\n if (params.includeEndpointBoundTemplates)\n queryParams.set('includeEndpointBoundTemplates', 'true');\n const query = queryParams.toString();\n const result = await runpodRequest(\n `/templates${query ? `?${query}` : ''}`\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Get Template Details\n server.tool(\n 'get-template',\n {\n templateId: z.string().describe('ID of the template to retrieve'),\n },\n async (params) => {\n const result = await runpodRequest(`/templates/${params.templateId}`);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Create Template\n server.tool(\n 'create-template',\n {\n name: z.string().describe('Name for the template'),\n imageName: z.string().describe('Docker image to use'),\n isServerless: z\n .boolean()\n .optional()\n .describe('Is this a serverless template'),\n ports: z.array(z.string()).optional().describe('Ports to expose'),\n dockerEntrypoint: z\n .array(z.string())\n .optional()\n .describe('Docker entrypoint commands'),\n dockerStartCmd: z\n .array(z.string())\n .optional()\n .describe('Docker start commands'),\n env: z.record(z.string()).optional().describe('Environment variables'),\n containerDiskInGb: z\n .number()\n .optional()\n .describe('Container disk size in GB'),\n volumeInGb: z.number().optional().describe('Volume size in GB'),\n volumeMountPath: z\n .string()\n .optional()\n .describe('Path to mount the volume'),\n readme: z\n .string()\n .optional()\n .describe('README content in markdown format'),\n },\n async (params) => {\n const result = await runpodRequest('/templates', 'POST', params);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Update Template\n server.tool(\n 'update-template',\n {\n templateId: z.string().describe('ID of the template to update'),\n name: z.string().optional().describe('New name for the template'),\n imageName: z.string().optional().describe('New Docker image'),\n ports: z.array(z.string()).optional().describe('New ports to expose'),\n env: z\n .record(z.string())\n .optional()\n .describe('New environment variables'),\n readme: z\n .string()\n .optional()\n .describe('New README content in markdown format'),\n },\n async (params) => {\n const { templateId, ...updateParams } = params;\n const result = await runpodRequest(\n `/templates/${templateId}`,\n 'PATCH',\n updateParams\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Delete Template\n server.tool(\n 'delete-template',\n {\n templateId: z.string().describe('ID of the template to delete'),\n },\n async (params) => {\n const result = await runpodRequest(\n `/templates/${params.templateId}`,\n 'DELETE'\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // ============== NETWORK VOLUME MANAGEMENT TOOLS ==============\n\n // List Network Volumes\n server.tool('list-network-volumes', {}, async () => {\n const result = await runpodRequest('/networkvolumes');\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n });\n\n // Get Network Volume Details\n server.tool(\n 'get-network-volume',\n {\n networkVolumeId: z\n .string()\n .describe('ID of the network volume to retrieve'),\n },\n async (params) => {\n const result = await runpodRequest(\n `/networkvolumes/${params.networkVolumeId}`\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Create Network Volume\n server.tool(\n 'create-network-volume',\n {\n name: z.string().describe('Name for the network volume'),\n size: z.number().describe('Size in GB (1-4000)'),\n dataCenterId: z.string().describe('Data center ID'),\n },\n async (params) => {\n const result = await runpodRequest('/networkvolumes', 'POST', params);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Update Network Volume\n server.tool(\n 'update-network-volume',\n {\n networkVolumeId: z\n .string()\n .describe('ID of the network volume to update'),\n name: z.string().optional().describe('New name for the network volume'),\n size: z\n .number()\n .optional()\n .describe('New size in GB (must be larger than current)'),\n },\n async (params) => {\n const { networkVolumeId, ...updateParams } = params;\n const result = await runpodRequest(\n `/networkvolumes/${networkVolumeId}`,\n 'PATCH',\n updateParams\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Delete Network Volume\n server.tool(\n 'delete-network-volume',\n {\n networkVolumeId: z\n .string()\n .describe('ID of the network volume to delete'),\n },\n async (params) => {\n const result = await runpodRequest(\n `/networkvolumes/${params.networkVolumeId}`,\n 'DELETE'\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // ============== CONTAINER REGISTRY AUTH TOOLS ==============\n\n // List Container Registry Auths\n server.tool('list-container-registry-auths', {}, async () => {\n const result = await runpodRequest('/containerregistryauth');\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n });\n\n // Get Container Registry Auth Details\n server.tool(\n 'get-container-registry-auth',\n {\n containerRegistryAuthId: z\n .string()\n .describe('ID of the container registry auth to retrieve'),\n },\n async (params) => {\n const result = await runpodRequest(\n `/containerregistryauth/${params.containerRegistryAuthId}`\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Create Container Registry Auth\n server.tool(\n 'create-container-registry-auth',\n {\n name: z.string().describe('Name for the container registry auth'),\n username: z.string().describe('Registry username'),\n password: z.string().describe('Registry password'),\n },\n async (params) => {\n const result = await runpodRequest(\n '/containerregistryauth',\n 'POST',\n params\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n\n // Delete Container Registry Auth\n server.tool(\n 'delete-container-registry-auth',\n {\n containerRegistryAuthId: z\n .string()\n .describe('ID of the container registry auth to delete'),\n },\n async (params) => {\n const result = await runpodRequest(\n `/containerregistryauth/${params.containerRegistryAuthId}`,\n 'DELETE'\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAA8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AAQ;AAAA,IACR,WAAW;AAAA,IACX,iBAAiB,IAAI,QAAQ,YAAY;AAAA,IACzC,eAAe,KAAK;AAAA,EACtB,CAAC;AAED,QAAM,YAAY,IAAI,oDAA8B;AAAA,IAClD,oBAAoB;AAAA;AAAA,EACtB,CAAC;AAID,MAAI,GAAG,SAAS,MAAM;AACpB,cAAU,MAAM,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAChC,WAAO,MAAM,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EAC/B,CAAC;AAED,QAAM,OAAO,QAAQ,SAAS;AAG9B,QAAM,UAAU,cAAc,KAAK,KAAM,IAA2B,IAAI;AAC1E;","names":["fetch"]}
|
package/dist/http.d.cts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
export { ToolContext, registerTools } from './tools.cjs';
|
|
3
|
+
import '@modelcontextprotocol/sdk/server/mcp.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Handle an incoming HTTP request as a streamable MCP session.
|
|
7
|
+
*
|
|
8
|
+
* Each request gets its own McpServer + transport. The caller's Bearer token
|
|
9
|
+
* is forwarded directly to the Runpod API as the credential — it may be a
|
|
10
|
+
* Runpod API key (set manually by the caller) or a token obtained through the
|
|
11
|
+
* OAuth "Sign in with Runpod" flow. The server holds no credential of its own
|
|
12
|
+
* and never shares one across users.
|
|
13
|
+
*/
|
|
14
|
+
declare function handleMcpRequest(req: IncomingMessage, res: ServerResponse, opts?: {
|
|
15
|
+
serverVersion?: string;
|
|
16
|
+
}): Promise<void>;
|
|
17
|
+
|
|
18
|
+
export { handleMcpRequest };
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
export { ToolContext, registerTools } from './tools.js';
|
|
3
|
+
import '@modelcontextprotocol/sdk/server/mcp.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Handle an incoming HTTP request as a streamable MCP session.
|
|
7
|
+
*
|
|
8
|
+
* Each request gets its own McpServer + transport. The caller's Bearer token
|
|
9
|
+
* is forwarded directly to the Runpod API as the credential — it may be a
|
|
10
|
+
* Runpod API key (set manually by the caller) or a token obtained through the
|
|
11
|
+
* OAuth "Sign in with Runpod" flow. The server holds no credential of its own
|
|
12
|
+
* and never shares one across users.
|
|
13
|
+
*/
|
|
14
|
+
declare function handleMcpRequest(req: IncomingMessage, res: ServerResponse, opts?: {
|
|
15
|
+
serverVersion?: string;
|
|
16
|
+
}): Promise<void>;
|
|
17
|
+
|
|
18
|
+
export { handleMcpRequest };
|
package/dist/http.mjs
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import {
|
|
2
|
+
registerTools
|
|
3
|
+
} from "./chunk-CRHHCQRI.mjs";
|
|
4
|
+
|
|
5
|
+
// src/http.ts
|
|
6
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
7
|
+
|
|
8
|
+
// src/server.ts
|
|
9
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
10
|
+
var SERVER_NAME = "Runpod API Server";
|
|
11
|
+
var SERVER_VERSION = true ? "1.3.0" : "dev";
|
|
12
|
+
function createServer(version = SERVER_VERSION) {
|
|
13
|
+
return new McpServer({
|
|
14
|
+
name: SERVER_NAME,
|
|
15
|
+
version,
|
|
16
|
+
capabilities: {
|
|
17
|
+
resources: {},
|
|
18
|
+
tools: {}
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// src/http.ts
|
|
24
|
+
function extractBearerToken(req) {
|
|
25
|
+
const authHeader = req.headers.authorization;
|
|
26
|
+
if (!authHeader) return null;
|
|
27
|
+
const parts = authHeader.split(" ");
|
|
28
|
+
if (parts.length !== 2 || parts[0].toLowerCase() !== "bearer") return null;
|
|
29
|
+
return parts[1];
|
|
30
|
+
}
|
|
31
|
+
function getBaseUrl(req) {
|
|
32
|
+
const proto = req.headers["x-forwarded-proto"]?.split(",")[0] ?? "https";
|
|
33
|
+
const host = req.headers.host;
|
|
34
|
+
if (!host) {
|
|
35
|
+
throw new Error("Missing Host header");
|
|
36
|
+
}
|
|
37
|
+
return `${proto}://${host}`;
|
|
38
|
+
}
|
|
39
|
+
function writeUnauthorized(req, res, error) {
|
|
40
|
+
const headers = {
|
|
41
|
+
"Content-Type": "application/json",
|
|
42
|
+
"WWW-Authenticate": `Bearer realm="mcp", resource_metadata="${getBaseUrl(
|
|
43
|
+
req
|
|
44
|
+
)}/.well-known/oauth-protected-resource"`
|
|
45
|
+
};
|
|
46
|
+
res.writeHead(401, headers);
|
|
47
|
+
res.end(JSON.stringify({ error }));
|
|
48
|
+
}
|
|
49
|
+
async function handleMcpRequest(req, res, opts = {}) {
|
|
50
|
+
const bearerToken = extractBearerToken(req);
|
|
51
|
+
console.log("mcp_request", {
|
|
52
|
+
method: req.method,
|
|
53
|
+
url: req.url,
|
|
54
|
+
hasBearerToken: !!bearerToken
|
|
55
|
+
});
|
|
56
|
+
if (!bearerToken) {
|
|
57
|
+
writeUnauthorized(
|
|
58
|
+
req,
|
|
59
|
+
res,
|
|
60
|
+
"Missing or invalid Authorization header. Provide a Bearer token."
|
|
61
|
+
);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const server = createServer(opts.serverVersion);
|
|
65
|
+
registerTools(server, {
|
|
66
|
+
apiKey: bearerToken,
|
|
67
|
+
transport: "http",
|
|
68
|
+
clientUserAgent: req.headers["user-agent"],
|
|
69
|
+
serverVersion: opts.serverVersion
|
|
70
|
+
});
|
|
71
|
+
const transport = new StreamableHTTPServerTransport({
|
|
72
|
+
sessionIdGenerator: void 0
|
|
73
|
+
// stateless — no session persistence
|
|
74
|
+
});
|
|
75
|
+
res.on("close", () => {
|
|
76
|
+
transport.close().catch(() => {
|
|
77
|
+
});
|
|
78
|
+
server.close().catch(() => {
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
await server.connect(transport);
|
|
82
|
+
await transport.handleRequest(req, res, req.body);
|
|
83
|
+
}
|
|
84
|
+
export {
|
|
85
|
+
handleMcpRequest,
|
|
86
|
+
registerTools
|
|
87
|
+
};
|
|
88
|
+
//# sourceMappingURL=http.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/http.ts","../src/server.ts"],"sourcesContent":["import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport { createServer } from './server.js';\nimport { registerTools } from './tools.js';\nimport { IncomingMessage, ServerResponse } from 'node:http';\n\n/**\n * Extract the bearer token from an HTTP request's Authorization header.\n * Returns null if the header is missing or malformed.\n */\nfunction extractBearerToken(req: IncomingMessage): string | null {\n const authHeader = req.headers.authorization;\n if (!authHeader) return null;\n const parts = authHeader.split(' ');\n if (parts.length !== 2 || parts[0].toLowerCase() !== 'bearer') return null;\n return parts[1];\n}\n\nfunction getBaseUrl(req: IncomingMessage): string {\n const proto =\n (req.headers['x-forwarded-proto'] as string | undefined)?.split(',')[0] ??\n 'https';\n const host = req.headers.host;\n if (!host) {\n throw new Error('Missing Host header');\n }\n\n return `${proto}://${host}`;\n}\n\nfunction writeUnauthorized(\n req: IncomingMessage,\n res: ServerResponse,\n error: string\n): void {\n // Always advertise the protected-resource metadata so OAuth-capable clients\n // (e.g. Claude) know to start the \"Sign in with Runpod\" flow. Callers who\n // bring their own API key as the bearer token simply never hit this path.\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'WWW-Authenticate': `Bearer realm=\"mcp\", resource_metadata=\"${getBaseUrl(\n req\n )}/.well-known/oauth-protected-resource\"`,\n };\n\n res.writeHead(401, headers);\n res.end(JSON.stringify({ error }));\n}\n\n/**\n * Handle an incoming HTTP request as a streamable MCP session.\n *\n * Each request gets its own McpServer + transport. The caller's Bearer token\n * is forwarded directly to the Runpod API as the credential — it may be a\n * Runpod API key (set manually by the caller) or a token obtained through the\n * OAuth \"Sign in with Runpod\" flow. The server holds no credential of its own\n * and never shares one across users.\n */\nexport async function handleMcpRequest(\n req: IncomingMessage,\n res: ServerResponse,\n opts: { serverVersion?: string } = {}\n): Promise<void> {\n const bearerToken = extractBearerToken(req);\n console.log('mcp_request', {\n method: req.method,\n url: req.url,\n hasBearerToken: !!bearerToken,\n });\n if (!bearerToken) {\n writeUnauthorized(\n req,\n res,\n 'Missing or invalid Authorization header. Provide a Bearer token.'\n );\n return;\n }\n\n const server = createServer(opts.serverVersion);\n // In stateless HTTP, a tools/call is a separate request from `initialize`, so\n // the per-request server never sees the MCP `clientInfo`. Fall back to the\n // inbound HTTP User-Agent so caller-tracking still attributes the client.\n registerTools(server, {\n apiKey: bearerToken,\n transport: 'http',\n clientUserAgent: req.headers['user-agent'],\n serverVersion: opts.serverVersion,\n });\n\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — no session persistence\n });\n\n // This per-request server/transport pair is single-use; dispose it when the\n // response closes so listeners don't accumulate on a warm serverless instance.\n res.on('close', () => {\n transport.close().catch(() => {});\n server.close().catch(() => {});\n });\n\n await server.connect(transport);\n // Pass the already-parsed body when the host provides one (e.g. Vercel's\n // VercelRequest exposes `req.body`); the SDK reads the raw stream otherwise.\n await transport.handleRequest(req, res, (req as { body?: unknown }).body);\n}\n\nexport { registerTools } from './tools.js';\nexport type { ToolContext } from './tools.js';\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\n// `__PACKAGE_VERSION__` is replaced at build time by tsup's `define` with the\n// current `version` from package.json. Falls back to `'dev'` when the\n// substitution doesn't happen (e.g. running via tsx).\ndeclare const __PACKAGE_VERSION__: string;\n\nexport const SERVER_NAME = 'Runpod API Server';\nexport const SERVER_VERSION =\n typeof __PACKAGE_VERSION__ !== 'undefined' ? __PACKAGE_VERSION__ : 'dev';\n\n// `version` defaults to the build-time value (correct for the npm/stdio build).\n// The hosted entrypoint passes a runtime value read from package.json, since\n// tsup's define doesn't run when Vercel compiles api/index.ts.\nexport function createServer(version: string = SERVER_VERSION): McpServer {\n return new McpServer({\n name: SERVER_NAME,\n version,\n capabilities: {\n resources: {},\n tools: {},\n },\n });\n}\n"],"mappings":";;;;;AAAA,SAAS,qCAAqC;;;ACA9C,SAAS,iBAAiB;AAOnB,IAAM,cAAc;AACpB,IAAM,iBACX,OAA6C,UAAsB;AAK9D,SAAS,aAAa,UAAkB,gBAA2B;AACxE,SAAO,IAAI,UAAU;AAAA,IACnB,MAAM;AAAA,IACN;AAAA,IACA,cAAc;AAAA,MACZ,WAAW,CAAC;AAAA,MACZ,OAAO,CAAC;AAAA,IACV;AAAA,EACF,CAAC;AACH;;;ADdA,SAAS,mBAAmB,KAAqC;AAC/D,QAAM,aAAa,IAAI,QAAQ;AAC/B,MAAI,CAAC,WAAY,QAAO;AACxB,QAAM,QAAQ,WAAW,MAAM,GAAG;AAClC,MAAI,MAAM,WAAW,KAAK,MAAM,CAAC,EAAE,YAAY,MAAM,SAAU,QAAO;AACtE,SAAO,MAAM,CAAC;AAChB;AAEA,SAAS,WAAW,KAA8B;AAChD,QAAM,QACH,IAAI,QAAQ,mBAAmB,GAA0B,MAAM,GAAG,EAAE,CAAC,KACtE;AACF,QAAM,OAAO,IAAI,QAAQ;AACzB,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,MAAM,qBAAqB;AAAA,EACvC;AAEA,SAAO,GAAG,KAAK,MAAM,IAAI;AAC3B;AAEA,SAAS,kBACP,KACA,KACA,OACM;AAIN,QAAM,UAAkC;AAAA,IACtC,gBAAgB;AAAA,IAChB,oBAAoB,0CAA0C;AAAA,MAC5D;AAAA,IACF,CAAC;AAAA,EACH;AAEA,MAAI,UAAU,KAAK,OAAO;AAC1B,MAAI,IAAI,KAAK,UAAU,EAAE,MAAM,CAAC,CAAC;AACnC;AAWA,eAAsB,iBACpB,KACA,KACA,OAAmC,CAAC,GACrB;AACf,QAAM,cAAc,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