// Idle's MCP server: the Model Context Protocol over Streamable HTTP, stateless, answering in JSON (no SSE). // Specification followed: https://modelcontextprotocol.io/specification/2026-07-28 (the current revision). // // That revision removed the `initialize` handshake: every request carries its protocol version and the client's // capabilities in `_meta`, mirrored in HTTP headers, and `server/discover` says what the server speaks. Clients // written for the earlier revisions still open with `initialize`. This server is "dual-era", as the revision // allows (basic/versioning, "Backward Compatibility"): it serves both, on the same endpoint. // // modern (2026-07-28) server/discover, tools/list, tools/call. Each request must carry // _meta["io.modelcontextprotocol/protocolVersion"] and ["…/clientCapabilities"], and the // headers MCP-Protocol-Version, Mcp-Method and (for tools/call) Mcp-Name, equal to the body. // legacy (2025-11-25, 2025-06-18, 2025-03-26) // initialize, notifications/initialized, ping, tools/list, tools/call. No session id is // minted: nothing is remembered between two requests in either era. // // It holds no logic of its own. Each tool is one call to the REST API of app.mjs, so a tool and its route cannot // disagree, and a tool that needs an account takes the same bearer token as the route does. export const MCP_MODERN = "2026-07-28"; export const MCP_LEGACY = ["2025-11-25", "2025-06-18", "2025-03-26"]; export const MCP_VERSIONS = [MCP_MODERN, ...MCP_LEGACY]; export const MCP_SPEC = "https://modelcontextprotocol.io/specification/2026-07-28"; const V = "io.modelcontextprotocol/protocolVersion"; const CAPS = "io.modelcontextprotocol/clientCapabilities"; const SERVER = "io.modelcontextprotocol/serverInfo"; // JSON-RPC and MCP error codes (basic/index, "Error Codes"). const PARSE = -32700, INVALID_REQUEST = -32600, METHOD_NOT_FOUND = -32601, INVALID_PARAMS = -32602, INTERNAL = -32603; const HEADER_MISMATCH = -32020, UNSUPPORTED_VERSION = -32022; const GPU_IDS = ["rtx-4090", "rtx-5090", "l40s", "a100", "h100", "h200", "b200"]; const none = { type: "object", additionalProperties: false }; const read = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }; /** * The tools. `call(args)` is the REST request a tool makes; `account: true` marks the ones that act on an * account (an API key, and an open engine). The order is fixed: clients cache the list. */ export const TOOLS = [ { name: "list_gpus", title: "List Idle's GPUs and rates", description: "The seven Nvidia GPUs Idle lists, each with its rate in USD per hour and per second, its HYPE price and whether one is available. While rentals are closed these are target rates and nothing is available; the answer says which (`source`: target or provider).", inputSchema: none, annotations: read, call: () => ({ method: "GET", path: "/v1/gpus" }), }, { name: "find_gpu", title: "Find a GPU on the market (idle/auto)", description: "Picks one whole Nvidia GPU from live market offers (Runpod list prices and Vast.ai live offers) by a stated rule: cheapest, fastest (highest tier, then cheapest) or secure (datacenter or secure cloud only). Returns the pick, up to three alternatives, the price with Idle's margin, and whether Idle can rent it for you right now. These are market offers from the named sources, not Idle's machines.", inputSchema: { type: "object", additionalProperties: false, properties: { minVram: { type: "number", minimum: 0, description: "Least GPU memory in GB. Default 0." }, prefer: { type: "string", enum: ["cheapest", "fastest", "secure"], description: "The rule. Default cheapest." }, gpu: { type: "string", enum: GPU_IDS, description: "Only this model (one of Idle's ids)." }, }, }, annotations: read, call: (a) => ({ method: "GET", path: "/v1/route", query: pickDefined({ minVram: a.minVram, prefer: a.prefer, gpu: a.gpu }) }), }, { name: "quote_rental", title: "Quote a rental", description: "What a number of seconds on one of Idle's GPUs costs, in USD and in HYPE, billed per second and rounded up to the micro-dollar. While rentals are closed it is a target price and says so.", inputSchema: { type: "object", additionalProperties: false, required: ["gpu", "seconds"], properties: { gpu: { type: "string", enum: GPU_IDS, description: "One of Idle's GPU ids." }, seconds: { type: "integer", minimum: 1, maximum: 2_592_000, description: "Whole seconds, up to 30 days." } }, }, annotations: read, call: (a) => ({ method: "GET", path: "/v1/quote", query: { gpu: a.gpu, seconds: a.seconds } }), }, { name: "market", title: "Live market figures", description: "The live figures Idle prices with, each read from a public source: the HYPE mid and Nvidia's price on Hyperliquid, the head of the Elysium chain, USDC on Elysium, and the tokenized Nvidia share EQNVDA with its Uniswap v4 pool price. A source that is down gives null and is named in `errors`.", inputSchema: none, annotations: read, call: () => ({ method: "GET", path: "/v1/market" }), }, { name: "quote_nvda_credits", title: "Quote credits for tokenized Nvidia", description: "How many USD of Idle credits an amount of EQNVDA (EQX's tokenized Nvidia share on Elysium) would buy: the lower of the Uniswap v4 pool price and Hyperliquid's xyz:NVDA mark, less a haircut, rounded down. It is a price, not an offer: a claim is priced again when it is made.", inputSchema: { type: "object", additionalProperties: false, required: ["amount"], properties: { amount: { type: "string", pattern: "^\\d+(\\.\\d+)?$", description: 'A positive decimal amount of EQNVDA, as a string, for example "1.5". At most 8 decimals.' } }, }, annotations: read, call: (a) => ({ method: "GET", path: "/v1/credits/quote", query: { token: "EQNVDA", amount: a.amount } }), }, { name: "rental_status", title: "Is renting open?", description: "Whether Idle can rent a machine right now, and if not, exactly what is missing. Also the tokens that buy credits, the limits per account, and whether the meter is running. Call this before rent_gpu.", inputSchema: none, annotations: read, call: () => ({ method: "GET", path: "/v1/health" }), }, { name: "credits_contract", title: "The credits contract on Elysium", description: "IdleCredits, the contract that holds prepaid credits on the Elysium chain, read from the chain now. Without an argument: its address, its operator, the withdrawal delay, and what it holds in USDC and EQNVDA. With an address: what that address holds in the contract and in its wallet, and any withdrawal it has requested. The contract is not audited, and the rental engine does not read or charge these balances yet.", inputSchema: { type: "object", additionalProperties: false, properties: { address: { type: "string", pattern: "^0x[0-9a-fA-F]{40}$", description: "A wallet address, to read what it holds in the contract." } }, }, annotations: read, call: (a) => (a.address ? { method: "GET", path: "/v1/contract/account", query: { address: a.address } } : { method: "GET", path: "/v1/contract" }), }, { name: "get_balance", title: "Account balance", description: "The credits of the account the API key belongs to (1 credit is 1 USD), with the key's daily cap and what it has spent today. Needs an API key.", account: true, inputSchema: none, annotations: { ...read, openWorldHint: false }, call: () => ({ method: "GET", path: "/v1/me" }), shape: (b) => ({ address: b.address, creditsUsd: b.creditsUsd, creditsMicro: b.creditsMicro, via: b.via, apiKey: b.apiKeys.find((k) => k.id === b.apiKeyId) ?? null, sshKeys: b.sshKeys.length, liveInstances: b.instances.filter((i) => i.status === "starting" || i.status === "running").length, limits: b.limits }), }, { name: "list_instances", title: "List instances", description: "The account's instances, newest first: status (starting, running, ended, failed), the SSH command once running, seconds billed and cost so far. Needs an API key.", account: true, inputSchema: none, annotations: { ...read, openWorldHint: false }, call: () => ({ method: "GET", path: "/v1/instances" }), }, { name: "rent_gpu", title: "Rent a GPU", description: "Rents one whole GPU for the account and spends its credits: billing is per second from the moment the machine answers on SSH, until end_instance is called or the credits run out. The account must hold credits for 10 minutes and at least one SSH key (keys are added in the dashboard, not here). Returns the instance; poll list_instances for its SSH command. Needs an API key, and rentals must be open.", account: true, inputSchema: { type: "object", additionalProperties: false, required: ["gpu"], properties: { gpu: { type: "string", enum: GPU_IDS, description: "One of Idle's GPU ids." }, sshKeyIds: { type: "array", items: { type: "string" }, minItems: 1, description: "The account's SSH key ids to put on the machine. Default: all of them." } }, }, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true }, call: (a) => ({ method: "POST", path: "/v1/instances", body: pickDefined({ gpu: a.gpu, sshKeyIds: a.sshKeyIds }) }), }, { name: "end_instance", title: "End an instance", description: "Ends an instance: the machine is terminated, its disk is wiped, billing stops and a receipt is returned (seconds billed, USD, start and end). Ending an instance that is already ended returns the same receipt. Needs an API key.", account: true, inputSchema: { type: "object", additionalProperties: false, required: ["id"], properties: { id: { type: "string", pattern: "^[a-z0-9]{1,16}$", description: "The instance id, as list_instances gives it." } } }, annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true }, call: (a) => ({ method: "POST", path: `/v1/instances/${a.id}/end` }), }, ]; function pickDefined(o) { return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined && v !== null)); } /** What is wrong with `args` for a tool's input schema: a list of sentences, empty when nothing is. */ export function checkArguments(schema, args) { const problems = []; if (args === null || typeof args !== "object" || Array.isArray(args)) return ["arguments must be an object"]; for (const name of schema.required ?? []) if (args[name] === undefined) problems.push(`${name} is required`); for (const [name, value] of Object.entries(args)) { const s = schema.properties?.[name]; if (!s) { if (schema.additionalProperties === false) problems.push(`${name} is not a parameter of this tool`); continue; } const ok = s.type === "string" ? typeof value === "string" : s.type === "integer" ? Number.isInteger(value) : s.type === "number" ? typeof value === "number" && Number.isFinite(value) : s.type === "array" ? Array.isArray(value) && value.every((x) => typeof x === s.items?.type) : true; if (!ok) problems.push(`${name} must be ${s.type === "array" ? "a list of " + s.items.type + "s" : (s.type === "integer" ? "an " : "a ") + s.type}`); else if (s.enum && !s.enum.includes(value)) problems.push(`${name} must be one of ${s.enum.join(", ")}`); else if (s.pattern && !new RegExp(s.pattern).test(value)) problems.push(`${name} is not in the expected form`); else if ((s.minimum !== undefined && value < s.minimum) || (s.maximum !== undefined && value > s.maximum)) problems.push(`${name} is out of range`); else if (s.minItems !== undefined && value.length < s.minItems) problems.push(`${name} must not be empty`); } return problems; } /** A header value that may be Base64-wrapped (=?base64?…?=), decoded. */ function headerValue(v) { if (typeof v !== "string") return null; const m = v.match(/^=\?base64\?(.*)\?=$/); return m ? Buffer.from(m[1], "base64").toString("utf8") : v; } /** * @param {{rest:(req:object)=>Promise<{status:number, body:any}>, info:{name:string, title?:string, version:string}, * instructions?:string, allowOrigin?:(origin:string)=>boolean, status:()=>{open:boolean, missing:string[]}, * log?:(e:object)=>void}} o * rest one call to the REST API: {method, path, query, body, auth} -> {status, body} * status whether the engine is open, and what is missing when it is not */ export function createMcp(o) { const info = o.info; const allowOrigin = o.allowOrigin ?? (() => true); const tools = TOOLS.map(({ name, title, description, inputSchema, annotations }) => ({ name, title, description, inputSchema, annotations })); const capabilities = { tools: { listChanged: false } }; const instructions = o.instructions ?? "Idle rents whole Nvidia GPUs by the second on Elysium. Start with rental_status: it says whether renting is open and what is missing. find_gpu, list_gpus, quote_rental, market, quote_nvda_credits and credits_contract always work and need no account. get_balance, list_instances, rent_gpu and end_instance act on an account and need an API key sent as Authorization: Bearer idk_…; rent_gpu spends real credits. Offers returned by find_gpu are market offers from named sources, not Idle's machines."; const reply = (status, body, headers = {}) => ({ status, headers, body }); const failure = (id, code, message, data) => ({ jsonrpc: "2.0", ...(id === undefined || id === null ? {} : { id }), error: { code, message, ...(data === undefined ? {} : { data }) } }); const success = (id, result) => ({ jsonrpc: "2.0", id, result }); /** Runs one tool. Always a tool result: what goes wrong inside a tool is for the model to read and act on. */ async function callTool(tool, args, auth) { const done = (structuredContent, isError) => ({ content: [{ type: "text", text: isError ? `${structuredContent.error}: ${structuredContent.message}` : JSON.stringify(structuredContent) }], structuredContent, isError }); const problems = checkArguments(tool.inputSchema, args); if (problems.length) return done({ error: "invalid", message: "Bad arguments: " + problems.join("; ") + "." }, true); if (tool.account) { const s = o.status(); if (!s.open) return done({ error: "not-open", message: `Rentals are not open on this deployment, so ${tool.name} cannot act yet. Missing: ${s.missing.join(", ")}. Tools that need no account still work.`, missing: s.missing }, true); if (!auth) return done({ error: "unauthorized", message: `${tool.name} acts on an account. Connect to this server with the header "Authorization: Bearer idk_…" (an API key, made in the Idle dashboard).` }, true); } const r = await o.rest({ ...tool.call(args), auth: tool.account ? auth : undefined }); if (r.status >= 200 && r.status < 300) return done(tool.shape ? tool.shape(r.body) : r.body, false); const { error = "error", message = "The request failed.", ...rest } = r.body ?? {}; return done({ error, message, ...rest }, true); } async function toolsCall(id, params, auth, modern) { const bad = (message) => reply(modern ? 400 : 200, failure(id, INVALID_PARAMS, message)); if (!params || typeof params.name !== "string") return bad("tools/call needs params.name"); const tool = TOOLS.find((t) => t.name === params.name); if (!tool) return bad("Unknown tool: " + params.name); const result = await callTool(tool, params.arguments ?? {}, auth); return reply(200, success(id, modern ? { resultType: "complete", ...result, _meta: { [SERVER]: info } } : result)); } /** * One HTTP request to the MCP endpoint. * @param {{httpMethod:string, headers?:object, body?:any, auth?:string, origin?:string}} req header names in lower case * @returns {Promise<{status:number, headers:object, body:object|null}>} */ async function handle({ httpMethod, headers = {}, body, auth, origin }) { // Streamable HTTP of this revision is POST only: no GET stream, no session to DELETE. if (httpMethod !== "POST") return reply(405, failure(null, INVALID_REQUEST, "The MCP endpoint takes POST only."), { Allow: "POST" }); if (origin && !allowOrigin(origin)) return reply(403, failure(null, INVALID_REQUEST, "This origin may not call the MCP endpoint.")); let msg = body; if (typeof body === "string") { try { msg = JSON.parse(body); } catch { return reply(400, failure(null, PARSE, "Parse error: the body is not JSON.")); } } if (Array.isArray(msg)) return reply(400, failure(null, INVALID_REQUEST, "One JSON-RPC message per request: batches are not taken.")); if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0") return reply(400, failure(null, INVALID_REQUEST, 'Not a JSON-RPC 2.0 message: "jsonrpc" must be "2.0".')); if (typeof msg.method !== "string") return reply(400, failure(msg.id, INVALID_REQUEST, "A request needs a method. This server sends no requests, so it takes no responses.")); // A notification: nothing is remembered, so there is nothing to do but accept it. if (!("id" in msg)) return reply(202, null); if ((typeof msg.id !== "string" && typeof msg.id !== "number") || (typeof msg.id === "number" && !Number.isInteger(msg.id))) return reply(400, failure(null, INVALID_REQUEST, "The id must be a string or an integer.")); const { id, method } = msg; const params = msg.params ?? {}; if (typeof params !== "object" || Array.isArray(params)) return reply(400, failure(id, INVALID_PARAMS, "params must be an object.")); const bodyVersion = params._meta?.[V]; const headerVersion = headers["mcp-protocol-version"]; const unsupported = (requested) => reply(400, failure(id, UNSUPPORTED_VERSION, "Unsupported protocol version", { supported: MCP_VERSIONS, requested })); // ---- Legacy: the handshake, and what follows it ---- if (method === "initialize") { if (typeof params.protocolVersion !== "string") return reply(200, failure(id, INVALID_PARAMS, "initialize needs params.protocolVersion")); // The same version when it is one this server serves with a handshake, otherwise the latest of those. const protocolVersion = MCP_LEGACY.includes(params.protocolVersion) ? params.protocolVersion : MCP_LEGACY[0]; return reply(200, success(id, { protocolVersion, capabilities, serverInfo: info, instructions })); } if (bodyVersion === undefined && (headerVersion === undefined || MCP_LEGACY.includes(headerVersion))) { // No header at all is how the 2025-03-26 revision spoke. if (method === "ping") return reply(200, success(id, {})); if (method === "tools/list") return reply(200, success(id, { tools })); if (method === "tools/call") return toolsCall(id, params, auth, false); return reply(200, failure(id, METHOD_NOT_FOUND, "Method not found: " + method)); } // ---- Modern: everything is in the request ---- if (bodyVersion === undefined) { if (headerVersion !== MCP_MODERN) return unsupported(headerVersion); return reply(400, failure(id, INVALID_PARAMS, `Malformed request: params._meta["${V}"] is required.`)); } if (typeof bodyVersion !== "string") return reply(400, failure(id, INVALID_PARAMS, `params._meta["${V}"] must be a string.`)); if (headerVersion === undefined) return reply(400, failure(id, HEADER_MISMATCH, "Header mismatch: the MCP-Protocol-Version header is missing")); if (headerVersion !== bodyVersion) return reply(400, failure(id, HEADER_MISMATCH, `Header mismatch: MCP-Protocol-Version header value '${headerVersion}' does not match body value '${bodyVersion}'`)); if (bodyVersion !== MCP_MODERN) return unsupported(bodyVersion); const headerMethod = headers["mcp-method"]; if (headerMethod === undefined) return reply(400, failure(id, HEADER_MISMATCH, "Header mismatch: the Mcp-Method header is missing")); if (headerMethod !== method) return reply(400, failure(id, HEADER_MISMATCH, `Header mismatch: Mcp-Method header value '${headerMethod}' does not match body value '${method}'`)); const caps = params._meta[CAPS]; if (!caps || typeof caps !== "object" || Array.isArray(caps)) return reply(400, failure(id, INVALID_PARAMS, `Malformed request: params._meta["${CAPS}"] is required.`)); const meta = { [SERVER]: info }; if (method === "server/discover") return reply(200, success(id, { resultType: "complete", supportedVersions: MCP_VERSIONS, capabilities, instructions, ttlMs: 3_600_000, cacheScope: "public", _meta: meta })); if (method === "tools/list") { if (params.cursor !== undefined) return reply(400, failure(id, INVALID_PARAMS, "Invalid cursor: the list has one page.")); // The same list for everyone: an API key changes what a tool answers, not which tools exist. return reply(200, success(id, { resultType: "complete", tools, ttlMs: 300_000, cacheScope: "public", _meta: meta })); } if (method === "tools/call") { const name = headerValue(headers["mcp-name"]); if (name === null) return reply(400, failure(id, HEADER_MISMATCH, "Header mismatch: the Mcp-Name header is missing")); if (name !== params.name) return reply(400, failure(id, HEADER_MISMATCH, `Header mismatch: Mcp-Name header value '${name}' does not match body value '${params.name}'`)); return toolsCall(id, params, auth, true); } // `initialize` and `ping` are not part of this revision; neither is anything else. return reply(404, failure(id, METHOD_NOT_FOUND, "Method not found: " + method)); } return { async handle(req) { try { return await handle(req); } catch (e) { o.log?.({ event: "error", path: "/mcp", error: String(e?.stack ?? e) }); return reply(500, failure(null, INTERNAL, "Internal error."), {}); } }, tools: TOOLS.map((t) => t.name), accountTools: TOOLS.filter((t) => t.account).map((t) => t.name), }; }