Skip to content
TypeScript

feat(server): hosted agents like ChatGPT can sign in to the T3 MCP server (#16718)

Julius Marminge10f39eb9ac80
diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts
index f1a616c4927..97e4a4d824c 100644
--- a/apps/server/src/auth/McpOAuth.test.ts
+++ b/apps/server/src/auth/McpOAuth.test.ts
@@ -180,12 +180,20 @@ it.live("derives discovery metadata from the origin the client reached", () =>
),
);
-it.live("registers only loopback clients and never redirects for an unverified client", () =>
+it.live("registers loopback and https clients and never redirects for an unverified client", () =>
withRoutes((handler) =>
Effect.gen(function* () {
- const remote = yield* register(handler, "https://attacker.example/callback");
- expect(remote.status).toBe(400);
- expect(yield* json<unknown>(remote)).toMatchObject({ error: "invalid_redirect_uri" });
+ for (const refused of [
+ "http://bot.example/callback",
+ "https://user:[email protected]/callback",
+ "https://bot.example/callback#",
+ "http://localhost/callback#",
+ "javascript:alert(1)",
+ ]) {
+ const response = yield* register(handler, refused);
+ expect(response.status).toBe(400);
+ expect(yield* json<unknown>(response)).toMatchObject({ error: "invalid_redirect_uri" });
+ }
const registered = yield* register(handler);
expect(registered.status).toBe(201);
@@ -308,6 +316,70 @@ it.live("signs in with a pairing code and issues a token only /mcp accepts", ()
),
);
+it.live("signs in a hosted agent with an https callback that asked for a client secret", () =>
+ withRoutes((handler, auth) =>
+ Effect.gen(function* () {
+ const callbackUrl = "https://bot.example/oauth/callback";
+ const registered = yield* handler(
+ at("/oauth/mcp/register", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: encodeJson({
+ client_name: "Hosted bot",
+ redirect_uris: [callbackUrl],
+ token_endpoint_auth_method: "client_secret_post",
+ }),
+ }),
+ );
+ expect(registered.status).toBe(201);
+ const client = (yield* json<unknown>(registered)) as {
+ client_id: string;
+ token_endpoint_auth_method: string;
+ };
+ // Registered as a public client: PKCE, not a secret, proves it at the token endpoint.
+ expect(client.token_endpoint_auth_method).toBe("none");
+
+ const params = authorizeParams(client.client_id, callbackUrl);
+ const details = yield* handler(postJson("/oauth/mcp/approval", params)).pipe(
+ Effect.flatMap(json<Record<string, unknown>>),
+ );
+ expect(details).toMatchObject({ clientName: "Hosted bot", redirectHost: "bot.example" });
+
+ const pairing = yield* auth.issuePairingCredential();
+ const approved = yield* decide(handler, params, {
+ _tag: "pairing-code",
+ access: "approval-required",
+ code: pairing.credential,
+ });
+ const callback = new URL(approved.redirectTo!);
+ expect(`${callback.origin}${callback.pathname}`).toBe(callbackUrl);
+
+ const tokenResponse = yield* handler(
+ at(
+ "/oauth/mcp/token",
+ form({
+ grant_type: "authorization_code",
+ code: callback.searchParams.get("code")!,
+ redirect_uri: callbackUrl,
+ client_id: client.client_id,
+ // Sent by a client that asked for one; there is none to check.
+ client_secret: "unused",
+ code_verifier: verifier,
+ }),
+ ),
+ );
+ expect(tokenResponse.status).toBe(200);
+ const token = (yield* json<unknown>(tokenResponse)) as { access_token: string };
+ const signedIn = yield* auth.authenticateMcpClient(
+ HttpServerRequest.fromWeb(
+ at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }),
+ ),
+ );
+ expect(signedIn).toMatchObject({ label: "Hosted bot", access: "approval-required" });
+ }),
+ ),
+);
+
it.live("rejects a wrong PKCE verifier and spends the code", () =>
withRoutes((handler, auth) =>
Effect.gen(function* () {
@@ -489,17 +561,14 @@ it.live("one-click approves only access the browser session holds the scopes for
),
);
-it("matches loopback redirects on everything but the port", () => {
- expect(
- McpOAuth.loopbackRedirectMatches("http://localhost/callback", "http://localhost:9/callback"),
- ).toBe(true);
- expect(
- McpOAuth.loopbackRedirectMatches("http://127.0.0.1:1/callback", "http://127.0.0.1:2/callback"),
- ).toBe(true);
- expect(
- McpOAuth.loopbackRedirectMatches("http://localhost/callback", "http://127.0.0.1/callback"),
- ).toBe(false);
- expect(
- McpOAuth.loopbackRedirectMatches("http://localhost/callback", "https://localhost/callback"),
- ).toBe(false);
+it("matches loopback redirects on everything but the port, and https redirects exactly", () => {
+ const matches = McpOAuth.redirectMatches;
+ expect(matches("http://localhost/callback", "http://localhost:9/callback")).toBe(true);
+ expect(matches("http://127.0.0.1:1/callback", "http://127.0.0.1:2/callback")).toBe(true);
+ expect(matches("http://localhost/callback", "http://127.0.0.1/callback")).toBe(false);
+ expect(matches("http://localhost/callback", "https://localhost/callback")).toBe(false);
+ expect(matches("https://bot.example/cb", "https://bot.example/cb")).toBe(true);
+ expect(matches("https://bot.example/cb", "https://bot.example:8443/cb")).toBe(false);
+ expect(matches("https://bot.example/cb", "https://bot.example/cb?x=1")).toBe(false);
+ expect(matches("https://bot.example/cb", "https://evil.example/cb")).toBe(false);
});
diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts
index 0ae7cdf888a..2ab4e50d9dc 100644
--- a/apps/server/src/auth/McpOAuth.ts
+++ b/apps/server/src/auth/McpOAuth.ts
@@ -45,9 +45,10 @@ import {
* Every URL is derived from the request's own origin, so the same server
* answers correctly over loopback, Tailscale Serve and a T3 Connect tunnel.
* Client registration is stateless: a client id is its signed metadata, so
- * an unauthenticated caller cannot grow server state. Only loopback redirect
- * URIs are accepted; an https redirect would let anyone mail the owner an
- * approval link that delivers the code to their own server.
+ * an unauthenticated caller cannot grow server state. Redirects go to a
+ * loopback address (a CLI agent on the user's machine) or any https address
+ * (a hosted agent); the approval page names where access goes, and the user
+ * decides.
*/
const SIGNING_SECRET_NAME = "mcp-oauth-signing-key";
@@ -105,29 +106,32 @@ export const authorizationServerMetadata = (
authorization_response_iss_parameter_supported: true,
});
-const parseLoopbackRedirect = (value: string): URL | undefined => {
- if (value.length > MAX_REDIRECT_URI_LENGTH) return undefined;
+/** A redirect URI an MCP client may register: loopback http, or any https. */
+const parseRedirect = (value: string): URL | undefined => {
+ // No fragment, not even an empty one, which `URL.hash` reports as "" (RFC 6749 §3.1.2).
+ if (value.length > MAX_REDIRECT_URI_LENGTH || value.includes("#")) return undefined;
try {
const url = new URL(value);
- return url.protocol === "http:" &&
- LOOPBACK_HOSTNAMES.has(url.hostname) &&
- url.username === "" &&
- url.password === "" &&
- url.hash === ""
- ? url
- : undefined;
+ const allowed =
+ url.protocol === "https:" ||
+ (url.protocol === "http:" && LOOPBACK_HOSTNAMES.has(url.hostname));
+ return allowed && url.username === "" && url.password === "" ? url : undefined;
} catch {
return undefined;
}
};
-/** RFC 8252 §7.3: loopback redirects match on everything but the port. */
-export const loopbackRedirectMatches = (registered: string, presented: string): boolean => {
- const left = parseLoopbackRedirect(registered);
- const right = parseLoopbackRedirect(presented);
+/**
+ * Whether a presented redirect is one the client registered. Loopback
+ * redirects match on everything but the port (RFC 8252 §7.3), since CLI
+ * agents listen on whatever port is free; https redirects match exactly.
+ */
+export const redirectMatches = (registered: string, presented: string): boolean => {
+ const left = parseRedirect(registered);
+ const right = parseRedirect(presented);
+ if (left === undefined || right === undefined) return false;
+ if (left.protocol === "https:" || right.protocol === "https:") return left.href === right.href;
return (
- left !== undefined &&
- right !== undefined &&
left.hostname === right.hostname &&
left.pathname === right.pathname &&
left.search === right.search
@@ -320,24 +324,17 @@ const make = Effect.gen(function* () {
error_description: `Register between 1 and ${MAX_REDIRECT_URIS} redirect URIs.`,
});
}
- if (!redirectUris.every((uri) => parseLoopbackRedirect(uri) !== undefined)) {
+ if (!redirectUris.every((uri) => parseRedirect(uri) !== undefined)) {
return yield* new AuthMcpRegistrationError({
error: "invalid_redirect_uri",
error_description:
- "Only http://localhost, 127.0.0.1 or [::1] redirect URIs are accepted.",
- });
- }
- if (
- metadata.token_endpoint_auth_method !== undefined &&
- metadata.token_endpoint_auth_method !== "none"
- ) {
- return yield* new AuthMcpRegistrationError({
- error: "invalid_client_metadata",
- error_description: "Only public clients (token_endpoint_auth_method none) are supported.",
+ "Redirect URIs must be https, or http on localhost, 127.0.0.1 or [::1].",
});
}
- // Requested grant types and scopes are ignored rather than rejected: RFC 7591 lets
- // the server answer with what it supports, and Claude Code asks for refresh_token.
+ // Requested grant types, scopes and token endpoint auth methods are ignored rather
+ // than rejected: RFC 7591 lets the server answer with what it supports. Claude Code
+ // asks for refresh_token, and hosted agents may ask for a client secret; every client
+ // is registered as public and proves itself with PKCE instead.
return { clientId: signClientId(name, redirectUris), name, redirectUris };
});
@@ -352,8 +349,7 @@ const make = Effect.gen(function* () {
const redirectUri = request.redirect_uri;
if (
redirectUri === undefined ||
- parseLoopbackRedirect(redirectUri) === undefined ||
- !client.redirectUris.some((registered) => loopbackRedirectMatches(registered, redirectUri))
+ !client.redirectUris.some((registered) => redirectMatches(registered, redirectUri))
) {
return yield* new McpOAuthPageError({
description: "This sign-in link sends you to an address the app did not register.",
diff --git a/apps/web/src/components/auth/ConnectAgentSurface.tsx b/apps/web/src/components/auth/ConnectAgentSurface.tsx
index 926a03b1635..12d620a0c7e 100644
--- a/apps/web/src/components/auth/ConnectAgentSurface.tsx
+++ b/apps/web/src/components/auth/ConnectAgentSurface.tsx
@@ -6,6 +6,7 @@ import {
type AuthMcpAuthorizationRequest,
} from "@t3tools/contracts";
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
+import { isLoopbackHost } from "@t3tools/shared/preview";
import { EyeIcon, type LucideIcon } from "lucide-react";
import type * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -35,6 +36,11 @@ const accessConfig: Record<
...runtimeModeConfig,
};
+/** A CLI agent's callback is a loopback address; a hosted agent's is its own server. */
+function redirectsToThisComputer(redirectHost: string): boolean {
+ return isLoopbackHost(new URL(`http://${redirectHost}`).hostname);
+}
+
type Loaded =
| { readonly status: "loading" }
| { readonly status: "invalid"; readonly message: string }
@@ -188,8 +194,18 @@ export function ConnectAgentSurface() {
}
/>
<p className="mt-2 text-xs text-muted-foreground">
- The name is chosen by the agent. Approval returns to {details.redirectHost} on the computer
- that opened this page. Only approve a sign-in you just started.
+ {redirectsToThisComputer(details.redirectHost) ? (
+ <>
+ The name is chosen by the agent. Approval returns to {details.redirectHost} on the
+ computer that opened this page. Only approve a sign-in you just started.
+ </>
+ ) : (
+ <>
+ The name is chosen by the agent. Approval gives access to whoever runs{" "}
+ <span className="font-medium text-foreground">{details.redirectHost}</span>. Only
+ approve a sign-in you just started there.
+ </>
+ )}
</p>
<form
diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.md
index 2526ee69caf..132b6554812 100644
--- a/docs/internals/environment-auth.md
+++ b/docs/internals/environment-auth.md
@@ -27,9 +27,12 @@ vocabulary gives these grants a familiar meaning.
Agents T3 Code did not launch sign in to `/mcp` through a narrow OAuth
authorization-code server ([McpOAuth](../../apps/server/src/auth/McpOAuth.ts)).
-It accepts only loopback redirect URIs: an HTTPS redirect would let anyone send
-the owner an approval link that delivers the code to their own server. Client
-registration is stateless, so an unauthenticated caller cannot grow server
+It accepts loopback redirect URIs for agents on the user's machine and any
+HTTPS redirect for hosted agents (ChatGPT, bots). An HTTPS redirect means a
+link someone else sends the owner can deliver access to that someone, so the
+approval page names the host access goes to and approving stays the owner's
+call. Every client is public and proves itself with PKCE; a client that asks
+for a secret is registered without one. Client registration is stateless, so an unauthenticated caller cannot grow server
state. Approval spends a one-time pairing code, or uses a browser session with
`access:write`; proof-bound T3 Connect codes are refused without being spent.
diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts
index f0478da0c8a..e206163869c 100644
--- a/packages/contracts/src/auth.ts
+++ b/packages/contracts/src/auth.ts
@@ -562,7 +562,10 @@ export type AuthMcpAuthorizationRequest = typeof AuthMcpAuthorizationRequest.Typ
export const AuthMcpApprovalDetails = Schema.Struct({
/** Self-declared by the client, so shown as such. */
clientName: Schema.String,
- /** Where the code goes: always a loopback address on the browser's machine. */
+ /**
+ * Where the code goes: a loopback address on the browser's machine (a CLI
+ * agent), or an https host (a hosted agent).
+ */
redirectHost: Schema.String,
environmentHost: Schema.String,
/** Present when this browser's session may approve without a pairing code. */