Repository navigation
Prototype: cmux Cloud as a remote MCP server #16568
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
4442399
df9a7f0
838c9ab
ce2edaf
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| // cmux Cloud remote MCP server (prototype), streamable HTTP transport in its | ||
| // stateless JSON form: each POST carries one JSON-RPC message (or a batch) and | ||
| // gets a JSON reply. There is no server-to-client stream, so GET answers 405. | ||
| // | ||
| // Auth is the same as `/api/vm`: the Stack bearer pair the cmux app sends, or a | ||
| // same-origin session cookie. OAuth for ChatGPT and Claude connectors is not | ||
| // wired yet; see #16567 for the plan. | ||
|
|
||
| import { recordSpanError, setSpanAttributes } from "../../../services/telemetry"; | ||
| import { handleCloudMcpBody } from "../../../services/mcp/cloudMcp"; | ||
| import { cloudMcpGatewayFor, toolErrorFromResponse } from "../../../services/mcp/cloudMcpGateway"; | ||
| import type { AuthedUser } from "../../../services/vms/auth"; | ||
| import { isVmBillingTeamResolutionError, resolveVmEntitlements } from "../../../services/vms/entitlements"; | ||
| import { vmModelPlaneRevoker } from "../../../services/vms/modelPlaneGateway"; | ||
| import { | ||
| jsonResponse, | ||
| requestedVmTeamIdFromRequest, | ||
| resolveVmRouteAccountScope, | ||
| vmBillingTeamErrorResponse, | ||
| withAuthedVmApiRoute, | ||
| } from "../../../services/vms/routeHelpers"; | ||
| import { annotateVmRequestBilling } from "../../../services/vms/requestContext"; | ||
| import { runVmRoute } from "../../../services/vms/routeWorkflow"; | ||
|
|
||
| // run_agent makes up to three guest calls of at most 30s each; leave room for auth and resume. | ||
| export const maxDuration = 120; | ||
|
|
||
| const MCP_ROUTE = "/api/mcp"; | ||
| // Tool arguments are capped at 16 KiB each; anything far beyond that is not a tool call. | ||
| const MAX_BODY_BYTES = 256 * 1024; | ||
|
|
||
| function withBearerChallenge(response: Response): Response { | ||
| if (response.status !== 401) return response; | ||
| const headers = new Headers(response.headers); | ||
| headers.set("www-authenticate", 'Bearer realm="cmux"'); | ||
| return new Response(response.body, { status: 401, headers }); | ||
| } | ||
|
|
||
| function rpcFailure(code: number, message: string, status: number): Response { | ||
| return jsonResponse({ jsonrpc: "2.0", id: null, error: { code, message } }, status); | ||
| } | ||
|
|
||
| /** The list scope `GET /api/vm` uses: entitlements only for a requested team or a team account. */ | ||
| async function listScopeFor(user: AuthedUser, request: Request): Promise<string | null> { | ||
| const requestedBillingTeamId = requestedVmTeamIdFromRequest(request); | ||
| if (!requestedBillingTeamId && user.billingCustomerType !== "team") return null; | ||
| try { | ||
| const entitlements = resolveVmEntitlements(user, process.env, { requestedBillingTeamId }); | ||
| annotateVmRequestBilling(entitlements); | ||
| return entitlements.billingTeamId; | ||
| } catch (err) { | ||
| if (isVmBillingTeamResolutionError(err)) throw await toolErrorFromResponse(vmBillingTeamErrorResponse(err)); | ||
| throw err; | ||
| } | ||
| } | ||
|
|
||
| export async function POST(request: Request): Promise<Response> { | ||
| const response = await withAuthedVmApiRoute( | ||
| request, | ||
| MCP_ROUTE, | ||
| { "cmux.vm.operation": "mcp" }, | ||
| `${MCP_ROUTE} POST failed`, | ||
| async ({ user, span }) => { | ||
| const declaredLength = Number(request.headers.get("content-length") ?? 0); | ||
| if (declaredLength > MAX_BODY_BYTES) return rpcFailure(-32600, "Request too large", 413); | ||
| const raw = await request.text(); | ||
| if (Buffer.byteLength(raw, "utf8") > MAX_BODY_BYTES) return rpcFailure(-32600, "Request too large", 413); | ||
| let body: unknown; | ||
| try { | ||
| body = JSON.parse(raw); | ||
| } catch { | ||
| return rpcFailure(-32700, "Parse error", 400); | ||
| } | ||
| const gateway = cloudMcpGatewayFor( | ||
| { | ||
| userId: user.id, | ||
| teamIds: user.teamIds, | ||
| listScope: () => listScopeFor(user, request), | ||
| accessScope: async () => { | ||
| const account = resolveVmRouteAccountScope(user, request); | ||
| if (!account.ok) throw await toolErrorFromResponse(account.response); | ||
| return { | ||
| billingTeamId: account.entitlements.billingTeamId, | ||
| maxActiveVms: account.entitlements.maxActiveVms, | ||
| planId: account.entitlements.planId, | ||
| }; | ||
| }, | ||
| }, | ||
| (program) => runVmRoute(program, { request }), | ||
| vmModelPlaneRevoker(), | ||
| ); | ||
| const method = body && typeof body === "object" && "method" in body ? String(body.method) : Array.isArray(body) ? "batch" : ""; | ||
| setSpanAttributes(span, { "cmux.mcp.method": method.slice(0, 64) }); | ||
| const reply = await handleCloudMcpBody(gateway, body, (error) => { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: The route now accepts batches, but Prompt for AI agents |
||
| recordSpanError(span, error); | ||
| console.error(`${MCP_ROUTE} tool call failed`, error); | ||
| }); | ||
| if (!reply) return new Response(null, { status: 202 }); | ||
| return jsonResponse(reply); | ||
| }, | ||
| ); | ||
| return withBearerChallenge(response); | ||
| } | ||
|
|
||
| export function GET(): Response { | ||
| return new Response(null, { status: 405, headers: { allow: "POST" } }); | ||
| } | ||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,56 @@ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // Local demo of the cmux Cloud MCP tools against a cmux-tui session on this | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // computer, for MCP Inspector or any MCP client. No auth and no Cloud: one fake | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // machine, `local`, whose guest commands run `cmux-tui` here. Binds 127.0.0.1. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // cmux-tui server ensure --session cloud | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // bun scripts/cloud-mcp-local.ts # prints the URL | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // npx @modelcontextprotocol/inspector --cli http://127.0.0.1:8765/mcp --transport http --method tools/list | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import { spawnSync } from "node:child_process"; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import { CloudMcpToolError, handleCloudMcpBody, type CloudMcpGateway } from "../services/mcp/cloudMcp"; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // The web package's tsconfig does not load Bun's ambient types; this script is | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // Bun-only, so type the one global it needs here. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| declare const Bun: { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| serve(options: { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| hostname: string; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| port: number; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| fetch(request: Request): Response | Promise<Response>; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }): unknown; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const port = Number(process.env.CMUX_MCP_DEMO_PORT ?? 8765); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const cmuxTui = process.env.CMUX_TUI_BIN ?? "cmux-tui"; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const MACHINE_ID = "local"; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const gateway: CloudMcpGateway = { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| listMachines: async () => [{ id: MACHINE_ID, name: "this computer", status: "running" }], | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| runCmuxTui: async (machineId, args, timeoutMs) => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (machineId !== MACHINE_ID) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| throw new CloudMcpToolError("vm_not_found", `Cloud VM ${machineId} was not found.`); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // `args` is quoted for a POSIX shell, exactly as it reaches the machine's shell. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const result = spawnSync("sh", ["-c", `exec "$0" ${args}`, cmuxTui], { encoding: "utf8", timeout: timeoutMs }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: Prompt for AI agentsThere was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: Prompt for AI agents
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| return { exitCode: result.status ?? 124, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Bun.serve({ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| hostname: "127.0.0.1", | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| port, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| async fetch(request) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const url = new URL(request.url); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (url.pathname !== "/mcp") return new Response("not found", { status: 404 }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (request.method !== "POST") return new Response(null, { status: 405, headers: { allow: "POST" } }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| let message: unknown; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| try { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| message = await request.json(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } catch { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| return Response.json({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }, { status: 400 }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const reply = await handleCloudMcpBody(gateway, message, (error) => console.error(error)); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| return reply ? Response.json(reply) : new Response(null, { status: 202 }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+38
to
+54
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win 🔎 Supported by static analysis🏁 Script executed: sed -n '1,100p' web/scripts/cloud-mcp-local.ts
sed -n '355,478p' web/services/mcp/cloudMcp.ts
rg -n 'bun-version|packageManager|Origin|origin' web/package.json .github/workflows web/scripts/cloud-mcp-local.tsRepository: manaflow-ai/cmux Length of output: 19204 🏁 Script executed: #!/bin/bash
set -eu
printf '%s\n' '--- changed file diff/stat ---'
git diff --stat 8b8762a5870f3018c66c19f308dfc4e9c873cd8f ce2edafd55173735b3e87b0c88b9a44ffb5e4d2e -- web/scripts/cloud-mcp-local.ts web/services/mcp/cloudMcp.ts
git diff --unified=20 8b8762a5870f3018c66c19f308dfc4e9c873cd8f ce2edafd55173735b3e87b0c88b9a44ffb5e4d2e -- web/scripts/cloud-mcp-local.ts
printf '%s\n' '--- cloud MCP tool definitions and dispatch ---'
rg -n -A35 -B10 'CLOUD_MCP_TOOLS|run_agent|send_input|function runAgent|async function runAgent|export async function callCloudMcpTool' web/services/mcp/cloudMcp.ts
printf '%s\n' '--- local script with line numbers ---'
nl -ba web/scripts/cloud-mcp-local.ts | sed -n '35,70p'
printf '%s\n' '--- repository MCP Origin/Host handling ---'
rg -n -S -i 'origin|host.*header|header.*host|dns rebinding|localhost|127\.0\.0\.1' web/scripts web/services/mcp web/package.json README.md .github 2>/dev/null | head -240Repository: manaflow-ai/cmux Length of output: 41970 🌐 Web query:
💡 Result: 🌐 Web query:
💡 Result: Reject untrusted origins before parsing MCP requests. The loopback bind does not validate Suggested fix if (url.pathname !== "/mcp") return new Response("not found", { status: 404 });
if (request.method !== "POST") return new Response(null, { status: 405, headers: { allow: "POST" } });
+ if (request.headers.get("origin") !== null) {
+ return new Response("forbidden", { status: 403 });
+ }
let message: unknown;📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| console.log(`cmux Cloud MCP demo at http://127.0.0.1:${port}/mcp (machine id: ${MACHINE_ID})`); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Count body bytes while the request streams in.
The
content-lengthcheck passes when the header is missing, for example on a chunked request. In that caserequest.text()buffers the whole body before line 67 measures it. One authenticated caller can make the function hold a body of any size in memory. Readrequest.bodywith a reader, keep a running byte count, and cancel the read when the count exceedsMAX_BODY_BYTES. Based on learnings: "check that the limit is instead enforced by the streaming body parser … counting actual bytes read."Proposed fix
🤖 Prompt for AI Agents
Source: Learnings