Open History to see the last commit
1import {
2 AuthAccessWriteScope,
3 type AuthMcpApprovalDecision,
4 type AuthMcpAuthorizationRequest,
5 type AuthMcpAuthorizationServerMetadata,
6 type AuthMcpClientRegistration,
7 type AuthMcpProtectedResourceMetadata,
8 AuthMcpRegistrationError,
9 AuthMcpTokenError,
10 type AuthMcpTokenRequest,
11 type AuthMcpTokenResult,
12 type AuthMcpClientAccess,
13 type AuthEnvironmentScope,
14 AuthOrchestrationOperateScope,
15 AuthOrchestrationReadScope,
16 MCP_PEER_LINK_SOFTWARE_ID,
17 mcpClientScopes,
18 parseMcpApprovalCode,
19 type RuntimeMode,
20} from "@t3tools/contracts";
21import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
22import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
23import * as Clock from "effect/Clock";
24import * as Context from "effect/Context";
25import * as Digest from "effect/crypto/Digest";
26import * as SecureRandom from "effect/crypto/SecureRandom";
27import * as Effect from "effect/Effect";
28import * as Layer from "effect/Layer";
29import * as Option from "effect/Option";
30import * as Redacted from "effect/Redacted";
31import * as Ref from "effect/Ref";
32import * as Schema from "effect/Schema";
33import { HttpServerRequest } from "effect/http";
34
35import { hostedAppUrlConfig } from "../cloud/publicConfig.ts";
36import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
37import * as ServerSettings from "../serverSettings.ts";
38import * as McpHttpServer from "../mcp/McpHttpServer.ts";
39import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
40import * as PayloadSigner from "./PayloadSigner.ts";
41import * as EnvironmentAuth from "./EnvironmentAuth.ts";
42import * as ServerSecretStore from "./ServerSecretStore.ts";
43import {
44 base64UrlDecodeUtf8,
45 base64UrlEncode,
46 deriveAuthClientMetadata,
47 timingSafeEqualBase64Url,
48} from "./utils.ts";
49import { requestUrl } from "../requestUrl.ts";
50
51// Request-derived origins support loopback, Tailscale and tunnels.
52// Signed client metadata keeps unauthenticated registration stateless.
53
54const SIGNING_SECRET_NAME = "mcp-oauth-signing-key";
55const AUTHORIZATION_CODE_TTL_MS = 60_000;
56const MAX_CLIENT_NAME_LENGTH = 100;
57const MAX_REDIRECT_URIS = 10;
58const MAX_REDIRECT_URI_LENGTH = 512;
59// The client_id rides in the authorize URL. Past the original five-URI limit, cap it to leave room
60// under Node's 16 KB header cap for an encoded redirect_uri and state.
61const MAX_UNBOUNDED_CLIENT_ID_REDIRECT_URIS = 5;
62const MAX_CLIENT_ID_LENGTH = 10_240;
63const DEFAULT_CLIENT_NAME = "MCP client";
64const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
65const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
66const CODE_VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/;
67
68const MCP_OAUTH_SCOPES = [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
69
70export interface McpOAuthUrls {
71 readonly issuer: string;
72 readonly resource: string;
73}
74
75export const requestUrls = (request: HttpServerRequest.HttpServerRequest): McpOAuthUrls => {
76 const origin = Option.match(requestUrl(request), {
77 onNone: () => "http://localhost",
78 onSome: (url) => url.origin,
79 });
80 return { issuer: origin, resource: `${origin}/mcp` };
81};
82
83export const protectedResourceMetadata = (
84 urls: McpOAuthUrls,
85): AuthMcpProtectedResourceMetadata => ({
86 resource: urls.resource,
87 authorization_servers: [urls.issuer],
88 scopes_supported: MCP_OAUTH_SCOPES,
89 bearer_methods_supported: ["header"],
90 resource_name: "T3 Code",
91});
92
93export const authorizationServerMetadata = (
94 urls: McpOAuthUrls,
95): AuthMcpAuthorizationServerMetadata => ({
96 issuer: urls.issuer,
97 authorization_endpoint: `${urls.issuer}/oauth/mcp/authorize`,
98 token_endpoint: `${urls.issuer}/oauth/mcp/token`,
99 registration_endpoint: `${urls.issuer}/oauth/mcp/register`,
100 revocation_endpoint: `${urls.issuer}/oauth/mcp/revoke`,
101 response_types_supported: ["code"],
102 grant_types_supported: ["authorization_code"],
103 code_challenge_methods_supported: ["S256"],
104 token_endpoint_auth_methods_supported: ["none"],
105 scopes_supported: MCP_OAUTH_SCOPES,
106 authorization_response_iss_parameter_supported: true,
107});
108
109const parseRedirect = (value: string): URL | undefined => {
110 // URL.hash misses empty fragments, which RFC 6749 §3.1.2 also forbids.
111 if (value.length > MAX_REDIRECT_URI_LENGTH || value.includes("#")) return undefined;
112 try {
113 const url = new URL(value);
114 const allowed =
115 url.protocol === "https:" ||
116 (url.protocol === "http:" && LOOPBACK_HOSTNAMES.has(url.hostname));
117 return allowed && url.username === "" && url.password === "" ? url : undefined;
118 } catch {
119 return undefined;
120 }
121};
122
123/** Loopback redirects ignore port (RFC 8252 §7.3); HTTPS redirects match exactly. */
124export const redirectMatches = (registered: string, presented: string): boolean => {
125 const left = parseRedirect(registered);
126 const right = parseRedirect(presented);
127 if (left === undefined || right === undefined) return false;
128 if (left.protocol === "https:" || right.protocol === "https:") return left.href === right.href;
129 return (
130 left.hostname === right.hostname &&
131 left.pathname === right.pathname &&
132 left.search === right.search
133 );
134};
135
136const sameResource = (urls: McpOAuthUrls, presented: string | undefined): boolean => {
137 if (presented === undefined) return true;
138 // URL.hash misses empty fragments, which RFC 8707 §2 also forbids.
139 if (presented.includes("#")) return false;
140 try {
141 const url = new URL(presented);
142 return `${url.origin}${url.pathname.replace(/\/+$/u, "")}` === urls.resource;
143 } catch {
144 return false;
145 }
146};
147
148const ClientIdPayload = Schema.Struct({
149 v: Schema.Literal(1),
150 n: Schema.String,
151 r: Schema.Array(Schema.String),
152 /** Registered as another T3 Code environment's peer link. */
153 p: Schema.optionalKey(Schema.Literal(1)),
154});
155const decodeClientIdPayload = Schema.decodeUnknownOption(Schema.fromJsonString(ClientIdPayload));
156
157export interface McpOAuthClient {
158 readonly clientId: string;
159 readonly name: string;
160 readonly redirectUris: ReadonlyArray<string>;
161 readonly peerLink: boolean;
162}
163
164export class McpOAuthPageError extends Schema.TaggedError<McpOAuthPageError>()(
165 "McpOAuthPageError",
166 { description: Schema.String },
167) {
168 override get message(): string {
169 return this.description;
170 }
171}
172
173export class McpOAuthRedirectError extends Schema.TaggedError<McpOAuthRedirectError>()(
174 "McpOAuthRedirectError",
175 {
176 error: Schema.Literals(["invalid_request", "unsupported_response_type", "invalid_target"]),
177 description: Schema.String,
178 redirectUri: Schema.String,
179 state: Schema.optional(Schema.RedactedFromValue(Schema.String)),
180 },
181) {}
182
183export interface AuthorizationRequest {
184 readonly client: McpOAuthClient;
185 readonly redirectUri: string;
186 readonly codeChallenge: string;
187 readonly state: Redacted.Redacted<string> | undefined;
188 readonly resource: string;
189 readonly issuer: string;
190}
191
192interface PendingCode {
193 readonly clientId: string;
194 readonly clientName: string;
195 readonly peerLink: boolean;
196 readonly redirectUri: string;
197 readonly codeChallenge: string;
198 readonly resource: string;
199 readonly access: AuthMcpClientAccess;
200 readonly approvedAtRevocationCount: number;
201 readonly expiresAtMs: number;
202}
203
204export type ApprovalDecision = Exclude<AuthMcpApprovalDecision, { readonly _tag: "deny" }>;
205
206export class McpOAuth extends Context.Service<
207 McpOAuth,
208 {
209 readonly register: (
210 input: AuthMcpClientRegistration,
211 ) => Effect.Effect<McpOAuthClient, AuthMcpRegistrationError>;
212 /** Page errors must never redirect. */
213 readonly validateAuthorization: (input: {
214 readonly urls: McpOAuthUrls;
215 readonly request: AuthMcpAuthorizationRequest;
216 }) => Effect.Effect<AuthorizationRequest, McpOAuthPageError | McpOAuthRedirectError>;
217 /** A browser cookie session, or a T3 Connect session from the hosted app, that may approve. */
218 readonly approvingSession: (
219 request: HttpServerRequest.HttpServerRequest,
220 authorization: AuthorizationRequest,
221 ) => Effect.Effect<
222 | { readonly csrfToken: string; readonly scopes: ReadonlyArray<AuthEnvironmentScope> }
223 | undefined
224 >;
225 readonly approve: (input: {
226 readonly request: HttpServerRequest.HttpServerRequest;
227 readonly authorization: AuthorizationRequest;
228 readonly decision: ApprovalDecision;
229 }) => Effect.Effect<string, EnvironmentAuth.ServerAuthMcpApprovalCodeError | McpOAuthPageError>;
230 readonly deny: (authorization: AuthorizationRequest) => string;
231 /** A managed policy's runtime-mode ceiling, shown on the approval page. */
232 readonly runtimeModeCeiling:
233 | { readonly organization: string; readonly maxRuntimeMode: RuntimeMode }
234 | undefined;
235 readonly exchangeCode: (input: {
236 readonly request: HttpServerRequest.HttpServerRequest;
237 readonly urls: McpOAuthUrls;
238 readonly token: AuthMcpTokenRequest;
239 }) => Effect.Effect<AuthMcpTokenResult, AuthMcpTokenError>;
240 }
241>()("t3/auth/McpOAuth") {}
242
243const redirectWith = (
244 redirectUri: string,
245 params: Record<string, string | Redacted.Redacted<string> | undefined>,
246) => {
247 const url = new URL(redirectUri);
248 for (const [name, value] of Object.entries(params)) {
249 if (value !== undefined) {
250 url.searchParams.set(name, Redacted.isRedacted(value) ? Redacted.value(value) : value);
251 }
252 }
253 return url.toString();
254};
255
256export const redirectForError = (error: McpOAuthRedirectError, issuer: string) =>
257 redirectWith(error.redirectUri, {
258 error: error.error,
259 error_description: error.description,
260 state: error.state,
261 iss: issuer,
262 });
263
264const make = Effect.gen(function* () {
265 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
266 const secretStore = yield* ServerSecretStore.ServerSecretStore;
267 const random = yield* SecureRandom.SecureRandom;
268 const digester = yield* Digest.Digest;
269 const serverSettings = yield* ServerSettings.ServerSettingsService;
270 const linksEnabled = serverSettings.getSettings.pipe(
271 Effect.map((settings) => settings.linkedEnvironmentsEnabled),
272 Effect.orElseSucceed(() => false),
273 );
274 const signer = yield* PayloadSigner.fromSecret(
275 yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(Effect.orDie),
276 );
277 const codes = yield* Ref.make<ReadonlyMap<string, PendingCode>>(new Map());
278
279 const sign = (domain: string, payload: string) => signer.sign(`${domain}.${payload}`);
280
281 const signClientId = (name: string, redirectUris: ReadonlyArray<string>, peerLink: boolean) => {
282 const body = base64UrlEncode(
283 JSON.stringify({ v: 1, n: name, r: redirectUris, ...(peerLink ? { p: 1 } : {}) }),
284 );
285 return sign("mcp-client-id", body).pipe(Effect.map((signature) => `${body}.${signature}`));
286 };
287
288 // Untraced: only called inside the traced McpOAuth methods below.
289 const parseClientId = Effect.fnUntraced(function* (
290 clientId: string,
291 ): Effect.fn.Return<McpOAuthClient | undefined> {
292 const [body, signature, extra] = clientId.split(".");
293 if (!body || !signature || extra !== undefined) return undefined;
294 const verified = yield* signer.verify(`mcp-client-id.${body}`, signature);
295 if (!verified) return undefined;
296 const json = Option.liftThrowable(base64UrlDecodeUtf8)(body);
297 if (Option.isNone(json)) return undefined;
298 return Option.getOrUndefined(
299 decodeClientIdPayload(json.value).pipe(
300 Option.map((payload) => ({
301 clientId,
302 name: payload.n,
303 redirectUris: payload.r,
304 peerLink: payload.p === 1,
305 })),
306 ),
307 );
308 });
309
310 const pkceVerifies = (verifier: string, challenge: string) =>
311 CODE_VERIFIER_PATTERN.test(verifier)
312 ? digester.digest(Digest.sha256, new TextEncoder().encode(verifier)).pipe(
313 Effect.orDie,
314 Effect.map((digest) => timingSafeEqualBase64Url(base64UrlEncode(digest), challenge)),
315 )
316 : Effect.succeed(false);
317
318 const csrfToken = (holder: string, authorization: AuthorizationRequest) =>
319 sign(
320 "mcp-csrf",
321 JSON.stringify([
322 holder,
323 authorization.client.clientId,
324 authorization.redirectUri,
325 authorization.codeChallenge,
326 ]),
327 );
328
329 const register: McpOAuth["Service"]["register"] = Effect.fn("McpOAuth.register")(
330 function* (metadata) {
331 const rawName = metadata.client_name?.trim() ?? "";
332 const name = (rawName.length > 0 ? rawName : DEFAULT_CLIENT_NAME).slice(
333 0,
334 MAX_CLIENT_NAME_LENGTH,
335 );
336 const redirectUris = metadata.redirect_uris ?? [];
337 if (redirectUris.length === 0 || redirectUris.length > MAX_REDIRECT_URIS) {
338 return yield* new AuthMcpRegistrationError({
339 error: "invalid_redirect_uri",
340 error_description: `Register between 1 and ${MAX_REDIRECT_URIS} redirect URIs.`,
341 });
342 }
343 if (!redirectUris.every((uri) => parseRedirect(uri) !== undefined)) {
344 return yield* new AuthMcpRegistrationError({
345 error: "invalid_redirect_uri",
346 error_description:
347 "Redirect URIs must be https, or http on localhost, 127.0.0.1 or [::1].",
348 });
349 }
350 // RFC 7591 allows ignoring unsupported registration options; all clients use public PKCE.
351 const peerLink = metadata.software_id === MCP_PEER_LINK_SOFTWARE_ID;
352 if (peerLink && !(yield* linksEnabled)) {
353 return yield* new AuthMcpRegistrationError({
354 error: "invalid_client_metadata",
355 error_description:
356 'Linked environments is off on that machine. Turn it on in its Settings → Labs, or without a desktop, set "linkedEnvironmentsEnabled": true in userdata/settings.json in its T3 home (~/.t3 by default).',
357 });
358 }
359 const clientId = yield* signClientId(name, redirectUris, peerLink);
360 if (
361 redirectUris.length > MAX_UNBOUNDED_CLIENT_ID_REDIRECT_URIS &&
362 clientId.length > MAX_CLIENT_ID_LENGTH
363 ) {
364 return yield* new AuthMcpRegistrationError({
365 error: "invalid_redirect_uri",
366 error_description: "Redirect URIs are too long to fit in an authorization request.",
367 });
368 }
369 return {
370 clientId,
371 name,
372 redirectUris,
373 peerLink,
374 };
375 },
376 );
377
378 const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = Effect.fn(
379 "McpOAuth.validateAuthorization",
380 )(function* ({ urls, request }) {
381 const client = yield* parseClientId(request.client_id ?? "");
382 if (client === undefined) {
383 return yield* new McpOAuthPageError({
384 description: "This sign-in link names an unknown app. Start the sign-in again from it.",
385 });
386 }
387 const redirectUri = request.redirect_uri;
388 if (
389 redirectUri === undefined ||
390 !client.redirectUris.some((registered) => redirectMatches(registered, redirectUri))
391 ) {
392 return yield* new McpOAuthPageError({
393 description: "This sign-in link sends you to an address the app did not register.",
394 });
395 }
396 const state = request.state;
397 const fail = (error: McpOAuthRedirectError["error"], description: string) =>
398 new McpOAuthRedirectError({
399 error,
400 description,
401 redirectUri,
402 ...(state === undefined ? {} : { state }),
403 });
404 if (request.response_type !== "code") {
405 return yield* fail("unsupported_response_type", "Only response_type=code is supported.");
406 }
407 const codeChallenge = request.code_challenge;
408 if (
409 request.code_challenge_method !== "S256" ||
410 codeChallenge === undefined ||
411 !CODE_CHALLENGE_PATTERN.test(codeChallenge)
412 ) {
413 return yield* fail("invalid_request", "PKCE with code_challenge_method=S256 is required.");
414 }
415 if (!sameResource(urls, request.resource)) {
416 return yield* fail("invalid_target", `This server only issues tokens for ${urls.resource}.`);
417 }
418 return {
419 client,
420 redirectUri,
421 codeChallenge,
422 state,
423 resource: urls.resource,
424 issuer: urls.issuer,
425 } satisfies AuthorizationRequest;
426 });
427
428 const approvingSession: McpOAuth["Service"]["approvingSession"] = (request, authorization) =>
429 environmentAuth.authenticateHttpRequest(request).pipe(
430 Effect.flatMap((session) =>
431 // Approving manages access, and a session may only hand out scopes it holds.
432 session.scopes.includes(AuthAccessWriteScope) &&
433 session.scopes.includes(AuthOrchestrationReadScope)
434 ? // The hosted app may get a fresh credential per call, all bound to one browser key.
435 csrfToken(
436 session.proofKeyThumbprint === undefined
437 ? session.sessionId
438 : `dpop:${session.proofKeyThumbprint}`,
439 authorization,
440 ).pipe(Effect.map((token) => ({ csrfToken: token, scopes: session.scopes })))
441 : Effect.undefined,
442 ),
443 Effect.orElseSucceed(() => undefined),
444 );
445
446 const mintCode = Effect.fn("McpOAuth.mintCode")(function* (
447 authorization: AuthorizationRequest,
448 access: AuthMcpClientAccess,
449 approvedAtRevocationCount: number,
450 ) {
451 const now = yield* Clock.currentTimeMillis;
452 const code = Buffer.from(yield* random.randomBytes(32)).toString("base64url");
453 yield* Ref.update(codes, (current) => {
454 const next = new Map(Array.from(current).filter(([, pending]) => pending.expiresAtMs > now));
455 next.set(code, {
456 clientId: authorization.client.clientId,
457 clientName: authorization.client.name,
458 peerLink: authorization.client.peerLink,
459 redirectUri: authorization.redirectUri,
460 codeChallenge: authorization.codeChallenge,
461 resource: authorization.resource,
462 access,
463 approvedAtRevocationCount,
464 expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS,
465 });
466 return next;
467 });
468 return code;
469 });
470
471 const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) {
472 const { decision } = input;
473 // Read before the approver is checked: "revoke all others" then ends this sign-in whether
474 // it lands before the check or after the code is handed out.
475 const approvedAtRevocationCount = yield* environmentAuth.otherSessionRevocationCount;
476 let access = decision.access;
477 if (decision._tag === "pairing-code") {
478 // An approval code is for one app's sign-in, never for linking another environment.
479 if (input.authorization.client.peerLink && parseMcpApprovalCode(decision.code)) {
480 return yield* new McpOAuthPageError({
481 description: "Linking needs a plain pairing code, not an app approval code.",
482 });
483 }
484 access = yield* environmentAuth
485 .consumeMcpApprovalCode(decision.code, decision.access, input.authorization.client.peerLink)
486 .pipe(
487 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
488 Effect.logError("MCP approval code check failed.", { cause }).pipe(
489 Effect.andThen(
490 Effect.fail(
491 new McpOAuthPageError({
492 description: "The code could not be checked. Try again.",
493 }),
494 ),
495 ),
496 ),
497 ),
498 );
499 } else {
500 const session = yield* approvingSession(input.request, input.authorization);
501 if (
502 session === undefined ||
503 !timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) ||
504 !mcpClientScopes(decision.access).every((scope) => session.scopes.includes(scope))
505 ) {
506 return yield* new McpOAuthPageError({
507 description: "Your session cannot approve this request. Enter a pairing code instead.",
508 });
509 }
510 }
511 const code = yield* mintCode(input.authorization, access, approvedAtRevocationCount);
512 yield* Effect.logInfo("Approved an MCP client sign-in.", {
513 client: input.authorization.client.name,
514 access,
515 method: decision._tag,
516 });
517 return redirectWith(input.authorization.redirectUri, {
518 code,
519 state: input.authorization.state,
520 iss: input.authorization.issuer,
521 });
522 });
523
524 const deny: McpOAuth["Service"]["deny"] = (authorization) =>
525 redirectWith(authorization.redirectUri, {
526 error: "access_denied",
527 state: authorization.state,
528 iss: authorization.issuer,
529 });
530
531 const exchangeCode: McpOAuth["Service"]["exchangeCode"] = Effect.fn("McpOAuth.exchangeCode")(
532 function* ({ request, urls, token }) {
533 const fail = (error: AuthMcpTokenError["error"], description: string) =>
534 new AuthMcpTokenError({ error, error_description: description });
535 if (token.grant_type !== "authorization_code") {
536 return yield* fail("unsupported_grant_type", "Only authorization_code is supported.");
537 }
538 const { redirect_uri: redirectUri, client_id: clientId } = token;
539 const code = token.code && Redacted.value(token.code);
540 const verifier = token.code_verifier && Redacted.value(token.code_verifier);
541 if (!code || !redirectUri || !clientId || !verifier) {
542 return yield* fail(
543 "invalid_request",
544 "code, redirect_uri, client_id and code_verifier are required.",
545 );
546 }
547 if ((yield* parseClientId(clientId)) === undefined) {
548 return yield* fail("invalid_client", "The client is unknown.");
549 }
550 // A presented code is spent even when a later check fails (RFC 6749 §4.1.2).
551 const pending = yield* Ref.modify(codes, (current) => {
552 const found = current.get(code);
553 if (found === undefined) return [undefined, current] as const;
554 const next = new Map(current);
555 next.delete(code);
556 return [found, next] as const;
557 });
558 const now = yield* Clock.currentTimeMillis;
559 if (
560 pending === undefined ||
561 pending.expiresAtMs <= now ||
562 pending.clientId !== clientId ||
563 pending.redirectUri !== redirectUri ||
564 pending.resource !== urls.resource ||
565 !sameResource(urls, token.resource) ||
566 !(yield* pkceVerifies(verifier, pending.codeChallenge))
567 ) {
568 return yield* fail("invalid_grant", "The authorization code is invalid or expired.");
569 }
570 const issued = yield* environmentAuth
571 .issueMcpClientSession({
572 label: pending.clientName,
573 access: pending.access,
574 peerLink: pending.peerLink,
575 client: deriveAuthClientMetadata({ request }),
576 approvedAtRevocationCount: pending.approvedAtRevocationCount,
577 })
578 .pipe(
579 Effect.catch((cause) =>
580 cause._tag === "ServerAuthInvalidCredentialError"
581 ? Effect.fail(fail("invalid_grant", "The authorization code is invalid or expired."))
582 : Effect.logError("Could not issue an MCP client session.", { cause }).pipe(
583 Effect.andThen(
584 Effect.fail(fail("invalid_grant", "The session could not be issued.")),
585 ),
586 ),
587 ),
588 );
589 return {
590 access_token: issued.token,
591 token_type: "Bearer",
592 expires_in: Math.max(0, Math.floor((issued.expiresAt.epochMilliseconds - now) / 1000)),
593 scope: encodeOAuthScope(mcpClientScopes(pending.access)),
594 };
595 },
596 );
597
598 const managedPolicy = serverSettings.managedPolicy;
599 const maxRuntimeMode = managedPolicy?.limits?.maxRuntimeMode;
600 return McpOAuth.of({
601 runtimeModeCeiling:
602 managedPolicy === undefined || maxRuntimeMode === undefined
603 ? undefined
604 : { organization: managedPolicy.organization, maxRuntimeMode },
605 register,
606 validateAuthorization,
607 approvingSession,
608 approve,
609 deny,
610 exchangeCode,
611 });
612});
613
614export const layer = Layer.effect(McpOAuth, make);
615
616export const layerMcpClientAuthenticator = Layer.effect(
617 McpHttpServer.McpClientAuthenticator,
618 Effect.gen(function* () {
619 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
620 const environment = yield* ServerEnvironment.ServerEnvironment;
621 const environmentId = yield* environment.getEnvironmentId;
622 const hostedAppUrl = yield* hostedAppUrlConfig.pipe(
623 Effect.catch((cause) =>
624 Effect.logWarning("Outside MCP clients get app.t3.codes thread links", { cause }).pipe(
625 Effect.as(DEFAULT_HOSTED_APP_URL),
626 ),
627 ),
628 );
629 return McpHttpServer.McpClientAuthenticator.of({
630 authenticate: Effect.fn("McpHttpServer.McpClientAuthenticator.authenticate")(
631 function (request) {
632 return environmentAuth.authenticateMcpClient(request).pipe(
633 Effect.flatMap((client) =>
634 Clock.currentTimeMillis.pipe(
635 Effect.map((issuedAt): McpInvocationContext.McpInvocationScope => ({
636 environmentId,
637 requestNamespace: `client:${client.sessionId}`,
638 thread: undefined,
639 client: {
640 sessionId: client.sessionId,
641 label: client.label,
642 access: client.access,
643 linked: client.peerLink,
644 linkExpiresAt: client.linkExpiresAt,
645 ...(client.peerLink ? {} : { hostedAppUrl }),
646 },
647 capabilities: new Set<McpInvocationContext.McpCapability>([
648 "orchestration",
649 "worktree",
650 "pull-requests",
651 ]),
652 issuedAt,
653 })),
654 ),
655 ),
656 Effect.catch((error) =>
657 (EnvironmentAuth.isServerAuthCredentialError(error)
658 ? Effect.void
659 : Effect.logWarning("MCP client authentication failed.", { cause: error })
660 ).pipe(Effect.as(undefined)),
661 ),
662 );
663 },
664 ),
665 });
666 }),
667);