feat(server): outside agents sign in to the T3 MCP server with OAuth (#16336)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-06 14:09:35 -07:00
1 parent 2f85686d9d
commit 2c8be5893e
29 files changed
+2531 -67

No files matched your search

+161 -2
View File
@@ -2,6 +2,8 @@ import {
AuthAccessTokenType,
AuthAccessWriteScope,
AuthAdministrativeScopes,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
AuthStandardClientScopes,
type AuthAccessTokenResult,
type AuthBrowserSessionResult,
@@ -9,6 +11,7 @@ import {
type AuthClientSession,
type AuthCreatePairingCredentialInput,
type AuthEnvironmentScope,
type AuthMcpClientAccess,
type AuthPairingLink,
type AuthPairingCredentialResult,
type AuthSessionId,
@@ -63,6 +66,31 @@ export interface IssuedBearerSession {
readonly expiresAt: DateTime.Utc;
}
/**
* Sessions an MCP client (an agent T3 Code did not launch) obtains through
* OAuth. They are accepted only by `/mcp`, where every action is capped by the
* access the user approved; the HTTP API and WebSocket reject them so an agent
* token cannot reach the full RPC surface around that cap.
*
* A read-only grant holds `orchestration:read` alone. Any other grant also
* holds `orchestration:operate` and carries its runtime-mode ceiling.
*/
const MCP_CLIENT_SUBJECT = "mcp-client";
const MCP_CLIENT_SESSION_TTL = Duration.days(30);
export const mcpClientScopes = (
access: AuthMcpClientAccess,
): ReadonlyArray<AuthEnvironmentScope> =>
access === "read-only"
? [AuthOrchestrationReadScope]
: [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
export interface McpClientSession {
readonly sessionId: AuthSessionId;
readonly label: string;
readonly access: AuthMcpClientAccess;
}
export interface AuthenticatedSession {
readonly sessionId: AuthSessionId;
readonly subject: string;
@@ -406,6 +434,19 @@ export const serverAuthInvalidRequestReason = (
): "invalid_scope" | "scope_not_granted" =>
error._tag === "ServerAuthInvalidScopeError" ? "invalid_scope" : "scope_not_granted";
export class ServerAuthMcpApprovalCodeError extends Schema.TaggedError<ServerAuthMcpApprovalCodeError>()(
"ServerAuthMcpApprovalCodeError",
{ reason: Schema.Literals(["unknown_or_used", "not_a_pairing_code", "insufficient_scope"]) },
) {
override get message(): string {
return this.reason === "insufficient_scope"
? "That pairing code cannot grant this access, and it is now used up. Create one with the standard scopes, or choose Read only with a new code."
: this.reason === "not_a_pairing_code"
? "That is not a one-time pairing code."
: "That pairing code is unknown, expired, or already used.";
}
}
export class ServerAuthForbiddenOperationError extends Schema.TaggedError<ServerAuthForbiddenOperationError>()(
"ServerAuthForbiddenOperationError",
{},
@@ -502,6 +543,32 @@ export class EnvironmentAuth extends Context.Service<
readonly issueStartupPairingUrl: (
baseUrl: string,
) => Effect.Effect<string, ServerAuthInternalError>;
/** Only bearer `mcp-client` sessions; never cookies or proof-bound tokens. */
readonly authenticateMcpClient: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<McpClientSession, ServerAuthCredentialError | ServerAuthInternalError>;
readonly issueMcpClientSession: (input: {
readonly label: string;
readonly access: AuthMcpClientAccess;
readonly client: AuthClientMetadata;
}) => Effect.Effect<
{ readonly token: string; readonly expiresAt: DateTime.DateTime },
ServerAuthInternalError
>;
/**
* Spends a one-time pairing code as approval for an MCP client with the
* given access; the code must hold every scope that access grants.
* Proof-bound codes (T3 Connect) are refused without being spent, and
* desktop bootstrap grants never qualify.
*/
readonly consumeMcpApprovalCode: (
code: string,
access: AuthMcpClientAccess,
) => Effect.Effect<void, ServerAuthMcpApprovalCodeError | ServerAuthInternalError>;
/** A browser cookie session only; a bearer header never counts as one. */
readonly authenticateBrowserSession: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
}
>()("t3/auth/EnvironmentAuth") {}
@@ -540,6 +607,15 @@ export function toBootstrapExchangeError(
});
}
const rejectMcpClientAudience = <S extends { readonly subject: string }>(session: S) =>
session.subject === MCP_CLIENT_SUBJECT
? Effect.fail(
new ServerAuthInvalidCredentialError({
diagnostic: "MCP client sessions are only accepted by the MCP endpoint.",
}),
).pipe(Effect.tap(() => Effect.logWarning("Rejected an MCP client session outside /mcp.")))
: Effect.succeed(session);
const mapSessionVerificationErrors = <A, R>(
effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
@@ -624,6 +700,8 @@ export const make = Effect.gen(function* () {
)
: Effect.void,
),
mapSessionVerificationErrors,
Effect.flatMap(rejectMcpClientAudience),
Effect.map((session) => ({
sessionId: session.sessionId,
subject: session.subject,
@@ -632,7 +710,6 @@ export const make = Effect.gen(function* () {
...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
})),
mapSessionVerificationErrors,
);
const authenticateRequest = (
@@ -1079,6 +1156,8 @@ export const make = Effect.gen(function* () {
const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);
if (websocketTicket && websocketTicket.trim().length > 0) {
return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(
mapSessionVerificationErrors,
Effect.flatMap(rejectMcpClientAudience),
Effect.map((session) => ({
sessionId: session.sessionId,
subject: session.subject,
@@ -1086,7 +1165,6 @@ export const make = Effect.gen(function* () {
scopes: session.scopes,
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
})),
mapSessionVerificationErrors,
);
}
}
@@ -1094,6 +1172,83 @@ export const make = Effect.gen(function* () {
return yield* authenticateRequest(request);
});
const authenticateMcpClient: EnvironmentAuth["Service"]["authenticateMcpClient"] = (request) => {
const token = parseBearerToken(request);
if (token === null) return Effect.fail(new ServerAuthMissingCredentialError({}));
return sessions.verify(token).pipe(
mapSessionVerificationErrors,
Effect.flatMap((session) =>
session.subject === MCP_CLIENT_SUBJECT && session.method === "bearer-access-token"
? Effect.succeed({
sessionId: session.sessionId,
label: session.client.label ?? "MCP client",
access: session.scopes.includes(AuthOrchestrationOperateScope)
? (session.runtimeModeCeiling ?? "approval-required")
: "read-only",
} satisfies McpClientSession)
: Effect.fail(
new ServerAuthInvalidCredentialError({
diagnostic: "Only MCP client sessions are accepted here.",
}),
),
),
Effect.withSpan("EnvironmentAuth.authenticateMcpClient"),
);
};
const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) =>
sessions
.issue({
subject: MCP_CLIENT_SUBJECT,
method: "bearer-access-token",
scopes: mcpClientScopes(input.access),
ttl: MCP_CLIENT_SESSION_TTL,
...(input.access === "read-only" ? {} : { runtimeModeCeiling: input.access }),
client: { ...input.client, label: input.label, deviceType: "bot" },
})
.pipe(
Effect.map((issued) => ({ token: issued.token, expiresAt: issued.expiresAt })),
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
Effect.withSpan("EnvironmentAuth.issueMcpClientSession"),
);
const authenticateBrowserSession: EnvironmentAuth["Service"]["authenticateBrowserSession"] = (
request,
) => {
const token =
request.cookies[sessions.cookieName] ??
(sessions.legacyCookieName ? request.cookies[sessions.legacyCookieName] : undefined) ??
(devAuth ? request.cookies[devAuth.cookieName] : undefined);
if (!token) return Effect.fail(new ServerAuthMissingCredentialError({}));
return authenticateToken(token).pipe(
Effect.filterOrFail(
(session) => session.method === "browser-session-cookie" && !session.proofKeyThumbprint,
() => new ServerAuthInvalidCredentialError({ diagnostic: "Not a browser session." }),
),
Effect.withSpan("EnvironmentAuth.authenticateBrowserSession"),
);
};
const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (
code,
access,
) =>
// No proof key: a code bound to a T3 Connect client's key fails without being spent.
resolveBootstrapGrant(code.trim()).pipe(
Effect.catchTags({
ServerAuthInvalidCredentialError: () =>
Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
}),
Effect.flatMap((grant) =>
grant.method !== "one-time-token" && grant.method !== "reusable-dev-token"
? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" }))
: mcpClientScopes(access).every((scope) => grant.scopes.includes(scope))
? Effect.void
: Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),
),
Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"),
);
return EnvironmentAuth.of({
getDescriptor: () =>
Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuth.getDescriptor")),
@@ -1116,6 +1271,10 @@ export const make = Effect.gen(function* () {
authenticateWebSocketUpgrade,
issueWebSocketTicket,
issueStartupPairingUrl,
authenticateMcpClient,
issueMcpClientSession,
consumeMcpApprovalCode,
authenticateBrowserSession,
});
});