feat(server): outside agents sign in to the T3 MCP server with OAuth #15220
Closedjuliusmarmingewants to merge 11 commits into
main fromt3code/mcp-oauth/sign-inopened View on GitHubjuliusmarminge added labelsmacroscope-review
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
- apps/server/src/auth/EnvironmentAuth.ts line 75OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -63,3 +66,10 @@6366 readonly expiresAt: DateTime.Utc;6467 }656869+/**70+ * Sessions an MCP client (an agent T3 Code did not launch) obtains through71+ * OAuth. They are accepted only by `/mcp`, where every action is capped by the72+ * runtime-mode ceiling the user approved; the HTTP API and WebSocket reject73+ * them so an agent token cannot reach the full RPC surface around that cap.74+ */75+export const MCP_CLIENT_SUBJECT = "mcp-client";apps/server/src/auth/EnvironmentAuth.ts lines 1222 to 1238OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1096,0 +1218,21 @@1218+ Effect.withSpan("EnvironmentAuth.authenticateBrowserSession"),1219+ );1220+ };1221+1222+ const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (code) =>1223+ // No proof key: a code bound to a T3 Connect client's key fails without being spent.1224+ resolveBootstrapGrant(code.trim()).pipe(1225+ Effect.catchIf(1226+ (error): error is ServerAuthInvalidCredentialError =>1227+ error._tag === "ServerAuthInvalidCredentialError",1228+ () => Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),1229+ ),1230+ Effect.flatMap((grant) =>1231+ grant.method !== "one-time-token" && grant.method !== "reusable-dev-token"1232+ ? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" }))1233+ : MCP_CLIENT_SCOPES.every((scope) => grant.scopes.includes(scope))1234+ ? Effect.void1235+ : Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),1236+ ),1237+ Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"),1238+ );apps/server/src/auth/McpOAuth.ts line 54OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +34,21 @@34+ * T3 Code did not launch) use to sign in to this environment's `/mcp`.35+ *36+ * Every URL is derived from the request's own origin, so the same server37+ * answers correctly over loopback, Tailscale Serve and a T3 Connect tunnel.38+ * Client registration is stateless: a client id is its signed metadata, so39+ * an unauthenticated caller cannot grow server state. Only loopback redirect40+ * URIs are accepted; an https redirect would let anyone mail the owner an41+ * approval link that delivers the code to their own server.42+ */43+44+const SIGNING_SECRET_NAME = "mcp-oauth-signing-key";45+const AUTHORIZATION_CODE_TTL_MS = 60_000;46+const MAX_CLIENT_NAME_LENGTH = 100;47+const MAX_REDIRECT_URIS = 5;48+const MAX_REDIRECT_URI_LENGTH = 512;49+const DEFAULT_CLIENT_NAME = "MCP client";50+const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);51+const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;52+const CODE_VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/;53+54+export const MCP_OAUTH_SCOPE = encodeOAuthScope(EnvironmentAuth.MCP_CLIENT_SCOPES);apps/server/src/auth/McpOAuth.ts lines 62 to 68OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +48,21 @@48+const MAX_REDIRECT_URI_LENGTH = 512;49+const DEFAULT_CLIENT_NAME = "MCP client";50+const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);51+const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;52+const CODE_VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/;53+54+export const MCP_OAUTH_SCOPE = encodeOAuthScope(EnvironmentAuth.MCP_CLIENT_SCOPES);55+export const decodeRuntimeMode = Schema.decodeUnknownOption(RuntimeMode);56+57+export interface McpOAuthUrls {58+ readonly issuer: string;59+ readonly resource: string;60+}61+62+/** Issuer and MCP resource for the origin this request reached. */63+export const requestUrls = (64+ request: HttpServerRequest.HttpServerRequest,65+): Option.Option<McpOAuthUrls> =>66+ HttpServerRequest.toURL(request).pipe(67+ Option.map((url) => ({ issuer: url.origin, resource: `${url.origin}/mcp` })),68+ );apps/server/src/auth/McpOAuth.ts lines 561 to 604Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +588,21 @@588+ runtimeModeCeiling: client.runtimeModeCeiling,589+ },590+ capabilities: new Set<McpInvocationContext.McpCapability>([591+ "orchestration",592+ "worktree",593+ "pull-requests",594+ ]),595+ issuedAt,596+ })),597+ ),598+ ),599+ Effect.catch((error) =>600+ (EnvironmentAuth.isServerAuthCredentialError(error)601+ ? Effect.void602+ : Effect.logWarning("MCP client authentication failed.", { cause: error })603+ ).pipe(Effect.as(undefined)),604+ ),605+ ),606+ });607+ }),608+);apps/server/src/mcp/McpHttpServer.ts line 63OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -59,13 +59,5 @@5959 DeviceStandardToolkit,6060 } from "./toolkits/device/tools.ts";616162-const unauthorized = HttpServerResponse.jsonUnsafe(63- {64- error: "invalid_mcp_credential",65- message: "A valid provider-scoped MCP bearer credential is required.",66- },67- {68- status: 401,69- headers: {70- "cache-control": "no-store",71- "www-authenticate": "Bearer",62+/** Where an MCP client discovers how to sign in (RFC 9728), at this request's own origin. */63+export const mcpResourceMetadataUrl = (request: HttpServerRequest.HttpServerRequest) =>
- apps/server/src/auth/EnvironmentAuth.ts line 1237Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1096,0 +1217,21 @@1217+ ) => {1218+ const token =1219+ request.cookies[sessions.cookieName] ??1220+ (sessions.legacyCookieName ? request.cookies[sessions.legacyCookieName] : undefined) ??1221+ (devAuth ? request.cookies[devAuth.cookieName] : undefined);1222+ if (!token) return Effect.fail(new ServerAuthMissingCredentialError({}));1223+ return authenticateToken(token).pipe(1224+ Effect.filterOrFail(1225+ (session) => session.method === "browser-session-cookie" && !session.proofKeyThumbprint,1226+ () => new ServerAuthInvalidCredentialError({ diagnostic: "Not a browser session." }),1227+ ),1228+ Effect.withSpan("EnvironmentAuth.authenticateBrowserSession"),1229+ );1230+ };1231+1232+ const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (1233+ code,1234+ access,1235+ ) =>1236+ // No proof key: a code bound to a T3 Connect client's key fails without being spent.1237+ resolveBootstrapGrant(code.trim()).pipe(
- apps/server/src/auth/McpOAuth.ts line 398OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +378,21 @@378+ );379+ }380+ return {381+ client,382+ redirectUri,383+ codeChallenge,384+ state,385+ resource: urls.resource,386+ issuer: urls.issuer,387+ } satisfies AuthorizationRequest;388+ });389+390+ const approvingBrowserSession: McpOAuth["Service"]["approvingBrowserSession"] = (391+ request,392+ authorization,393+ ) =>394+ environmentAuth.authenticateBrowserSession(request).pipe(395+ Effect.map((session) =>396+ // Approving manages access, and a session may only hand out scopes it holds.397+ session.scopes.includes(AuthAccessWriteScope) &&398+ MCP_OAUTH_SCOPES.every((scope) => session.scopes.includes(scope))
- apps/server/src/auth/mcpOAuthHttp.ts lines 37 to 37OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +17,21 @@17+18+const PAGE_HEADERS = {19+ "content-security-policy":20+ "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'",21+ "x-frame-options": "DENY",22+ "cache-control": "no-store",23+ "referrer-policy": "no-referrer",24+ "x-content-type-options": "nosniff",25+};26+27+/** OAuth responses carry codes, tokens and client ids, none of which may be cached. */28+const noStore = HttpEffect.appendPreResponseHandler((_request, response) =>29+ Effect.succeed(30+ HttpServerResponse.setHeaders(response, { "cache-control": "no-store", pragma: "no-cache" }),31+ ),32+);33+34+/** Issuer and resource for the origin this request reached. */35+const requestUrls = Effect.map(HttpServerRequest.HttpServerRequest, McpOAuth.requestUrls);36+37+const approvalError = (message: string) => new AuthMcpApprovalError({ message });apps/server/src/auth/EnvironmentAuth.ts lines 1238 to 1238OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1096,0 +1218,21 @@1218+ const token =1219+ request.cookies[sessions.cookieName] ??1220+ (sessions.legacyCookieName ? request.cookies[sessions.legacyCookieName] : undefined) ??1221+ (devAuth ? request.cookies[devAuth.cookieName] : undefined);1222+ if (!token) return Effect.fail(new ServerAuthMissingCredentialError({}));1223+ return authenticateToken(token).pipe(1224+ Effect.filterOrFail(1225+ (session) => session.method === "browser-session-cookie" && !session.proofKeyThumbprint,1226+ () => new ServerAuthInvalidCredentialError({ diagnostic: "Not a browser session." }),1227+ ),1228+ Effect.withSpan("EnvironmentAuth.authenticateBrowserSession"),1229+ );1230+ };1231+1232+ const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (1233+ code,1234+ access,1235+ ) =>1236+ // No proof key: a code bound to a T3 Connect client's key fails without being spent.1237+ resolveBootstrapGrant(code.trim()).pipe(1238+ Effect.catchIf(
- @@ -28,3 +30,17 @@2830 return new OrchestratorMcpFailure({ code: "invalid_request", message });2931 }303233+/**34+ * An existing checkout a launch may bind: one of the project's own git35+ * worktrees. Without this check a launch could point an agent at any directory36+ * on the machine.37+ */38+const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* (39+ workspaceRoot: string,40+ worktreePath: string,41+) {42+ const git = yield* GitVcsDriver.GitVcsDriver;43+ const fileSystem = yield* FileSystem.FileSystem;44+ const real = (path: string) => fileSystem.realPath(path).pipe(Effect.orElseSucceed(() => path));45+ const worktrees = yield* git.listWorktreePaths(workspaceRoot).pipe(46+ Effect.flatMap((paths) => Effect.forEach(paths, real)),
- @@ -1,17 +1,11 @@11 import { MessageId, ThreadId, OrchestratorMcpFailure, ProjectId } from "@t3tools/contracts";22 import * as Effect from "effect/Effect";3+import * as FileSystem from "effect/FileSystem";34 import * as Option from "effect/Option";45 import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";56 import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";67 import * as Project from "../../../project/ProjectService.ts";78 import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts";89 import * as Repositories from "../../../sourceControl/SourceControlRepositoryService.ts";9-import { resolveRuntimeMode } from "../../OrchestratorMcpService.ts";10-import {11- newCommandId,12- readCaller,13- readFullAccessCaller,14- readMutationCaller,15- resolveProjectId,16- unavailable,17-} from "../../threadAccess.ts";10+import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";11+import * as McpToolAccess from "../../McpToolAccess.ts";
juliusmarminge closed this
Sign in to join this conversation.




Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
204a639· PR result:de97505· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.