cloud / internal-packages / installer / worker / mcp-relay.jsmain at aacbc74
// mcp-relay.js — ONE MCP SERVER FOR EVERY DEPLOYMENT: the address that iterate's one app in an
// app directory (ChatGPT, Claude) names, where each deployment has its own MCP server and its own
// identity provider. A directory app has one fixed address, so the Cloud stands at it:
//
// the app ──OAuth──▶ the Cloud (this file) ──OAuth──▶ the deployment's identity provider
// the app ──/mcp───▶ the Cloud (this file) ──/mcp───▶ https://iterate.<domain>/mcp
//
// The Cloud is an authorization server for the app and an ordinary OAuth client of the deployment
// (a client metadata document, /oauth2/client.json). At sign-in the person names their deployment,
// then signs in and consents there, on their own deployment. The Cloud has no users of its own and
// decides nothing about who may come in.
//
// What the Cloud keeps: a grant per connection, with the deployment's tokens in it encrypted under
// a key that only the app's own token unwraps (@cloudflare/workers-oauth-provider's `props`). The
// Cloud cannot read them at rest: it holds no standing access. The grant's own fields are plain:
// the deployment's domain, the app's client id, the scope and the times. A grant lasts until
// GRANT_IDLE_LIFE after the app's last refresh, or until the deployment refuses a refresh, which
// removes it. What the Cloud sees: every request and answer while it passes, and the deployment's
// tokens in memory for that time. So whoever can change or deploy this Worker can keep them, and
// then act in every deployment whose connection is used afterwards.
//
// The app's token never reaches the deployment, and the deployment's never reaches the app: the
// MCP specification forbids passing a token through, and allows a server to be a client upstream.
//
// Bindings: RELAY (KV; the library's rows live in it, apart from the installer's own rows, because
// anybody may register an app here; /kept lists both namespaces),
// OPENAI_APPS_CHALLENGE (optional var: ChatGPT's proof that the hostname is ours).
import {
AuthorizationError,
authorizationErrorRedirect,
getOAuthApi,
OAuthError,
OAuthProvider,
} from "@cloudflare/workers-oauth-provider";
const AUTHORIZE = "/oauth2/auth";
const CALLBACK = "/oauth2/callback";
const CLIENT = "/oauth2/client.json";
const CHALLENGE = "/.well-known/openai-apps-challenge";
const SCOPE = "iterate";
// A connection the app stops using ends by itself: 30 days after its last refresh.
const GRANT_IDLE_LIFE = 30 * 24 * 3600;
// Anyone may register an app, so a registration is small and counted, as a deployment's own
// identity provider does it (core/auth-worker/src/oauth.ts): 4096 characters of metadata, and
// in ten minutes 20 from one address and 120 in all. The count is kept in KV, which is not
// exact under a burst: it is a brake, not a gate.
const CLIENT_METADATA_MAX_CHARACTERS = 4096;
const REGISTRATION_WINDOW_SECONDS = 600;
const REGISTRATIONS = { perAddress: 20, inAll: 120 };
const DOMAIN = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/;
// What passes between the app and the deployment, each way. Nothing else does: no cookie, no
// forwarded address, and never the app's own authorization.
const REQUEST_HEADERS = [
"accept",
"content-type",
"last-event-id",
"mcp-protocol-version",
"mcp-session-id",
];
const ANSWER_HEADERS = ["cache-control", "content-type", "mcp-session-id"];
/** Whether a request is the relay's: the MCP server, its OAuth endpoints and its metadata. */
export const handles = ({ pathname }) =>
pathname === "/mcp" ||
pathname.startsWith("/mcp/") ||
pathname.startsWith("/oauth2/") ||
pathname.startsWith("/.well-known/oauth-") ||
pathname === CHALLENGE;
const providers = new Map(); // one per origin: dev answers on workers.dev, production on its route
function providerOf(origin) {
if (!providers.has(origin)) {
const options = {
apiRoute: `${origin}/mcp`,
apiHandler: { fetch: relay },
defaultHandler: { fetch: pages },
authorizeEndpoint: `${origin}${AUTHORIZE}`,
tokenEndpoint: `${origin}/oauth2/token`,
clientRegistrationEndpoint: `${origin}/oauth2/register`,
// The library writes a client again at a token exchange past half of this, so twice a
// connection's idle life keeps every client that still has one.
clientRegistrationTTL: 2 * GRANT_IDLE_LIFE,
// the library hands this callback no bindings: `storage` is this isolate's KV (below)
clientRegistrationCallback: (registration) => registrationRefusal(registration, storage),
clientIdMetadataDocumentEnabled: true,
resourceMetadata: { resource: `${origin}/mcp`, resource_name: "iterate" },
scopesSupported: [SCOPE],
requiredScopes: [SCOPE],
refreshTokenTTL: GRANT_IDLE_LIFE,
refreshTokenIdleTTL: GRANT_IDLE_LIFE,
tokenExchangeCallback: (exchange) => exchanged(origin, options, exchange),
onError: ({ code, status, internal }) =>
console.warn({
event: "mcp-relay.oauth-refusal",
code,
status,
category: internal.category,
reason: internal.reason,
}),
};
providers.set(origin, new OAuthProvider(options));
}
return providers.get(origin);
}
/** The KV namespace of the Worker this isolate serves, for the one callback that gets no env. */
let storage;
export default {
fetch: (request, env, ctx) => {
storage = env.RELAY;
return providerOf(new URL(request.url).origin).fetch(
request,
{ ...env, OAUTH_KV: env.RELAY },
ctx,
);
},
};
// ── the relay ───────────────────────────────────────────────────────────────────────────────────
/** One MCP request of the app, sent on to the deployment the connection is for, with the
* deployment's own token. The body and the answer pass as streams and are not read. */
async function relay(request, _env, ctx) {
const { resource, accessToken } = ctx.props;
const url = new URL(request.url);
const headers = new Headers({ authorization: `Bearer ${accessToken}` });
for (const name of REQUEST_HEADERS)
if (request.headers.has(name)) headers.set(name, request.headers.get(name));
const answer = await fetch(`${resource}${url.pathname.slice("/mcp".length)}${url.search}`, {
method: request.method,
headers,
body: request.body,
redirect: "manual",
});
// The deployment ended the grant (a member revoked it). The app's token lives no longer than
// the deployment's, so this is the only way here. The app asks for a new token, the refresh is
// refused upstream, and `exchanged` removes this connection.
if (answer.status === 401)
return new Response("The deployment refused the connection's token\n", {
status: 401,
headers: {
"www-authenticate": `Bearer error="invalid_token", resource_metadata="${url.origin}/.well-known/oauth-protected-resource/mcp"`,
},
});
// The answer is the deployment's, served at the Cloud's origin: a browser must never run it here.
const out = new Headers({
"x-content-type-options": "nosniff",
"content-security-policy": "sandbox",
});
for (const name of ANSWER_HEADERS) {
const value = answer.headers.get(name);
if (value) out.set(name, value);
}
return new Response(answer.body, { status: answer.status, headers: out });
}
// ── the deployment's tokens ─────────────────────────────────────────────────────────────────────
/** The Cloud as a client of every deployment: its client id is the address of this document. */
const clientOf = (origin) => ({
client_id: `${origin}${CLIENT}`,
client_name: "iterate Cloud, for your AI app",
client_uri: origin,
redirect_uris: [`${origin}${CALLBACK}`],
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code"],
token_endpoint_auth_method: "none",
});
/** One request to a deployment's token endpoint: `{ ok, status, body }`. */
async function tokenRequest(origin, { tokenEndpoint, resource }, fields) {
try {
const answer = await fetch(tokenEndpoint, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
body: new URLSearchParams({ ...fields, client_id: `${origin}${CLIENT}`, resource }),
redirect: "manual",
signal: AbortSignal.timeout(15_000),
});
const body = await answer.json().catch(() => null);
return { ok: answer.ok && typeof body?.access_token === "string", status: answer.status, body };
} catch {
// no answer in time, or none at all: not the deployment's refusal
return { ok: false, status: 504, body: null };
}
}
/** The deployment's tokens as a connection keeps them. */
const tokensOf = (body, before) => ({
accessToken: body.access_token,
refreshToken: body.refresh_token || before?.refreshToken || null,
expiresAt: Date.now() + (Number(body.expires_in) || 3600) * 1000,
});
/** How long the app's token may live: as long as the deployment's, so the relay never refreshes.
* KV keeps nothing for under a minute. */
const lifeOf = ({ expiresAt }) =>
Math.min(GRANT_IDLE_LIFE, Math.max(60, Math.floor((expiresAt - Date.now()) / 1000) - 30));
/** What one of the app's access tokens unwraps: where to send its requests, and the deployment's
* access token. Never the deployment's refresh token, which a refresh alone needs. */
const accessProps = ({ resource, accessToken }) => ({ resource, accessToken });
/** Why a registration is refused, or nothing: too large, or too many just now. */
async function registrationRefusal({ clientMetadata, request }, kv) {
if (JSON.stringify(clientMetadata).length > CLIENT_METADATA_MAX_CHARACTERS)
return {
description: `Client metadata may be ${CLIENT_METADATA_MAX_CHARACTERS} characters at most.`,
status: 413,
};
const window = Math.floor(Date.now() / (REGISTRATION_WINDOW_SECONDS * 1000));
const address = request.headers.get("cf-connecting-ip") || "unknown";
/** @type {[key: string, most: number][]} */
const counted = [
[`registrations:${window}`, REGISTRATIONS.inAll],
[`registrations:${window}:${address}`, REGISTRATIONS.perAddress],
];
// Both counts are read before either is added to: a refused registration counts nowhere, so one
// address at its limit cannot use up everybody's.
const counts = await Promise.all(counted.map(async ([key]) => Number(await kv.get(key)) || 0));
if (counted.some(([, most], index) => counts[index] >= most)) {
console.warn({ event: "mcp-relay.registration-refused" });
return {
code: "temporarily_unavailable",
description: "Too many apps registered here just now. Wait ten minutes, then try again.",
status: 429,
};
}
await Promise.all(
counted.map(([key], index) =>
kv.put(key, String(counts[index] + 1), { expirationTtl: 2 * REGISTRATION_WINDOW_SECONDS }),
),
);
}
/** At each token the app gets. Its first lives as long as the deployment's token from the
* sign-in. At a refresh, the deployment's token is refreshed too; when the deployment says the
* grant is gone, this connection is removed with it and the app signs in again. */
async function exchanged(origin, options, { grantType, props, grantId, userId, env }) {
if (grantType !== "refresh_token")
return { accessTokenProps: accessProps(props), accessTokenTTL: lifeOf(props) };
const ended = async (description) => {
await getOAuthApi(options, env).revokeGrant(grantId, userId);
return new OAuthError("invalid_grant", { description });
};
if (!props.refreshToken) throw await ended("The deployment gave no refresh token");
const { ok, status, body } = await tokenRequest(origin, props, {
grant_type: "refresh_token",
refresh_token: props.refreshToken,
});
if (!ok && status >= 400 && status < 500 && status !== 429)
throw await ended("The deployment ended this connection");
if (!ok)
throw new OAuthError("temporarily_unavailable", {
description: "The deployment did not answer",
statusCode: 503,
});
const newProps = { ...props, ...tokensOf(body, props) };
return { newProps, accessTokenProps: accessProps(newProps), accessTokenTTL: lifeOf(newProps) };
}
// ── which deployment ────────────────────────────────────────────────────────────────────────────
async function readJson(url) {
try {
const answer = await fetch(url, {
headers: { accept: "application/json" },
redirect: "manual",
signal: AbortSignal.timeout(8000),
});
return answer.ok ? await answer.json() : null;
} catch {
return null;
}
}
/** The deployment a person named, read from its own metadata: its MCP server at
* `https://iterate.<domain>/mcp`, and its identity provider on that same host. Null when nothing
* there answers as one. `typed` may be the domain, the platform's hostname or the MCP address. */
export async function deploymentOf(typed) {
const name = String(typed || "")
.trim()
.toLowerCase()
.replace(/^https?:\/\//, "")
.replace(/[/?#].*$/, "");
if (!DOMAIN.test(name)) return null;
// "iterate.garple.com" is garple.com's platform, so that name itself is tried first. But
// "iterate.com" is a domain, whose platform is iterate.iterate.com: its own host serves the
// deployment's loaded code, which must not answer as the deployment. So a name is tried as a
// platform's host only when a whole domain follows its "iterate." label.
const platformHost = name.startsWith("iterate.") && name.slice("iterate.".length).includes(".");
const hosts = platformHost ? [name, `iterate.${name}`] : [`iterate.${name}`];
for (const host of hosts) {
const resource = `https://${host}/mcp`;
const server = await readJson(`https://${host}/.well-known/oauth-protected-resource/mcp`);
// A deployment is its own identity provider, at its platform's host, and nowhere else. The
// metadata is the typed domain's word: without this, a hostile domain could name another
// deployment's sign-in with a token endpoint of its own, and get that deployment's code and
// this sign-in's PKCE verifier.
const issuer = `https://${host}`;
if (server?.resource !== resource || server.authorization_servers?.[0] !== issuer) continue;
const provider = await readJson(`${issuer}/.well-known/oauth-authorization-server`);
const own = (endpoint) => typeof endpoint === "string" && endpoint.startsWith(`${issuer}/`);
if (
provider?.issuer === issuer &&
own(provider.authorization_endpoint) &&
own(provider.token_endpoint) &&
provider.client_id_metadata_document_supported === true &&
provider.code_challenge_methods_supported?.includes("S256")
)
return {
domain: host.slice("iterate.".length),
resource,
issuer,
authorizationEndpoint: provider.authorization_endpoint,
tokenEndpoint: provider.token_endpoint,
};
}
return null;
}
// ── the pages: which deployment, and back from it ───────────────────────────────────────────────
const esc = (value) =>
String(value ?? "").replace(
/[&<>"']/g,
(c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c],
);
const page = (title, body, { status = 200, headers = new Headers() } = {}) => {
const style =
"body{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:3rem auto;padding:0 1rem}input[name=domain]{font:inherit;padding:.4rem;width:100%;box-sizing:border-box}button{font:inherit;padding:.4rem .9rem;margin-right:.5rem}.quiet{color:#555;font-size:14px}";
headers.set("content-type", "text/html; charset=utf-8");
headers.set("cache-control", "no-store");
return new Response(
`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${esc(title)}</title><style>${style}</style><h1>${esc(title)}</h1>${body}`,
{ status, headers },
);
};
const go = (location, headers = new Headers()) => {
headers.set("location", location);
return new Response(null, { status: 302, headers });
};
const b64url = (bytes) =>
btoa(String.fromCharCode(...new Uint8Array(bytes)))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
/** Whether a consent form's handle is one that this page gave this browser and that still
* waits. It reads what the library wrote at `beginConsent`: a cookie named by the handle's hash,
* with that hash as its value, and a row under the hash for ten minutes. A cookie alone proves
* nothing (anybody can hash a handle they made up); the row is what only the page makes. Nothing
* is used up here: the library checks all of it again at `approveConsent`. */
async function waits(request, kv, handle) {
if (!handle) return false;
const hash = [
...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(handle))),
]
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
const bound = (request.headers.get("cookie") || "")
.split(";")
.map((cookie) => cookie.trim().split("="))
// the library's cookies start with "__Host-oauth-": the consent form's handle is bound to one
.find(([name]) => name === `__Host-oauth-consent-${hash.slice(0, 16)}`)?.[1];
return bound === hash && (await kv.get(`transaction:${hash}`)) !== null;
}
function askPage(details, handle, headers) {
const from = details.clientDomain
? `Published by <strong>${esc(details.clientDomain)}</strong>.`
: "This app registered itself, so its name is not verified.";
const local = details.redirectIsLoopback
? "<p><strong>This sends access to an app on your computer.</strong> Continue only if you just started to connect from it.</p>"
: "";
return page(
`Connect ${details.clientName} to your iterate`,
`<p>${from} Access goes to <strong>${esc(details.redirectHost)}</strong>.</p>${local}
<form method="post">
<input type="hidden" name="handle" value="${esc(handle)}">
<p><label>Your deployment's domain<br><input name="domain" placeholder="example.com" autocapitalize="none" autocomplete="off" spellcheck="false" required autofocus></label></p>
<p><button name="decision" value="approve">Continue</button><button name="decision" value="deny" formnovalidate>Cancel</button></p>
</form>
<p class="quiet">Next you sign in on your own deployment, and it asks whether to let this app in. iterate Cloud passes the app's requests on to your deployment: it sees each request and each answer while it passes, and does not store what is in them. It keeps no token that it can read. The connection ends when the app disconnects, or 30 days after the app last used it.</p>`,
{ headers },
);
}
/** Everything that is not the MCP server or the library's own endpoints. */
async function pages(request, env) {
const url = new URL(request.url);
const oauth = env.OAUTH_PROVIDER;
try {
if (url.pathname === CLIENT && request.method === "GET")
return Response.json(clientOf(url.origin), {
headers: { "cache-control": "public, max-age=300" },
});
if (url.pathname === CHALLENGE && env.OPENAI_APPS_CHALLENGE)
return new Response(env.OPENAI_APPS_CHALLENGE);
if (url.pathname === AUTHORIZE && request.method === "GET") {
const asked = await oauth.parseAuthRequest(request);
// PKCE with S256 for every app: the library requires it of a public client, and an app that
// registered with a secret is held to it here too.
if (asked.codeChallengeMethod !== "S256" || !asked.codeChallenge)
return go(
authorizationErrorRedirect(asked, "invalid_request", "PKCE with S256 is required."),
);
const details = await oauth.describeConsent(asked);
const consent = await oauth.beginConsent(asked);
return askPage(details, consent.handle, consent.headers);
}
if (url.pathname === AUTHORIZE && request.method === "POST") {
const form = await request.formData();
const handle = String(form.get("handle") || "");
if (form.get("decision") !== "approve")
return new Response(null, {
status: 302,
headers: (await oauth.denyConsent(request, handle)).headers,
});
// A form whose handle this page did not give this browser, or that waited too long, gets
// no request made for it to whatever domain it names.
if (!(await waits(request, env.OAUTH_KV, handle)))
return page(
"This sign-in cannot go on",
"<p>This form was not sent from its own page, or the page waited longer than ten minutes. Go back to the app and start again.</p>",
{ status: 400 },
);
// before the handle is used up: a mistyped domain leaves the form good to send again
const deployment = await deploymentOf(form.get("domain"));
if (!deployment)
return page(
"No deployment there",
`<p>No iterate deployment answered for <strong>${esc(form.get("domain"))}</strong>. Go back and check the domain. It is the one your deployment runs on: for <code>iterate.example.com</code>, type <code>example.com</code>.</p>`,
{ status: 400 },
);
const approved = await oauth.approveConsent(request, handle);
const verifier = b64url(crypto.getRandomValues(new Uint8Array(32)));
const { state, headers } = await oauth.beginUpstream(approved.request, {
data: { ...deployment, verifier },
headers: approved.headers,
});
const there = new URL(deployment.authorizationEndpoint);
there.search = new URLSearchParams({
response_type: "code",
client_id: `${url.origin}${CLIENT}`,
redirect_uri: `${url.origin}${CALLBACK}`,
scope: SCOPE,
resource: deployment.resource,
state,
code_challenge: b64url(
await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)),
),
code_challenge_method: "S256",
}).toString();
return go(there.href, headers);
}
if (url.pathname === CALLBACK && request.method === "GET") {
const { request: original, data, headers } = await oauth.finishUpstream(request);
const code = url.searchParams.get("code");
const iss = url.searchParams.get("iss");
if (url.searchParams.get("error") || !code || (iss && iss !== data.issuer))
return go(
authorizationErrorRedirect(
original,
"access_denied",
"The deployment did not let the app in",
),
headers,
);
const { ok, body } = await tokenRequest(url.origin, data, {
grant_type: "authorization_code",
code,
redirect_uri: `${url.origin}${CALLBACK}`,
code_verifier: data.verifier,
});
if (!ok)
return go(
authorizationErrorRedirect(
original,
"server_error",
"The deployment refused the sign-in's code",
),
headers,
);
const { redirectTo } = await oauth.completeAuthorization({
request: original,
// The Cloud has no users: a connection is its own subject, and who the person is stays
// at the deployment.
userId: crypto.randomUUID(),
metadata: { domain: data.domain },
scope: original.scope,
props: {
domain: data.domain,
resource: data.resource,
tokenEndpoint: data.tokenEndpoint,
...tokensOf(body),
},
});
return go(redirectTo, headers);
}
} catch (error) {
if (!(error instanceof AuthorizationError)) throw error;
if (error.redirectTo) return go(error.redirectTo);
return page("This sign-in cannot go on", `<p>${esc(error.description)}</p>`, { status: 400 });
}
return new Response("Not found\n", { status: 404 });
}