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,
});
});
+505
View File
@@ -0,0 +1,505 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
AuthAdministrativeScopes,
type AuthEnvironmentScope,
EnvironmentHttpApi,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Etag from "effect/http/Etag";
import * as HttpPlatform from "effect/http/HttpPlatform";
import * as HttpRouter from "effect/http/HttpRouter";
import * as HttpServerRequest from "effect/http/HttpServerRequest";
import * as HttpApi from "effect/http-api/HttpApi";
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
import * as Schema from "effect/Schema";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as Sqlite from "../persistence/Sqlite.ts";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import * as McpOAuth from "./McpOAuth.ts";
import * as McpOAuthHttp from "./mcpOAuthHttp.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import * as AuthHttp from "./http.ts";
class AuthTestApi extends HttpApi.make("environment")
.add(EnvironmentHttpApi.groups.auth)
.add(EnvironmentHttpApi.groups.mcpOAuth) {}
const layerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-oauth-test-" });
const layerEnvironmentAuth = EnvironmentAuth.layer.pipe(
Layer.provide(Sqlite.layerMemory),
Layer.provideMerge(ServerSecretStore.layer),
Layer.provideMerge(ServerEnvironment.layerIdentity),
Layer.provide(layerConfig),
);
// Each router gets its own database; the capture hands that router's EnvironmentAuth to its test.
const makeLayerRoutes = (capture: (auth: EnvironmentAuth.EnvironmentAuth["Service"]) => void) =>
Layer.mergeAll(
Layer.effectDiscard(
EnvironmentAuth.EnvironmentAuth.pipe(Effect.tap((auth) => Effect.sync(() => capture(auth)))),
),
HttpApiBuilder.layer(AuthTestApi).pipe(
Layer.provide(AuthHttp.layer),
Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))),
Layer.provide(AuthHttp.layerAuthenticatedAuth),
),
).pipe(
Layer.provideMerge(layerEnvironmentAuth),
Layer.provide(layerConfig),
Layer.provideMerge(
HttpPlatform.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(Etag.layerWeak),
),
),
Layer.provide(NodeServices.layer),
);
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
const ORIGIN = "https://box.example.ts.net";
const REDIRECT = "http://localhost/callback";
const verifier = "a".repeat(43) + "-verifier-for-tests";
/** base64url(SHA-256(verifier)), the S256 challenge for `verifier`. */
const challenge = "DeB41nTVkPwpbbYecrnqtVq7VXLezustdHAK4SWt13c";
/** Requests as they arrive behind an https proxy: plain http with the public Host. */
const at = (path: string, init?: RequestInit) =>
new Request(`http://127.0.0.1${path}`, {
...init,
headers: { host: "box.example.ts.net", "x-forwarded-proto": "https", ...init?.headers },
});
const form = (body: Record<string, string>) => ({
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(body).toString(),
});
type Handler = (request: Request) => Effect.Effect<Response>;
const withRoutes = <A, E>(
use: (handler: Handler, auth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>,
) =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const context = Context.make(Crypto.Crypto, crypto);
let routerAuth: EnvironmentAuth.EnvironmentAuth["Service"] | undefined;
const layerRoutes = makeLayerRoutes((auth) => {
routerAuth = auth;
});
return yield* Effect.acquireUseRelease(
Effect.sync(() => HttpRouter.toWebHandler(layerRoutes, { disableLogger: true })),
(web) =>
Effect.gen(function* () {
const handler: Handler = (request) => Effect.promise(() => web.handler(request, context));
// The router builds its layer on first request; a metadata read warms it.
yield* handler(at("/.well-known/oauth-authorization-server"));
return yield* use(handler, routerAuth!);
}),
(web) => Effect.promise(() => web.dispose()),
);
}).pipe(Effect.provide(NodeServices.layer));
const json = <A>(response: Response) => Effect.promise(() => response.json() as Promise<A>);
const postJson = (path: string, body: unknown, cookie?: string) =>
at(path, {
method: "POST",
headers: { "content-type": "application/json", ...(cookie ? { cookie } : {}) },
body: encodeJson(body),
});
/** What the approval page posts: the agent's request plus the user's choice. */
const decide = (
handler: Handler,
authorization: Record<string, string>,
decision: Record<string, string>,
cookie?: string,
) =>
handler(postJson("/oauth/mcp/decision", { authorization, decision }, cookie)).pipe(
Effect.flatMap((response) =>
json<{ redirectTo?: string; message?: string }>(response).pipe(
Effect.map((payload) => ({ status: response.status, ...payload })),
),
),
);
const register = (handler: Handler, redirect = REDIRECT) =>
handler(
at("/oauth/mcp/register", {
method: "POST",
headers: { "content-type": "application/json" },
body: encodeJson({
client_name: "Claude Code",
redirect_uris: [redirect],
grant_types: ["authorization_code", "refresh_token"],
token_endpoint_auth_method: "none",
}),
}),
);
const registeredClientId = (handler: Handler) =>
register(handler).pipe(
Effect.flatMap((response) => json<{ client_id: string }>(response)),
Effect.map((body) => body.client_id),
);
const authorizeParams = (clientId: string, redirect = "http://localhost:51234/callback") => ({
response_type: "code",
client_id: clientId,
redirect_uri: redirect,
code_challenge: challenge,
code_challenge_method: "S256",
state: "state-1",
resource: `${ORIGIN}/mcp`,
});
it.live("derives discovery metadata from the origin the client reached", () =>
withRoutes((handler) =>
Effect.gen(function* () {
const resource = yield* handler(at("/.well-known/oauth-protected-resource/mcp"));
expect(yield* json<unknown>(resource)).toMatchObject({
resource: `${ORIGIN}/mcp`,
authorization_servers: [ORIGIN],
});
const server = yield* json<unknown>(
yield* handler(at("/.well-known/oauth-authorization-server")),
);
expect(server).toMatchObject({
issuer: ORIGIN,
authorization_endpoint: `${ORIGIN}/oauth/mcp/authorize`,
token_endpoint: `${ORIGIN}/oauth/mcp/token`,
registration_endpoint: `${ORIGIN}/oauth/mcp/register`,
code_challenge_methods_supported: ["S256"],
});
}),
),
);
it.live("registers only loopback 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" });
const registered = yield* register(handler);
expect(registered.status).toBe(201);
const { client_id: clientId } = (yield* json<unknown>(registered)) as { client_id: string };
const forged = yield* handler(
at(
`/oauth/mcp/authorize?${new URLSearchParams(authorizeParams(`${clientId.split(".")[0]}.forged`))}`,
),
);
expect(forged.status).toBe(400);
expect(forged.headers.get("location")).toBeNull();
const unregistered = yield* handler(
at(
`/oauth/mcp/authorize?${new URLSearchParams(
authorizeParams(clientId, "http://localhost:51234/elsewhere"),
)}`,
),
);
expect(unregistered.status).toBe(400);
expect(unregistered.headers.get("location")).toBeNull();
// A valid request is handed to the web app's approval page, query intact.
const query = new URLSearchParams(authorizeParams(clientId)).toString();
const handoff = yield* handler(at(`/oauth/mcp/authorize?${query}`));
expect(handoff.status).toBe(302);
expect(handoff.headers.get("location")).toBe(`/connect-agent?${query}`);
const details = yield* handler(
postJson("/oauth/mcp/approval", authorizeParams(clientId)),
).pipe(Effect.flatMap(json<Record<string, unknown>>));
expect(details).toEqual({
clientName: "Claude Code",
redirectHost: "localhost:51234",
environmentHost: "box.example.ts.net",
});
// The approval endpoints re-check the request: a forged client gets a message, not a URL.
const forgedDetails = yield* handler(
postJson("/oauth/mcp/approval", authorizeParams(`${clientId.split(".")[0]}.forged`)),
);
expect(forgedDetails.status).toBe(400);
expect(yield* json<Record<string, unknown>>(forgedDetails)).not.toHaveProperty("redirectTo");
}),
),
);
it.live("signs in with a pairing code and issues a token only /mcp accepts", () =>
withRoutes((handler, auth) =>
Effect.gen(function* () {
const clientId = yield* registeredClientId(handler);
const pairing = yield* auth.issuePairingCredential();
const params = authorizeParams(clientId);
const wrongCode = yield* decide(handler, params, {
_tag: "pairing-code",
access: "auto",
code: "nope",
});
expect(wrongCode.status).toBe(400);
expect(wrongCode.message).toContain("unknown, expired, or already used");
const approved = yield* decide(handler, params, {
_tag: "pairing-code",
access: "auto",
code: pairing.credential,
});
expect(approved.status).toBe(200);
const callback = new URL(approved.redirectTo!);
expect(callback.origin).toBe("http://localhost:51234");
expect(callback.searchParams.get("state")).toBe("state-1");
expect(callback.searchParams.get("iss")).toBe(ORIGIN);
const code = callback.searchParams.get("code")!;
const exchange = (codeVerifier: string) =>
handler(
at(
"/oauth/mcp/token",
form({
grant_type: "authorization_code",
code,
redirect_uri: params.redirect_uri,
client_id: clientId,
code_verifier: codeVerifier,
resource: `${ORIGIN}/mcp`,
}),
),
);
const tokenResponse = yield* exchange(verifier);
expect(tokenResponse.status).toBe(200);
const token = (yield* json<unknown>(tokenResponse)) as {
access_token: string;
scope: string;
};
expect(token.scope).toBe("orchestration:read orchestration:operate");
// Codes are single use.
expect((yield* exchange(verifier)).status).toBe(400);
const client = yield* auth.authenticateMcpClient(
HttpServerRequest.fromWeb(
at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }),
),
);
expect(client).toMatchObject({ label: "Claude Code", access: "auto" });
// The same token is refused by the rest of the environment.
const session = yield* handler(
at("/api/auth/session", { headers: { authorization: `Bearer ${token.access_token}` } }),
);
expect(yield* json<unknown>(session)).toMatchObject({ authenticated: false });
const ticket = yield* handler(
at("/api/auth/websocket-ticket", {
method: "POST",
headers: { authorization: `Bearer ${token.access_token}` },
}),
);
expect(ticket.status).toBe(401);
}),
),
);
it.live("rejects a wrong PKCE verifier and spends the code", () =>
withRoutes((handler, auth) =>
Effect.gen(function* () {
const clientId = yield* registeredClientId(handler);
const pairing = yield* auth.issuePairingCredential();
const params = authorizeParams(clientId);
const approved = yield* decide(handler, params, {
_tag: "pairing-code",
access: "approval-required",
code: pairing.credential,
});
const code = new URL(approved.redirectTo!).searchParams.get("code")!;
const exchange = (codeVerifier: string) =>
handler(
at(
"/oauth/mcp/token",
form({
grant_type: "authorization_code",
code,
redirect_uri: params.redirect_uri,
client_id: clientId,
code_verifier: codeVerifier,
}),
),
);
const wrong = yield* exchange("b".repeat(64));
expect(wrong.status).toBe(400);
expect(yield* json<unknown>(wrong)).toMatchObject({ error: "invalid_grant" });
expect((yield* exchange(verifier)).status).toBe(400);
}),
),
);
it.live(
"denies and refuses codes bound to another client's key or without the scopes it grants",
() =>
withRoutes((handler, auth) =>
Effect.gen(function* () {
const clientId = yield* registeredClientId(handler);
const params = authorizeParams(clientId);
const denied = yield* decide(handler, params, { _tag: "deny" });
const deniedUrl = new URL(denied.redirectTo!);
expect(deniedUrl.searchParams.get("error")).toBe("access_denied");
expect(deniedUrl.searchParams.get("state")).toBe("state-1");
const approveWith = (code: string) =>
decide(handler, params, { _tag: "pairing-code", access: "auto", code });
// A T3 Connect code is bound to a device key: refused, and still usable by its device.
const bound = yield* auth.createPairingLink({
proofKeyThumbprint: "device-key-thumbprint",
});
expect((yield* approveWith(bound.credential)).status).toBe(400);
const stillValid = yield* auth
.exchangeBootstrapCredentialForAccessToken(
bound.credential,
undefined,
{ deviceType: "mobile" },
{ proofKeyThumbprint: "device-key-thumbprint" },
)
.pipe(
Effect.as(true),
Effect.orElseSucceed(() => false),
);
expect(stillValid).toBe(true);
const readOnly = yield* auth.issuePairingCredential({ scopes: ["orchestration:read"] });
const readOnlyResponse = yield* approveWith(readOnly.credential);
expect(readOnlyResponse.status).toBe(400);
expect(readOnlyResponse.message).toContain("cannot grant this access");
// A read-only code can approve read-only access.
const readOnlyCode = yield* auth.issuePairingCredential({ scopes: ["orchestration:read"] });
const readOnlyApproval = yield* decide(handler, params, {
_tag: "pairing-code",
access: "read-only",
code: readOnlyCode.credential,
});
expect(readOnlyApproval.status).toBe(200);
const readOnlyToken = yield* handler(
at(
"/oauth/mcp/token",
form({
grant_type: "authorization_code",
code: new URL(readOnlyApproval.redirectTo!).searchParams.get("code")!,
redirect_uri: params.redirect_uri,
client_id: clientId,
code_verifier: verifier,
resource: `${ORIGIN}/mcp`,
}),
),
).pipe(Effect.flatMap(json<{ access_token: string; scope: string }>));
expect(readOnlyToken.scope).toBe("orchestration:read");
const readOnlyClient = yield* auth.authenticateMcpClient(
HttpServerRequest.fromWeb(
at("/mcp", { headers: { authorization: `Bearer ${readOnlyToken.access_token}` } }),
),
);
expect(readOnlyClient.access).toBe("read-only");
}),
),
);
it.live("one-click approves only access the browser session holds the scopes for", () =>
withRoutes((handler, auth) =>
Effect.gen(function* () {
const clientId = yield* registeredClientId(handler);
const params = authorizeParams(clientId);
// Signs a browser in through the real route and returns its session cookie.
const browserCookie = (scopes: ReadonlyArray<AuthEnvironmentScope>) =>
Effect.gen(function* () {
const pairing = yield* auth.issuePairingCredential({ scopes });
const response = yield* handler(
at("/api/auth/browser-session", {
method: "POST",
headers: { "content-type": "application/json" },
body: encodeJson({ credential: pairing.credential }),
}),
);
return response.headers.getSetCookie()[0]!.split(";", 1)[0]!;
});
const details = (cookie: string) =>
handler(postJson("/oauth/mcp/approval", params, cookie)).pipe(
Effect.flatMap(json<{ csrfToken?: string; oneClickAccess?: ReadonlyArray<string> }>),
);
const admin = yield* browserCookie([...AuthAdministrativeScopes]);
const adminDetails = yield* details(admin);
expect(adminDetails.csrfToken).toEqual(expect.any(String));
expect(adminDetails.oneClickAccess).toEqual([
"read-only",
"approval-required",
"auto-accept-edits",
"auto",
"full-access",
]);
const oneClick = yield* decide(
handler,
params,
{ _tag: "browser-session", access: "auto", csrfToken: adminDetails.csrfToken! },
admin,
);
expect(new URL(oneClick.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
// access:write alone cannot hand an agent thread control it does not hold.
const accessOnly = yield* browserCookie(["access:read", "access:write"]);
expect((yield* details(accessOnly)).csrfToken).toBeUndefined();
const forged = yield* decide(
handler,
params,
{ _tag: "browser-session", access: "auto", csrfToken: "forged" },
accessOnly,
);
expect(forged.status).toBe(400);
expect(forged.message).toContain("Enter a pairing code instead");
// A session that can read but not operate threads may approve read-only access only.
const reader = yield* browserCookie(["access:write", "orchestration:read"]);
const readerDetails = yield* details(reader);
expect(readerDetails.csrfToken).toEqual(expect.any(String));
// The page shows the pairing-code field for anything above read only.
expect(readerDetails.oneClickAccess).toEqual(["read-only"]);
const tooBroad = yield* decide(
handler,
params,
{ _tag: "browser-session", access: "auto", csrfToken: readerDetails.csrfToken! },
reader,
);
expect(tooBroad.status).toBe(400);
const readOnly = yield* decide(
handler,
params,
{ _tag: "browser-session", access: "read-only", csrfToken: readerDetails.csrfToken! },
reader,
);
expect(new URL(readOnly.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
}),
),
);
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);
});
+603
View File
@@ -0,0 +1,603 @@
import {
AuthAccessWriteScope,
type AuthMcpApprovalDecision,
type AuthMcpAuthorizationRequest,
type AuthMcpAuthorizationServerMetadata,
type AuthMcpClientRegistration,
type AuthMcpProtectedResourceMetadata,
AuthMcpRegistrationError,
AuthMcpTokenError,
type AuthMcpTokenRequest,
type AuthMcpTokenResult,
type AuthMcpClientAccess,
type AuthEnvironmentScope,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
} from "@t3tools/contracts";
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import { HttpServerRequest } from "effect/http";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as McpHttpServer from "../mcp/McpHttpServer.ts";
import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import {
base64UrlDecodeUtf8,
base64UrlEncode,
deriveAuthClientMetadata,
signPayload,
timingSafeEqualBase64Url,
} from "./utils.ts";
/**
* The OAuth authorization server MCP clients (Claude Code, Codex, any agent
* T3 Code did not launch) use to sign in to this environment's `/mcp`.
*
* 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.
*/
const SIGNING_SECRET_NAME = "mcp-oauth-signing-key";
const AUTHORIZATION_CODE_TTL_MS = 60_000;
const MAX_CLIENT_NAME_LENGTH = 100;
const MAX_REDIRECT_URIS = 5;
const MAX_REDIRECT_URI_LENGTH = 512;
const DEFAULT_CLIENT_NAME = "MCP client";
const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
const CODE_VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/;
const MCP_OAUTH_SCOPES = [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
export interface McpOAuthUrls {
readonly issuer: string;
readonly resource: string;
}
/**
* Issuer and MCP resource for the origin this request reached: its Host, and
* https when a proxy says so. A Host that is not a valid authority falls back
* to localhost, which no client will have asked for.
*/
export const requestUrls = (request: HttpServerRequest.HttpServerRequest): McpOAuthUrls => {
const origin = Option.match(HttpServerRequest.toURL(request), {
onNone: () => "http://localhost",
onSome: (url) => url.origin,
});
return { issuer: origin, resource: `${origin}/mcp` };
};
export const protectedResourceMetadata = (
urls: McpOAuthUrls,
): AuthMcpProtectedResourceMetadata => ({
resource: urls.resource,
authorization_servers: [urls.issuer],
scopes_supported: MCP_OAUTH_SCOPES,
bearer_methods_supported: ["header"],
resource_name: "T3 Code",
});
export const authorizationServerMetadata = (
urls: McpOAuthUrls,
): AuthMcpAuthorizationServerMetadata => ({
issuer: urls.issuer,
authorization_endpoint: `${urls.issuer}/oauth/mcp/authorize`,
token_endpoint: `${urls.issuer}/oauth/mcp/token`,
registration_endpoint: `${urls.issuer}/oauth/mcp/register`,
response_types_supported: ["code"],
grant_types_supported: ["authorization_code"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
scopes_supported: MCP_OAUTH_SCOPES,
authorization_response_iss_parameter_supported: true,
});
const parseLoopbackRedirect = (value: string): URL | undefined => {
if (value.length > MAX_REDIRECT_URI_LENGTH) 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;
} 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);
return (
left !== undefined &&
right !== undefined &&
left.hostname === right.hostname &&
left.pathname === right.pathname &&
left.search === right.search
);
};
const sameResource = (urls: McpOAuthUrls, presented: string | undefined): boolean => {
if (presented === undefined) return true;
try {
const url = new URL(presented);
return url.hash === "" && `${url.origin}${url.pathname.replace(/\/+$/u, "")}` === urls.resource;
} catch {
return false;
}
};
const ClientIdPayload = Schema.Struct({
v: Schema.Literal(1),
n: Schema.String,
r: Schema.Array(Schema.String),
});
const decodeClientIdPayload = Schema.decodeUnknownOption(Schema.fromJsonString(ClientIdPayload));
export interface McpOAuthClient {
readonly clientId: string;
readonly name: string;
readonly redirectUris: ReadonlyArray<string>;
}
/** Problems the authorize page shows the user without redirecting anywhere. */
export class McpOAuthPageError extends Schema.TaggedError<McpOAuthPageError>()(
"McpOAuthPageError",
{ description: Schema.String },
) {
override get message(): string {
return this.description;
}
}
/** Problems reported back to the client through its (validated) redirect URI. */
export class McpOAuthRedirectError extends Schema.TaggedError<McpOAuthRedirectError>()(
"McpOAuthRedirectError",
{
error: Schema.Literals(["invalid_request", "unsupported_response_type", "invalid_target"]),
description: Schema.String,
redirectUri: Schema.String,
state: Schema.optional(Schema.String),
},
) {}
export interface AuthorizationRequest {
readonly client: McpOAuthClient;
readonly redirectUri: string;
readonly codeChallenge: string;
readonly state: string | undefined;
readonly resource: string;
readonly issuer: string;
}
interface PendingCode {
readonly clientId: string;
readonly clientName: string;
readonly redirectUri: string;
readonly codeChallenge: string;
readonly resource: string;
readonly access: AuthMcpClientAccess;
readonly expiresAtMs: number;
}
export type ApprovalDecision = Exclude<AuthMcpApprovalDecision, { readonly _tag: "deny" }>;
export class McpOAuth extends Context.Service<
McpOAuth,
{
readonly register: (
input: AuthMcpClientRegistration,
) => Effect.Effect<McpOAuthClient, AuthMcpRegistrationError>;
/** Validates an authorize request. Page errors must never redirect. */
readonly validateAuthorization: (input: {
readonly urls: McpOAuthUrls;
readonly request: AuthMcpAuthorizationRequest;
}) => Effect.Effect<AuthorizationRequest, McpOAuthPageError | McpOAuthRedirectError>;
/**
* The signed-in owner on this origin, when their browser session may
* approve at least read-only access. `approve` checks the chosen access
* against the session's scopes.
*/
readonly approvingBrowserSession: (
request: HttpServerRequest.HttpServerRequest,
authorization: AuthorizationRequest,
) => Effect.Effect<
| { readonly csrfToken: string; readonly scopes: ReadonlyArray<AuthEnvironmentScope> }
| undefined
>;
/** Approves and returns the URL to send the browser to. */
readonly approve: (input: {
readonly request: HttpServerRequest.HttpServerRequest;
readonly authorization: AuthorizationRequest;
readonly decision: ApprovalDecision;
}) => Effect.Effect<string, EnvironmentAuth.ServerAuthMcpApprovalCodeError | McpOAuthPageError>;
readonly deny: (authorization: AuthorizationRequest) => string;
readonly exchangeCode: (input: {
readonly request: HttpServerRequest.HttpServerRequest;
readonly urls: McpOAuthUrls;
readonly token: AuthMcpTokenRequest;
}) => Effect.Effect<AuthMcpTokenResult, AuthMcpTokenError>;
}
>()("t3/auth/McpOAuth") {}
/** Appends OAuth response parameters, keeping any the client put in its redirect URI. */
const redirectWith = (redirectUri: string, params: Record<string, string | undefined>) => {
const url = new URL(redirectUri);
for (const [name, value] of Object.entries(params)) {
if (value !== undefined) url.searchParams.set(name, value);
}
return url.toString();
};
export const redirectForError = (error: McpOAuthRedirectError, issuer: string) =>
redirectWith(error.redirectUri, {
error: error.error,
error_description: error.description,
state: error.state,
iss: issuer,
});
const make = Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const crypto = yield* Crypto.Crypto;
const signingKey = yield* secretStore
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
.pipe(Effect.orDie);
const codes = yield* Ref.make<ReadonlyMap<string, PendingCode>>(new Map());
const sign = (domain: string, payload: string) => signPayload(`${domain}.${payload}`, signingKey);
const signClientId = (name: string, redirectUris: ReadonlyArray<string>) => {
const body = base64UrlEncode(JSON.stringify({ v: 1, n: name, r: redirectUris }));
return `${body}.${sign("mcp-client-id", body)}`;
};
const parseClientId = (clientId: string): McpOAuthClient | undefined => {
const [body, signature, extra] = clientId.split(".");
if (!body || !signature || extra !== undefined) return undefined;
if (!timingSafeEqualBase64Url(signature, sign("mcp-client-id", body))) return undefined;
let json: string;
try {
json = base64UrlDecodeUtf8(body);
} catch {
return undefined;
}
return Option.getOrUndefined(
decodeClientIdPayload(json).pipe(
Option.map((payload) => ({ clientId, name: payload.n, redirectUris: payload.r })),
),
);
};
const pkceVerifies = (verifier: string, challenge: string) =>
CODE_VERIFIER_PATTERN.test(verifier)
? crypto.digest("SHA-256", new TextEncoder().encode(verifier)).pipe(
Effect.orDie,
Effect.map((digest) => timingSafeEqualBase64Url(base64UrlEncode(digest), challenge)),
)
: Effect.succeed(false);
const csrfToken = (sessionId: string, authorization: AuthorizationRequest) =>
sign(
"mcp-csrf",
JSON.stringify([
sessionId,
authorization.client.clientId,
authorization.redirectUri,
authorization.codeChallenge,
]),
);
const register: McpOAuth["Service"]["register"] = (metadata) =>
Effect.gen(function* () {
const rawName = metadata.client_name?.trim() ?? "";
const name = (rawName.length > 0 ? rawName : DEFAULT_CLIENT_NAME).slice(
0,
MAX_CLIENT_NAME_LENGTH,
);
const redirectUris = metadata.redirect_uris ?? [];
if (redirectUris.length === 0 || redirectUris.length > MAX_REDIRECT_URIS) {
return yield* new AuthMcpRegistrationError({
error: "invalid_redirect_uri",
error_description: `Register between 1 and ${MAX_REDIRECT_URIS} redirect URIs.`,
});
}
if (!redirectUris.every((uri) => parseLoopbackRedirect(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.",
});
}
// 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.
return { clientId: signClientId(name, redirectUris), name, redirectUris };
});
const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = ({ urls, request }) =>
Effect.gen(function* () {
const client = parseClientId(request.client_id ?? "");
if (client === undefined) {
return yield* new McpOAuthPageError({
description: "This sign-in link names an unknown app. Start the sign-in again from it.",
});
}
const redirectUri = request.redirect_uri;
if (
redirectUri === undefined ||
parseLoopbackRedirect(redirectUri) === undefined ||
!client.redirectUris.some((registered) => loopbackRedirectMatches(registered, redirectUri))
) {
return yield* new McpOAuthPageError({
description: "This sign-in link sends you to an address the app did not register.",
});
}
const state = request.state;
const fail = (error: McpOAuthRedirectError["error"], description: string) =>
new McpOAuthRedirectError({
error,
description,
redirectUri,
...(state === undefined ? {} : { state }),
});
if (request.response_type !== "code") {
return yield* fail("unsupported_response_type", "Only response_type=code is supported.");
}
const codeChallenge = request.code_challenge;
if (
request.code_challenge_method !== "S256" ||
codeChallenge === undefined ||
!CODE_CHALLENGE_PATTERN.test(codeChallenge)
) {
return yield* fail("invalid_request", "PKCE with code_challenge_method=S256 is required.");
}
if (!sameResource(urls, request.resource)) {
return yield* fail(
"invalid_target",
`This server only issues tokens for ${urls.resource}.`,
);
}
return {
client,
redirectUri,
codeChallenge,
state,
resource: urls.resource,
issuer: urls.issuer,
} satisfies AuthorizationRequest;
});
const approvingBrowserSession: McpOAuth["Service"]["approvingBrowserSession"] = (
request,
authorization,
) =>
environmentAuth.authenticateBrowserSession(request).pipe(
Effect.map((session) =>
// Approving manages access, and a session may only hand out scopes it holds.
session.scopes.includes(AuthAccessWriteScope) &&
session.scopes.includes(AuthOrchestrationReadScope)
? { csrfToken: csrfToken(session.sessionId, authorization), scopes: session.scopes }
: undefined,
),
Effect.orElseSucceed(() => undefined),
);
const mintCode = (authorization: AuthorizationRequest, access: AuthMcpClientAccess) =>
Effect.gen(function* () {
const now = yield* Clock.currentTimeMillis;
const code = Buffer.from(yield* crypto.randomBytes(32).pipe(Effect.orDie)).toString(
"base64url",
);
yield* Ref.update(codes, (current) => {
const next = new Map(
Array.from(current).filter(([, pending]) => pending.expiresAtMs > now),
);
next.set(code, {
clientId: authorization.client.clientId,
clientName: authorization.client.name,
redirectUri: authorization.redirectUri,
codeChallenge: authorization.codeChallenge,
resource: authorization.resource,
access,
expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS,
});
return next;
});
return code;
});
const approve: McpOAuth["Service"]["approve"] = (input) =>
Effect.gen(function* () {
const { decision } = input;
if (decision._tag === "pairing-code") {
yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
Effect.logError("MCP approval code check failed.", { cause }).pipe(
Effect.andThen(
Effect.fail(
new McpOAuthPageError({
description: "The code could not be checked. Try again.",
}),
),
),
),
),
);
} else {
const session = yield* approvingBrowserSession(input.request, input.authorization);
if (
session === undefined ||
!timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) ||
!EnvironmentAuth.mcpClientScopes(decision.access).every((scope) =>
session.scopes.includes(scope),
)
) {
return yield* new McpOAuthPageError({
description: "Your session cannot approve this request. Enter a pairing code instead.",
});
}
}
const code = yield* mintCode(input.authorization, decision.access);
yield* Effect.logInfo("Approved an MCP client sign-in.", {
client: input.authorization.client.name,
access: decision.access,
method: decision._tag,
});
return redirectWith(input.authorization.redirectUri, {
code,
state: input.authorization.state,
iss: input.authorization.issuer,
});
});
const deny: McpOAuth["Service"]["deny"] = (authorization) =>
redirectWith(authorization.redirectUri, {
error: "access_denied",
state: authorization.state,
iss: authorization.issuer,
});
const exchangeCode: McpOAuth["Service"]["exchangeCode"] = ({ request, urls, token }) =>
Effect.gen(function* () {
const fail = (error: AuthMcpTokenError["error"], description: string) =>
new AuthMcpTokenError({ error, error_description: description });
if (token.grant_type !== "authorization_code") {
return yield* fail("unsupported_grant_type", "Only authorization_code is supported.");
}
const { code, redirect_uri: redirectUri, client_id: clientId } = token;
const verifier = token.code_verifier;
if (!code || !redirectUri || !clientId || !verifier) {
return yield* fail(
"invalid_request",
"code, redirect_uri, client_id and code_verifier are required.",
);
}
if (parseClientId(clientId) === undefined) {
return yield* fail("invalid_client", "The client is unknown.");
}
// A presented code is spent even when a later check fails (RFC 6749 §4.1.2).
const pending = yield* Ref.modify(codes, (current) => {
const found = current.get(code);
if (found === undefined) return [undefined, current] as const;
const next = new Map(current);
next.delete(code);
return [found, next] as const;
});
const now = yield* Clock.currentTimeMillis;
if (
pending === undefined ||
pending.expiresAtMs <= now ||
pending.clientId !== clientId ||
pending.redirectUri !== redirectUri ||
pending.resource !== urls.resource ||
!sameResource(urls, token.resource) ||
!(yield* pkceVerifies(verifier, pending.codeChallenge))
) {
return yield* fail("invalid_grant", "The authorization code is invalid or expired.");
}
const issued = yield* environmentAuth
.issueMcpClientSession({
label: pending.clientName,
access: pending.access,
client: deriveAuthClientMetadata({ request }),
})
.pipe(
Effect.catch((cause) =>
Effect.logError("Could not issue an MCP client session.", { cause }).pipe(
Effect.andThen(
Effect.fail(fail("invalid_grant", "The session could not be issued.")),
),
),
),
);
return {
access_token: issued.token,
token_type: "Bearer",
expires_in: Math.max(0, Math.floor((issued.expiresAt.epochMilliseconds - now) / 1000)),
scope: encodeOAuthScope(EnvironmentAuth.mcpClientScopes(pending.access)),
};
});
return McpOAuth.of({
register,
validateAuthorization,
approvingBrowserSession,
approve,
deny,
exchangeCode,
});
});
export const layer = Layer.effect(McpOAuth, make);
/**
* Lets `/mcp` admit OAuth clients. Their scope has no calling thread, and
* never carries preview or device access: those tools act on the caller's
* own thread.
*/
export const layerMcpClientAuthenticator = Layer.effect(
McpHttpServer.McpClientAuthenticator,
Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const environment = yield* ServerEnvironment.ServerEnvironment;
const environmentId = yield* environment.getEnvironmentId;
return McpHttpServer.McpClientAuthenticator.of({
authenticate: (request) =>
environmentAuth.authenticateMcpClient(request).pipe(
Effect.flatMap((client) =>
Clock.currentTimeMillis.pipe(
Effect.map((issuedAt): McpInvocationContext.McpInvocationScope => ({
environmentId,
requestNamespace: `client:${client.sessionId}`,
thread: undefined,
client: {
sessionId: client.sessionId,
label: client.label,
access: client.access,
},
capabilities: new Set<McpInvocationContext.McpCapability>([
"orchestration",
"worktree",
"pull-requests",
]),
issuedAt,
})),
),
),
Effect.catch((error) =>
(EnvironmentAuth.isServerAuthCredentialError(error)
? Effect.void
: Effect.logWarning("MCP client authentication failed.", { cause: error })
).pipe(Effect.as(undefined)),
),
),
});
}),
);
+14
View File
@@ -276,6 +276,20 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
expect(verified.expiresAt?.toString()).toBe(issued.expiresAt.toString());
}).pipe(Effect.provide(layerSessionStore())),
);
it.effect("carries a runtime-mode ceiling only on sessions issued with one", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
const capped = yield* sessions.issue({
subject: "mcp-client",
method: "bearer-access-token",
runtimeModeCeiling: "auto",
});
const uncapped = yield* sessions.issue({ method: "bearer-access-token" });
expect((yield* sessions.verify(capped.token)).runtimeModeCeiling).toBe("auto");
expect((yield* sessions.verify(uncapped.token)).runtimeModeCeiling).toBeUndefined();
}).pipe(Effect.provide(layerSessionStore())),
);
it.effect("rejects malformed session tokens", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
+7
View File
@@ -7,6 +7,7 @@ import {
type AuthClientSession,
type AuthEnvironmentScope,
type ClientSurface,
RuntimeMode,
type ServerAuthSessionMethod,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
@@ -58,6 +59,8 @@ export interface VerifiedSession {
readonly subject: string;
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
readonly proofKeyThumbprint?: string;
/** The most an MCP client approved through OAuth may hand to the threads it drives. */
readonly runtimeModeCeiling?: RuntimeMode;
}
export type SessionCredentialChange =
@@ -374,6 +377,7 @@ export class SessionStore extends Context.Service<
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly client?: AuthClientMetadata;
readonly proofKeyThumbprint?: string;
readonly runtimeModeCeiling?: RuntimeMode;
/**
* Atomically revoke active sessions with the same subject and method
* before storing this session.
@@ -430,6 +434,7 @@ const SessionClaims = Schema.Struct({
scopes: AuthEnvironmentScopes,
method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]),
jkt: Schema.optionalKey(Schema.String),
rtc: Schema.optionalKey(RuntimeMode),
iat: Schema.Number,
exp: Schema.Number,
});
@@ -665,6 +670,7 @@ export const make = Effect.gen(function* () {
scopes: input?.scopes ?? AuthStandardClientScopes,
method: input?.method ?? "browser-session-cookie",
...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
...(input?.runtimeModeCeiling ? { rtc: input.runtimeModeCeiling } : {}),
iat: issuedAt.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
@@ -839,6 +845,7 @@ export const make = Effect.gen(function* () {
subject: claims.sub,
scopes: claims.scopes,
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
...(claims.rtc ? { runtimeModeCeiling: claims.rtc } : {}),
} satisfies VerifiedSession;
},
);
+46
View File
@@ -0,0 +1,46 @@
/**
* The page for a sign-in link that cannot be trusted (unknown client or
* unregistered redirect). It is plain server HTML so it never depends on the
* web app, and it must not redirect anywhere.
*/
const escapeHtml = (value: string) =>
value.replace(
/[&<>"']/gu,
(character) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[character]!,
);
const STYLES = `
:root { color-scheme: light dark; font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 32px 16px; background: #f6f7f9; color: #17191f; }
main { width: min(100%, 440px); }
h1 { margin: 0 0 8px; font-size: 20px; }
p { margin: 0 0 12px; line-height: 1.5; color: #4b5060; }
@media (prefers-color-scheme: dark) {
body { background: #0f1115; color: #e6e8ee; }
p { color: #a0a6b4; }
}
`;
const shell = (title: string, body: string) => `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light dark" />
<title>${escapeHtml(title)}</title>
<style>${STYLES}</style>
</head>
<body>
<main>${body}</main>
</body>
</html>`;
export function renderErrorPage(description: string): string {
return shell(
"Sign-in failed",
`<h1>This sign-in cannot continue</h1>
<p>${escapeHtml(description)}</p>
<p>Close this page and start the sign-in again from your agent.</p>`,
);
}
+159
View File
@@ -0,0 +1,159 @@
import {
AuthMcpApprovalError,
type AuthMcpAuthorizationRequest,
AuthMcpClientAccess,
EnvironmentHttpApi,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Result from "effect/Result";
import { HttpServerRequest, HttpServerResponse } from "effect/http";
import * as HttpEffect from "effect/http/HttpEffect";
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import * as McpOAuth from "./McpOAuth.ts";
import { renderErrorPage } from "./mcpOAuthHtml.ts";
/** Where the approval page lives in the web app. */
const APPROVAL_PAGE_PATH = "/connect-agent";
const PAGE_HEADERS = {
"content-security-policy":
"default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'",
"x-frame-options": "DENY",
"cache-control": "no-store",
"referrer-policy": "no-referrer",
"x-content-type-options": "nosniff",
};
/** OAuth responses carry codes, tokens and client ids, none of which may be cached. */
const noStore = HttpEffect.appendPreResponseHandler((_request, response) =>
Effect.succeed(
HttpServerResponse.setHeaders(response, { "cache-control": "no-store", pragma: "no-cache" }),
),
);
/** Issuer and resource for the origin this request reached. */
const requestUrls = Effect.map(HttpServerRequest.HttpServerRequest, McpOAuth.requestUrls);
/**
* Validates the request the approval page forwards. An unverified client or
* redirect is reported, never redirected; any other problem goes back to the
* agent through its (verified) redirect URI.
*/
const forwardedAuthorization = (
oauth: McpOAuth.McpOAuth["Service"],
request: AuthMcpAuthorizationRequest,
) =>
Effect.gen(function* () {
const urls = yield* requestUrls;
return yield* oauth.validateAuthorization({ urls, request }).pipe(
Effect.catchTags({
McpOAuthPageError: (error) =>
Effect.fail(new AuthMcpApprovalError({ message: error.description })),
McpOAuthRedirectError: (error) =>
Effect.succeed({ redirectTo: McpOAuth.redirectForError(error, urls.issuer) }),
}),
);
});
export const layer = HttpApiBuilder.group(
EnvironmentHttpApi,
"mcpOAuth",
Effect.fnUntraced(function* (handlers) {
const oauth = yield* McpOAuth.McpOAuth;
const protectedResource = () =>
requestUrls.pipe(Effect.map(McpOAuth.protectedResourceMetadata));
return (
handlers
.handle("protectedResource", protectedResource)
.handle("mcpProtectedResource", protectedResource)
.handle("authorizationServer", () =>
requestUrls.pipe(Effect.map(McpOAuth.authorizationServerMetadata)),
)
.handle("register", ({ payload }) =>
oauth.register(payload).pipe(
Effect.map((client) => ({
client_id: client.clientId,
client_name: client.name,
redirect_uris: client.redirectUris,
grant_types: ["authorization_code" as const],
response_types: ["code" as const],
token_endpoint_auth_method: "none" as const,
})),
Effect.tap(() => noStore),
),
)
// The browser lands here from the agent. A valid request is handed to the
// web app's approval page with its query intact.
.handleRaw("authorize", ({ request }) =>
Effect.gen(function* () {
const urls = yield* requestUrls;
const url = new URL(request.url, urls.issuer);
const authorization = yield* oauth
.validateAuthorization({ urls, request: Object.fromEntries(url.searchParams) })
.pipe(Effect.result);
const headers = { "cache-control": "no-store", "referrer-policy": "no-referrer" };
if (Result.isSuccess(authorization)) {
return HttpServerResponse.redirect(`${APPROVAL_PAGE_PATH}${url.search}`, { headers });
}
const error = authorization.failure;
return error._tag === "McpOAuthPageError"
? HttpServerResponse.text(renderErrorPage(error.description), {
status: 400,
contentType: "text/html; charset=utf-8",
headers: PAGE_HEADERS,
})
: HttpServerResponse.redirect(McpOAuth.redirectForError(error, urls.issuer), {
headers,
});
}),
)
// What the approval page shows, and whether one click may approve.
.handle("approval", ({ payload, request }) =>
Effect.gen(function* () {
const resolved = yield* forwardedAuthorization(oauth, payload);
if ("redirectTo" in resolved) return resolved;
const urls = yield* requestUrls;
const session = yield* oauth.approvingBrowserSession(request, resolved);
yield* noStore;
return {
clientName: resolved.client.name,
redirectHost: new URL(resolved.redirectUri).host,
environmentHost: new URL(urls.issuer).host,
...(session === undefined
? {}
: {
csrfToken: session.csrfToken,
oneClickAccess: AuthMcpClientAccess.literals.filter((access) =>
EnvironmentAuth.mcpClientScopes(access).every((scope) =>
session.scopes.includes(scope),
),
),
}),
};
}),
)
.handle("decision", ({ payload, request }) =>
Effect.gen(function* () {
const resolved = yield* forwardedAuthorization(oauth, payload.authorization);
if ("redirectTo" in resolved) return resolved;
yield* noStore;
const { decision } = payload;
if (decision._tag === "deny") return { redirectTo: oauth.deny(resolved) };
return yield* oauth.approve({ request, authorization: resolved, decision }).pipe(
Effect.map((redirectTo) => ({ redirectTo })),
Effect.mapError((error) => new AuthMcpApprovalError({ message: error.message })),
);
}),
)
.handle("token", ({ payload, request }) =>
Effect.gen(function* () {
yield* noStore;
return yield* oauth.exchangeCode({ request, urls: yield* requestUrls, token: payload });
}),
)
);
}),
);
+153 -2
View File
@@ -3,7 +3,13 @@ import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
import { expect, it } from "@effect/vitest";
import { NodeHttpServer } from "@effect/platform-node";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import {
EnvironmentId,
OrchestratorMcpFailure,
PreviewTabId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -11,14 +17,16 @@ import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { McpProtocol, McpSchema, McpServer } from "effect/ai";
import { McpProtocol, McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/http";
import * as ProjectService from "../project/ProjectService.ts";
import * as ServerConfig from "../config.ts";
import * as McpHttpServer from "./McpHttpServer.ts";
import * as McpToolAccess from "./McpToolAccess.ts";
import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
const environmentId = EnvironmentId.make("environment-mcp-test");
@@ -356,6 +364,28 @@ it.effect.each([
).pipe(Effect.provide(layerTest)),
);
it.effect("refuses preview tools to a client outside a thread before they run", () =>
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const readOnly = {
...invocation,
thread: undefined,
requestNamespace: "client:session-1",
client: { sessionId: "session-1", label: "Claude Code", access: "read-only" as const },
};
const click = yield* server
.callTool({ name: "preview_click", arguments: { locator: "text=Send" } })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, readOnly),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(click.isError).toBe(true);
expect(click.content).toEqual([
{ type: "text", text: expect.stringContaining("needs an agent running inside T3 Code") },
]);
}).pipe(Effect.provide(layerTest)),
);
it.effect("rejects non-boolean snapshot image options before selecting a browser host", () =>
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
@@ -916,3 +946,124 @@ it.effect("registers annotated tools and preserves authenticated request context
}),
).pipe(Effect.provide(layerTest)),
);
it.effect("admits provider and OAuth client credentials and points only clients at OAuth", () =>
Effect.scoped(
Effect.gen(function* () {
const providerToken = "providerTokenWithoutDots";
const clientToken = "client-payload.client-signature";
const providerScope: McpInvocationContext.McpInvocationScope = {
environmentId,
requestNamespace: "provider-session",
thread: {
threadId: ThreadId.make("thread-provider"),
providerSessionId: "provider-session",
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
const clientScope: McpInvocationContext.McpInvocationScope = {
environmentId,
requestNamespace: "client:session-1",
thread: undefined,
client: { sessionId: "session-1", label: "Claude Code", access: "auto" },
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
const seen: Array<McpInvocationContext.McpInvocationScope> = [];
const ProbeToolkit = Toolkit.make(
Tool.make("probe", {
description: "Reports the caller.",
success: Schema.Struct({ ok: Schema.Boolean }),
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies: [McpInvocationContext.McpInvocationContext],
}),
);
const serverLayer = McpHttpServer.toolkitRegistration(
ProbeToolkit,
McpToolAccess.toLayer(ProbeToolkit, {
probe: McpToolAccess.reads(() =>
McpInvocationContext.McpInvocationContext.pipe(
Effect.tap((scope) => Effect.sync(() => seen.push(scope))),
Effect.as({ ok: true }),
),
),
}),
).pipe(
Layer.provideMerge(McpHttpServer.layerMcpTransport),
Layer.provide(
Layer.mock(McpSessionRegistry.McpSessionRegistry)({
resolve: (token) =>
Effect.succeed(
token === providerToken
? (providerScope as McpInvocationContext.McpThreadInvocationScope)
: undefined,
),
}),
),
Layer.provide(
Layer.succeed(McpHttpServer.McpClientAuthenticator, {
authenticate: (request) =>
Effect.succeed(
request.headers.authorization === `Bearer ${clientToken}` ? clientScope : undefined,
),
}),
),
);
yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
Layer.build,
);
const httpClient = yield* HttpClient.HttpClient;
const call = (token: string | undefined) =>
Effect.gen(function* () {
const headers = {
accept: "application/json, text/event-stream",
...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
};
const initialize = yield* httpClient.post("/mcp", {
headers,
body: HttpBody.text(
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
"application/json",
),
});
if (initialize.status !== 200) return initialize;
return yield* httpClient.post("/mcp", {
headers: {
...headers,
"mcp-session-id": initialize.headers["mcp-session-id"]!,
"mcp-protocol-version": "2025-06-18",
},
body: HttpBody.text(
`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"probe","arguments":{}}}`,
"application/json",
),
});
});
expect((yield* call(providerToken)).status).toBe(200);
expect((yield* call(clientToken)).status).toBe(200);
expect(seen.map((scope) => scope.requestNamespace)).toEqual([
"provider-session",
"client:session-1",
]);
const missing = yield* call(undefined);
expect(missing.status).toBe(401);
expect(missing.headers["www-authenticate"]).toMatch(
/^Bearer resource_metadata="http:\/\/[^"]+\/\.well-known\/oauth-protected-resource\/mcp"$/,
);
const expiredClient = yield* call("stale-payload.stale-signature");
expect(expiredClient.headers["www-authenticate"]).toContain("resource_metadata=");
expect(expiredClient.headers["www-authenticate"]).toContain('error="invalid_token"');
const deadProvider = yield* call("deadProviderToken");
expect(deadProvider.status).toBe(401);
expect(deadProvider.headers["www-authenticate"]).toBe('Bearer error="invalid_token"');
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+93 -40
View File
@@ -58,19 +58,62 @@ import {
import * as HtmlHandlers from "./toolkits/html/handlers.ts";
import { HtmlPreviewTool, HtmlPreviewToolkit, HtmlRenderToolkit } from "./toolkits/html/tools.ts";
const unauthorized = HttpServerResponse.jsonUnsafe(
{
error: "invalid_mcp_credential",
message: "A valid provider-scoped MCP bearer credential is required.",
},
{
status: 401,
headers: {
"cache-control": "no-store",
"www-authenticate": "Bearer",
/** Where an MCP client discovers how to sign in (RFC 9728), at this request's own origin. */
const mcpResourceMetadataUrl = (request: HttpServerRequest.HttpServerRequest) =>
HttpServerRequest.toURL(request).pipe(
Option.map((url) => `${url.origin}/.well-known/oauth-protected-resource/mcp`),
);
/**
* Agents T3 Code launched carry a registry token and must never be sent into
* an OAuth flow when it dies: they cannot open a browser, and a sign-in
* would mint a credential that outlives their session. Only a request that
* does not look like a provider token is pointed at the OAuth metadata.
*/
const unauthorized = (input: {
readonly request: HttpServerRequest.HttpServerRequest;
readonly presentedToken: boolean;
readonly offerOAuth: boolean;
}) => {
const metadataUrl = input.offerOAuth
? Option.getOrUndefined(mcpResourceMetadataUrl(input.request))
: undefined;
const challenge = [
"Bearer",
[
...(metadataUrl === undefined ? [] : [`resource_metadata="${metadataUrl}"`]),
...(input.presentedToken ? ['error="invalid_token"'] : []),
].join(", "),
]
.filter((part) => part.length > 0)
.join(" ");
return HttpServerResponse.jsonUnsafe(
{
error: "invalid_mcp_credential",
message: "A valid T3 Code MCP credential is required.",
},
},
);
{
status: 401,
headers: {
"cache-control": "no-store",
"www-authenticate": challenge,
},
},
);
};
/**
* Resolves a bearer token that is not a provider-session token: an OAuth
* client signed in from outside T3. Undefined when the token is not one.
*/
export class McpClientAuthenticator extends Context.Service<
McpClientAuthenticator,
{
readonly authenticate: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<McpInvocationContext.McpInvocationScope | undefined>;
}
>()("t3/mcp/McpHttpServer/McpClientAuthenticator") {}
type AuthenticatedHttpEffect = Effect.Effect<
HttpServerResponse.HttpServerResponse,
@@ -98,33 +141,43 @@ export const normalizeMcpHttpResponse = (
: response;
};
const makeMcpAuthMiddleware = McpSessionRegistry.McpSessionRegistry.pipe(
Effect.map((registry): McpAuthMiddleware =>
Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
const request = yield* HttpServerRequest.HttpServerRequest;
const authorization = request.headers.authorization;
const token =
authorization?.startsWith("Bearer ") === true
? authorization.slice("Bearer ".length).trim()
: "";
const invocation = yield* registry.resolve(token);
if (!invocation) {
// Without this the only symptom of a dead credential is the agent
// quietly losing the whole `t3-code` toolkit for the rest of its
// session, with nothing on the server to explain why.
yield* Effect.logWarning("rejected MCP request with an unusable credential", {
reason: token.length === 0 ? "missing_bearer_token" : "unknown_or_expired_token",
});
return unauthorized;
}
return yield* httpEffect.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.map(normalizeMcpHttpResponse),
);
}),
),
Effect.withSpan("McpHttpServer.makeAuthMiddleware"),
);
// Session tokens are `<payload>.<signature>`; registry tokens are a bare base64url secret.
const looksLikeProviderToken = (token: string) => token.length > 0 && !token.includes(".");
const makeMcpAuthMiddleware = Effect.gen(function* () {
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const clients = yield* Effect.serviceOption(McpClientAuthenticator);
return Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
const request = yield* HttpServerRequest.HttpServerRequest;
const authorization = request.headers.authorization;
const token =
authorization?.startsWith("Bearer ") === true
? authorization.slice("Bearer ".length).trim()
: "";
const invocation =
(yield* registry.resolve(token)) ??
(Option.isSome(clients) && token.length > 0
? yield* clients.value.authenticate(request)
: undefined);
if (!invocation) {
// Without this the only symptom of a dead credential is the agent
// quietly losing the whole `t3-code` toolkit for the rest of its
// session, with nothing on the server to explain why.
yield* Effect.logWarning("rejected MCP request with an unusable credential", {
reason: token.length === 0 ? "missing_bearer_token" : "unknown_or_expired_token",
});
return unauthorized({
request,
presentedToken: token.length > 0,
offerOAuth: Option.isSome(clients) && !looksLikeProviderToken(token),
});
}
return yield* httpEffect.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.map(normalizeMcpHttpResponse),
);
}) satisfies McpAuthMiddleware;
}).pipe(Effect.withSpan("McpHttpServer.makeAuthMiddleware"));
const layerMcpAuthMiddleware = HttpRouter.middleware<{
provides: McpInvocationContext.McpInvocationContext;
@@ -787,7 +840,7 @@ export const layerDeviceToolkit = Layer.mergeAll(
layerDeviceScreenshotRegistration,
);
const layerMcpTransport = McpServer.layerHttp({
export const layerMcpTransport = McpServer.layerHttp({
name: "T3 Code",
version: packageJson.version,
path: "/mcp",
@@ -81,7 +81,7 @@ it.effect("refuses thread-owned capabilities to a caller signed in from outside
environmentId: EnvironmentId.make("environment-1"),
requestNamespace: "client:session-1",
thread: undefined,
client: { sessionId: "session-1", label: "Claude Code", runtimeModeCeiling: "auto" },
client: { sessionId: "session-1", label: "Claude Code", access: "auto" },
capabilities: new Set(["preview", "orchestration"]),
issuedAt: 1,
};
+11 -1
View File
@@ -1,4 +1,5 @@
import {
type AuthMcpClientAccess,
type EnvironmentId,
McpCapabilityUnavailableError,
OrchestratorMcpFailure,
@@ -30,9 +31,18 @@ export interface McpThreadCaller {
export interface McpClientCaller {
readonly sessionId: string;
readonly label: string;
readonly runtimeModeCeiling: RuntimeMode;
/** Read only, or the most the threads it starts or changes may run with. */
readonly access: AuthMcpClientAccess;
}
/**
* The runtime mode a client caller's writes are capped at. A read-only client
* never reaches a write (`McpToolAccess` refuses it first), so it maps to the
* lowest mode rather than to nothing.
*/
export const clientRuntimeModeCeiling = (client: McpClientCaller | undefined): RuntimeMode =>
client === undefined || client.access === "read-only" ? "approval-required" : client.access;
/**
* Who is calling and what they may do. Tool parameters choose the target
* (thread, project); the caller sets the limits. A thread caller's omitted
@@ -66,7 +66,7 @@ const supervisedClient: McpInvocationContext.McpInvocationScope = {
environmentId: EnvironmentId.make("environment"),
requestNamespace: "client:race",
thread: undefined,
client: { sessionId: "race", label: "Claude Code", runtimeModeCeiling: "approval-required" },
client: { sessionId: "race", label: "Claude Code", access: "approval-required" },
capabilities: new Set(["orchestration"]),
issuedAt: 0,
};
+10 -2
View File
@@ -48,12 +48,12 @@ const threadCaller = (threadId: ThreadId): McpInvocationContext.McpInvocationSco
});
const clientCaller = (
runtimeModeCeiling: RuntimeMode,
access: McpInvocationContext.McpClientCaller["access"],
): McpInvocationContext.McpInvocationScope => ({
environmentId: EnvironmentId.make("environment"),
requestNamespace: "client:session",
thread: undefined,
client: { sessionId: "session", label: "Claude Code", runtimeModeCeiling },
client: { sessionId: "session", label: "Claude Code", access },
capabilities: new Set(["orchestration"]),
issuedAt: 0,
});
@@ -193,6 +193,7 @@ const fullAccess = threadCaller(fullAccessThreadId);
const ended = threadCaller(endedThreadId);
const supervisedClient = clientCaller("approval-required");
const fullAccessClient = clientCaller("full-access");
const readOnlyClient = clientCaller("read-only");
// A live full-access thread whose credential may use its browser but not control threads.
const previewOnly = { ...fullAccess, capabilities: new Set(["preview"] as const) };
@@ -200,6 +201,13 @@ it.effect.each([
// Reads are open to every caller, even one whose turn ended.
["reads", ended, {}, "ran"],
["reads", supervisedClient, {}, "ran"],
["reads", readOnlyClient, {}, "ran"],
// A client approved for read-only access changes nothing.
["writes", readOnlyClient, {}, "capability_denied"],
["writes_threads", readOnlyClient, { threadId: supervisedThreadId }, "capability_denied"],
["starts_threads", readOnlyClient, {}, "capability_denied"],
["writes_environment", readOnlyClient, {}, "capability_denied"],
// What belongs to the calling thread needs one; changing it needs its live turn.
["reads_as_caller", ended, {}, "ran"],
+23 -2
View File
@@ -97,15 +97,36 @@ export class Declaration<out Handler> {
}
}
/** A client approved for read-only access changes nothing. */
const refuseReadOnlyClient = McpInvocationContext.McpInvocationContext.pipe(
Effect.flatMap((scope) =>
scope.client?.access === "read-only"
? Effect.fail(
new OrchestratorMcpFailure({
code: "capability_denied",
message:
"This tool changes the environment, and this MCP client was approved for read-only access.",
}),
)
: Effect.void,
),
);
/**
* The caller of a tool that changes something. Tools that act for a
* capability of their own (preview, device, worktree, pull requests) check it
* themselves.
*/
const writingCaller = loadCaller().pipe(Effect.tap(assertLiveCaller));
const writingCaller = refuseReadOnlyClient.pipe(
Effect.andThen(loadCaller()),
Effect.tap(assertLiveCaller),
);
/** The same, for tools whose only capability is controlling threads. */
const orchestratingCaller = readCaller().pipe(Effect.tap(assertLiveCaller));
const orchestratingCaller = refuseReadOnlyClient.pipe(
Effect.andThen(readCaller()),
Effect.tap(assertLiveCaller),
);
const requireThreadCaller = McpInvocationContext.McpInvocationContext.pipe(
Effect.flatMap((scope) => McpInvocationContext.requireThreadScope(scope, "This tool")),
@@ -1603,7 +1603,7 @@ describe("OrchestratorMcpService provider resolution", () => {
client: {
sessionId: "scheduled",
label: "Claude Code",
runtimeModeCeiling: "approval-required",
access: "approval-required",
},
capabilities: new Set(["orchestration"]),
issuedAt: 1,
@@ -1709,6 +1709,25 @@ describe("OrchestratorMcpService provider resolution", () => {
}),
);
it.effect("never shows a read-only client a webhook URL", () =>
Effect.gen(function* () {
const upserted = yield* Ref.make(0);
const listed = yield* OrchestratorMcpService.OrchestratorMcpService.pipe(
Effect.flatMap((mcp) =>
mcp.listScheduledTasks(
{
...supervisedClient,
client: { sessionId: "scheduled", label: "Claude Code", access: "read-only" },
},
{ projectId },
),
),
Effect.provide(service([task({})], null, upserted)),
);
assert.equal(listed.tasks[0]?.webhookUrl, undefined);
}),
);
it.effect("checks a bound task against its thread's current modes", () =>
Effect.gen(function* () {
const upserted = yield* Ref.make(0);
@@ -84,6 +84,7 @@ import * as ProjectService from "../project/ProjectService.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
import {
clientRuntimeModeCeiling,
type McpInvocationScope,
type McpThreadInvocationScope,
requireThreadScope,
@@ -908,7 +909,7 @@ const make = Effect.gen(function* () {
return {
parent: undefined,
limits: {
runtimeMode: scope.client?.runtimeModeCeiling ?? "approval-required",
runtimeMode: clientRuntimeModeCeiling(scope.client),
interactionMode: "default",
} satisfies { runtimeMode: RuntimeMode; interactionMode: ProviderInteractionMode },
} as const;
@@ -1400,8 +1401,9 @@ const make = Effect.gen(function* () {
/**
* A task as the caller may see it. Its webhook URL starts runs, so only a
* caller that may start one sees it: a thread caller with a live turn, at
* modes covering every mode the task runs at.
* caller that may start one sees it: never a client approved for read-only
* access, and a thread caller only with a live turn, at modes covering every
* mode the task runs at.
*/
const summarizeScheduledTask = (
scope: McpInvocationScope,
@@ -1416,8 +1418,9 @@ const make = Effect.gen(function* () {
) =>
Effect.gen(function* () {
const live =
caller.parent === undefined ||
Exit.isSuccess(yield* Effect.exit(assertLiveCaller(scope, caller.parent)));
caller.parent === undefined
? scope.client?.access !== "read-only"
: Exit.isSuccess(yield* Effect.exit(assertLiveCaller(scope, caller.parent)));
// This runs after a save, so a failed lookup of the bound thread hides
// the webhook URL instead of reporting a saved task as an error.
const modes = yield* scheduledTaskRunModes(task).pipe(Effect.option);
+1 -1
View File
@@ -76,7 +76,7 @@ export const loadCaller = Effect.fn("mcp.loadCaller")(function* () {
threads,
caller: undefined,
limits: {
runtimeMode: scope.client?.runtimeModeCeiling ?? "approval-required",
runtimeMode: McpInvocationContext.clientRuntimeModeCeiling(scope.client),
interactionMode: "default",
},
} satisfies Caller;
+72 -2
View File
@@ -396,12 +396,12 @@ it.effect("resolves reused attachment references from stored metadata", () =>
);
const clientScope = (
runtimeModeCeiling: "approval-required" | "auto-accept-edits" | "auto" | "full-access",
access: McpInvocationContext.McpClientCaller["access"],
): McpInvocationContext.McpInvocationScope => ({
environmentId: EnvironmentId.make("mcp-core-environment"),
requestNamespace: "client:session-1",
thread: undefined,
client: { sessionId: "session-1", label: "Claude Code", runtimeModeCeiling },
client: { sessionId: "session-1", label: "Claude Code", access },
issuedAt: 0,
capabilities: new Set(["orchestration", "worktree", "pull-requests"]),
});
@@ -474,6 +474,76 @@ it.effect("a client caller targets any thread within its ceiling and cannot act
),
);
it.effect("a read-only client reads threads and is refused every write before it runs", () =>
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const call = (name: string, args: Record<string, unknown>) =>
server
.callTool({ name, arguments: args })
.pipe(
Effect.provideService(
McpInvocationContext.McpInvocationContext,
clientScope("read-only"),
),
Effect.provideService(McpSchema.McpServerClient, client),
);
const configuration = yield* call("t3_thread_configuration", {
threadId: "other-project-thread",
});
expect(configuration.isError).toBe(false);
expect(configuration.structuredContent).toMatchObject({ runtimeMode: "auto" });
const pinned = yield* call("t3_thread_organize", {
action: "pin",
threadId: "other-project-thread",
});
expect(declaredFailure(pinned)).toMatchObject({ code: "capability_denied" });
expect(dispatched).toEqual([]);
const configure = yield* call("t3_thread_configure", {
threadId: "other-project-thread",
modelSelection: { instanceId: "codex", model: "gpt-5" },
});
expect(declaredFailure(configure)).toMatchObject({ code: "capability_denied" });
expect(dispatched).toEqual([]);
}).pipe(
Effect.provide(
McpHttpServer.layerThreadToolkit.pipe(
Layer.provideMerge(McpServer.McpServer.layer),
Layer.provide(NodeCrypto.layer),
Layer.provide(
Layer.mock(ThreadManagement.ThreadManagementService)({
getThreadShell: () =>
Effect.succeed({
id: ThreadId.make("other-project-thread"),
projectId: "other-project",
deletedAt: null,
} as never),
getProjectThreadRecords: () =>
Effect.succeed({
thread: {
id: ThreadId.make("other-project-thread"),
projectId: "other-project",
modelSelection: { instanceId: "codex", model: "gpt-5" },
runtimeMode: "auto",
interactionMode: "default",
deletedAt: null,
},
} as never),
dispatch: () =>
Effect.sync(() => {
dispatched.push("dispatch");
return { sequence: 7 } as never;
}),
}),
),
),
),
),
);
const dispatched: Array<string> = [];
it.effect("refuses act-as-caller tools to a client caller", () =>
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
@@ -313,7 +313,7 @@ const clientLaunchHarness = (input: {
client: {
sessionId: "session-1",
label: "Claude Code",
runtimeModeCeiling: input.runtimeModeCeiling,
access: input.runtimeModeCeiling,
},
issuedAt: 0,
capabilities: new Set(["orchestration" as const]),
+4
View File
@@ -116,6 +116,8 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as WebhookRoute from "./scheduledTasks/webhookRoute.ts";
import * as RelayDeliveryProof from "./scheduledTasks/RelayDeliveryProof.ts";
import * as HeldHooksWaker from "./relay/HeldHooksWaker.ts";
import * as McpOAuth from "./auth/McpOAuth.ts";
import * as McpOAuthHttp from "./auth/mcpOAuthHttp.ts";
import {
relayHookBaseUrl,
ScheduledTaskWebhookOrigin,
@@ -654,6 +656,7 @@ const layerMakeRoutes = Layer.mergeAll(
Layer.mergeAll(
HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
Layer.provide(AuthHttp.layer),
Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))),
Layer.provide(CloudHttp.layer),
Layer.provide(OrchestrationHttp.layer),
Layer.provide(PullRequestHttp.layer),
@@ -677,6 +680,7 @@ const layerMakeRoutes = Layer.mergeAll(
// what dispatch can actually serve.
McpHttpServer.layer.pipe(
Layer.provide(ProviderAdapterRegistry.layerFromProviderInstanceRegistry),
Layer.provide(McpOAuth.layerMcpClientAuthenticator),
),
).pipe(
// Both transports consume the same service instance, so caches single-flight across clients
@@ -0,0 +1,317 @@
import {
type AuthMcpApprovalDecision,
type AuthMcpApprovalDetails,
AuthMcpApprovalError,
AuthMcpClientAccess,
type AuthMcpAuthorizationRequest,
} from "@t3tools/contracts";
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
import { EyeIcon, type LucideIcon } from "lucide-react";
import type * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { type ReactNode, useCallback, useEffect, useState } from "react";
import { PrimaryEnvironmentHttpClient } from "~/environments/primary/httpClient";
import { runPrimaryHttp } from "~/lib/runtime";
import { cn } from "~/lib/utils";
import { runtimeModeConfig } from "../chat/runtimeModeConfig";
import { Alert, AlertDescription } from "../ui/alert";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { RadioGroup } from "../ui/radio-group";
import { Spinner } from "../ui/spinner";
import { AuthSurfaceShell } from "./AuthSurfaceShell";
const accessConfig: Record<
AuthMcpClientAccess,
{ readonly label: string; readonly description: string; readonly icon: LucideIcon }
> = {
"read-only": {
label: "Read only",
description: "Read projects and threads. Cannot start, message or change anything.",
icon: EyeIcon,
},
...runtimeModeConfig,
};
type Loaded =
| { readonly status: "loading" }
| { readonly status: "invalid"; readonly message: string }
| { readonly status: "ready"; readonly details: AuthMcpApprovalDetails };
const UNREACHABLE = "Could not reach this environment. Try again.";
const isApprovalError = Schema.is(AuthMcpApprovalError);
type Answer<A> =
| { readonly kind: "ok"; readonly value: A }
| { readonly kind: "redirect"; readonly url: string }
| { readonly kind: "error"; readonly message: string };
/**
* Runs an approval call. The server validates the agent's request again on
* every call and answers what the page asked for, a message to show, or a URL
* the browser must follow (an approval, a denial, or a protocol error the
* agent should receive).
*/
function runApproval<A>(
call: (
client: Context.Service.Shape<typeof PrimaryEnvironmentHttpClient>,
) => Effect.Effect<A | { readonly redirectTo: string }, unknown>,
): Promise<Answer<A>> {
return runPrimaryHttp(
PrimaryEnvironmentHttpClient.pipe(
Effect.flatMap(call),
Effect.map((value): Answer<A> =>
typeof value === "object" && value !== null && "redirectTo" in value
? { kind: "redirect", url: value.redirectTo }
: { kind: "ok", value: value as A },
),
Effect.catch((error) =>
Effect.succeed<Answer<A>>({
kind: "error",
message: isApprovalError(error) ? error.message : UNREACHABLE,
}),
),
),
).catch((): Answer<A> => ({ kind: "error", message: UNREACHABLE }));
}
function readAuthorizationRequest(): AuthMcpAuthorizationRequest {
return Object.fromEntries(new URL(window.location.href).searchParams);
}
/**
* /connect-agent: where an outside agent's MCP sign-in lands after the server
* checks the request. The user picks the most the agent may allow, then
* approves with a pairing code, or in one click when this browser is already
* signed in to the environment as an administrator.
*/
/**
* Whether this browser's session may approve `access` without a pairing code.
* A session may only grant access whose scopes it holds itself.
*/
function oneClickApproves(details: AuthMcpApprovalDetails, access: AuthMcpClientAccess) {
return details.csrfToken !== undefined && (details.oneClickAccess ?? []).includes(access);
}
export function ConnectAgentSurface() {
const [authorization] = useState(readAuthorizationRequest);
const [loaded, setLoaded] = useState<Loaded>({ status: "loading" });
const [access, setAccess] = useState<AuthMcpClientAccess>("read-only");
const [pairingCode, setPairingCode] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const [pending, setPending] = useState<"approve" | "deny" | null>(null);
useEffect(() => {
let cancelled = false;
void runApproval((client) => client.mcpOAuth.approval({ payload: authorization })).then(
(answer) => {
if (cancelled) return;
if (answer.kind === "redirect") {
window.location.replace(answer.url);
return;
}
setLoaded(
answer.kind === "error"
? { status: "invalid", message: answer.message }
: { status: "ready", details: answer.value },
);
},
);
return () => {
cancelled = true;
};
}, [authorization]);
const decide = useCallback(
async (choice: "approve" | "deny") => {
if (loaded.status !== "ready") return;
setPending(choice);
setErrorMessage("");
const { csrfToken } = loaded.details;
const decision: AuthMcpApprovalDecision =
choice === "deny"
? { _tag: "deny" }
: csrfToken !== undefined && oneClickApproves(loaded.details, access)
? { _tag: "browser-session", access, csrfToken }
: { _tag: "pairing-code", access, code: pairingCode.trim() };
const answer = await runApproval((client) =>
client.mcpOAuth.decision({ payload: { authorization, decision } }),
);
if (answer.kind === "redirect") {
window.location.replace(answer.url);
return;
}
setPending(null);
setErrorMessage(answer.kind === "error" ? answer.message : "The sign-in could not continue.");
},
[access, authorization, loaded, pairingCode],
);
if (loaded.status === "loading") {
return (
<AuthSurfaceShell>
<ConnectAgentHeading
title="Checking the sign-in request"
description="One moment while this environment verifies the agent's request."
/>
<Spinner className="mt-6" size="lg" tone="muted" />
</AuthSurfaceShell>
);
}
if (loaded.status === "invalid") {
return (
<AuthSurfaceShell>
<ConnectAgentHeading title="This sign-in cannot continue" description={loaded.message} />
<p className="mt-4 text-sm text-muted-foreground">
Close this page and start the sign-in again from your agent.
</p>
</AuthSurfaceShell>
);
}
const { details } = loaded;
const oneClick = oneClickApproves(details, access);
const canApprove = pending === null && (oneClick || pairingCode.trim().length > 0);
return (
<AuthSurfaceShell>
<ConnectAgentHeading
title={`Connect ${details.clientName}`}
description={
<>
This agent wants to use the threads in every project on{" "}
<span className="font-medium text-foreground">{details.environmentHost}</span>.
</>
}
/>
<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.
</p>
<form
className="mt-6 space-y-5"
onSubmit={(event) => {
event.preventDefault();
if (canApprove) void decide("approve");
}}
>
<div className="space-y-2">
<span id="connect-agent-access-label" className="text-sm font-medium">
What it may do
</span>
<RadioGroup
aria-labelledby="connect-agent-access-label"
value={access}
onValueChange={(value) => setAccess(value as AuthMcpClientAccess)}
>
{AuthMcpClientAccess.literals.map((option) => (
<AccessOption key={option} access={option} selected={option === access} />
))}
</RadioGroup>
<p className="text-xs text-muted-foreground">
Beyond read only, it can start, message and stop threads, and none of them can run with
more than the mode you pick.
</p>
</div>
{oneClick ? null : (
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="connect-agent-pairing-code">
Pairing code
</label>
<Input
id="connect-agent-pairing-code"
autoCapitalize="none"
autoComplete="one-time-code"
autoCorrect="off"
disabled={pending !== null}
nativeInput
onChange={(event) => setPairingCode(event.currentTarget.value)}
placeholder="Paste a one-time pairing code"
spellCheck={false}
value={pairingCode}
/>
<p className="text-xs text-muted-foreground">
Create one in Settings → Connections, or run <code>t3 auth pairing create</code> on
this machine.
</p>
</div>
)}
{errorMessage ? (
<Alert variant="error">
<AlertDescription>{errorMessage}</AlertDescription>
</Alert>
) : null}
<div className="flex flex-wrap gap-2">
<Button disabled={!canApprove} type="submit">
{pending === "approve" ? "Approving…" : "Approve"}
</Button>
<Button
disabled={pending !== null}
onClick={() => void decide("deny")}
type="button"
variant="outline"
>
{pending === "deny" ? "Denying…" : "Deny"}
</Button>
</div>
</form>
</AuthSurfaceShell>
);
}
function ConnectAgentHeading({
title,
description,
}: {
readonly title: string;
readonly description: ReactNode;
}) {
return (
<>
<p className="text-3xs font-semibold tracking-widest text-primary uppercase">Agent sign-in</p>
<h1 className="mt-2 text-2xl font-semibold tracking-tight sm:text-3xl">{title}</h1>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{description}</p>
</>
);
}
function AccessOption({
access,
selected,
}: {
readonly access: AuthMcpClientAccess;
readonly selected: boolean;
}) {
const { label, description, icon: Icon } = accessConfig[access];
return (
<RadioPrimitive.Root
value={access}
className={cn(
"flex cursor-pointer items-start gap-3 rounded-lg border px-3 py-2.5 text-left outline-none transition-[background-color,border-color,box-shadow]",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
selected
? "border-primary bg-background ring-2 ring-primary/25 dark:border-transparent dark:bg-primary/10 dark:ring-1 dark:ring-primary/30"
: "border-border bg-background hover:bg-muted/50 dark:border-transparent dark:bg-white/[0.035] dark:hover:bg-accent",
)}
>
<Icon
aria-hidden
className={cn(
"mt-0.5 size-4 shrink-0",
selected ? "text-primary" : "text-muted-foreground",
)}
/>
<span className="min-w-0">
<span className="block text-sm font-medium text-foreground">{label}</span>
<span className="block text-xs text-muted-foreground">{description}</span>
</span>
</RadioPrimitive.Root>
);
}
+21
View File
@@ -13,6 +13,7 @@ import { Route as WelcomeRouteImport } from './routes/welcome'
import { Route as UsageRouteImport } from './routes/usage'
import { Route as SettingsRouteImport } from './routes/settings'
import { Route as PairRouteImport } from './routes/pair'
import { Route as ConnectAgentRouteImport } from './routes/connect-agent'
import { Route as ConnectRouteImport } from './routes/connect'
import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
@@ -55,6 +56,11 @@ const PairRoute = PairRouteImport.update({
path: '/pair',
getParentRoute: () => rootRouteImport,
} as any)
const ConnectAgentRoute = ConnectAgentRouteImport.update({
id: '/connect-agent',
path: '/connect-agent',
getParentRoute: () => rootRouteImport,
} as any)
const ConnectRoute = ConnectRouteImport.update({
id: '/connect',
path: '/connect',
@@ -165,6 +171,7 @@ const ChatEnvironmentIdThreadIdRoute =
export interface FileRoutesByFullPath {
'/': typeof ChatIndexRoute
'/connect': typeof ConnectRoute
'/connect-agent': typeof ConnectAgentRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/usage': typeof UsageRoute
@@ -190,6 +197,7 @@ export interface FileRoutesByFullPath {
}
export interface FileRoutesByTo {
'/connect': typeof ConnectRoute
'/connect-agent': typeof ConnectAgentRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/usage': typeof UsageRoute
@@ -218,6 +226,7 @@ export interface FileRoutesById {
__root__: typeof rootRouteImport
'/_chat': typeof ChatRouteWithChildren
'/connect': typeof ConnectRoute
'/connect-agent': typeof ConnectAgentRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/usage': typeof UsageRoute
@@ -247,6 +256,7 @@ export interface FileRouteTypes {
fullPaths:
| '/'
| '/connect'
| '/connect-agent'
| '/pair'
| '/settings'
| '/usage'
@@ -272,6 +282,7 @@ export interface FileRouteTypes {
fileRoutesByTo: FileRoutesByTo
to:
| '/connect'
| '/connect-agent'
| '/pair'
| '/settings'
| '/usage'
@@ -299,6 +310,7 @@ export interface FileRouteTypes {
| '__root__'
| '/_chat'
| '/connect'
| '/connect-agent'
| '/pair'
| '/settings'
| '/usage'
@@ -327,6 +339,7 @@ export interface FileRouteTypes {
export interface RootRouteChildren {
ChatRoute: typeof ChatRouteWithChildren
ConnectRoute: typeof ConnectRoute
ConnectAgentRoute: typeof ConnectAgentRoute
PairRoute: typeof PairRoute
SettingsRoute: typeof SettingsRouteWithChildren
UsageRoute: typeof UsageRoute
@@ -364,6 +377,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof PairRouteImport
parentRoute: typeof rootRouteImport
}
'/connect-agent': {
id: '/connect-agent'
path: '/connect-agent'
fullPath: '/connect-agent'
preLoaderRoute: typeof ConnectAgentRouteImport
parentRoute: typeof rootRouteImport
}
'/connect': {
id: '/connect'
path: '/connect'
@@ -571,6 +591,7 @@ const SettingsRouteWithChildren = SettingsRoute._addFileChildren(
const rootRouteChildren: RootRouteChildren = {
ChatRoute: ChatRouteWithChildren,
ConnectRoute: ConnectRoute,
ConnectAgentRoute: ConnectAgentRoute,
PairRoute: PairRoute,
SettingsRoute: SettingsRouteWithChildren,
UsageRoute: UsageRoute,
+1 -1
View File
@@ -161,7 +161,7 @@ function RootRouteView() {
};
}, [pathname]);
if (pathname === "/pair" || pathname === "/connect") {
if (pathname === "/pair" || pathname === "/connect" || pathname === "/connect-agent") {
return (
<>
<DocumentTitleSync />
+7
View File
@@ -0,0 +1,7 @@
import { createFileRoute } from "@tanstack/react-router";
import { ConnectAgentSurface } from "../components/auth/ConnectAgentSurface";
export const Route = createFileRoute("/connect-agent")({
component: ConnectAgentSurface,
});
+5 -2
View File
@@ -9,7 +9,10 @@ import "vite-plus/test/config";
import { defineConfig, type Connect, type Plugin } from "vite-plus";
import pkg from "./package.json" with { type: "json" };
import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";
import {
DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES,
DEV_PROXIED_PATH_PREFIXES,
} from "@t3tools/shared/devProxy";
import { loadRepoEnv } from "../../scripts/lib/public-config";
import { thirdPartyLicensesPlugin } from "../../scripts/lib/third-party-licenses";
@@ -249,7 +252,7 @@ export default defineConfig(() => {
prefix,
{
target: devProxyTarget,
changeOrigin: true,
changeOrigin: !DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES.has(prefix),
...(prefix === "/ws" || prefix === "/api" ? { ws: true } : {}),
},
]),
+29 -2
View File
@@ -21,8 +21,35 @@ authority.
Browser cookies, bearer tokens, and DPoP tokens adapt the same scoped session
model. DPoP binds a token to a client's proof key; an invalid proof must fail
rather than fall back to bearer authentication. The OAuth token-exchange
vocabulary gives these grants a familiar meaning, but the environment does not
implement a general-purpose OAuth authorization server.
vocabulary gives these grants a familiar meaning.
### MCP clients are a separate audience
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
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.
The user grants either read-only access or a runtime-mode ceiling, not a
scope list: MCP tools are all orchestration, and `orchestration:operate`
alone would let an agent start a thread in full access and act through it.
The result is an ordinary session with subject `mcp-client`. A read-only
grant holds `orchestration:read` alone. On `/mcp` it passes only tools
declared as reads in [McpToolAccess](../../apps/server/src/mcp/McpToolAccess.ts),
where every tool must declare who may call it to compile. Any other grant adds
`orchestration:operate` and a signed ceiling. Only `/mcp` accepts these sessions. Every other HTTP and WebSocket
path rejects that subject, because the RPC surface would let the agent act
above its ceiling. Inside MCP the credential sets the limits and tool
parameters only pick targets; see
[threadAccess](../../apps/server/src/mcp/threadAccess.ts).
Issuer and resource URLs come from the request's Host and
`X-Forwarded-Proto`, so one server answers over loopback, Tailscale Serve and a
T3 Connect tunnel. A proxy that rewrites Host or drops the protocol header
breaks sign-in.
Bearer and DPoP clients obtain short-lived WebSocket tickets through authenticated
HTTP so long-lived tokens stay out of socket URLs. Browser sessions can
+180
View File
@@ -353,3 +353,183 @@ export const AuthSessionState = Schema.Struct({
expiresAt: Schema.optionalKey(Schema.DateTimeUtc),
});
export type AuthSessionState = typeof AuthSessionState.Type;
/**
* What an agent signed in through MCP OAuth may do, least to most: only read,
* or act on threads that never run above the given runtime mode.
*/
export const AuthMcpClientAccess = Schema.Literals([
"read-only",
"approval-required",
"auto-accept-edits",
"auto",
"full-access",
]);
export type AuthMcpClientAccess = typeof AuthMcpClientAccess.Type;
/** RFC 9728 metadata for an environment's `/mcp` resource. */
export const AuthMcpProtectedResourceMetadata = Schema.Struct({
resource: Schema.String,
authorization_servers: Schema.Array(Schema.String),
scopes_supported: Schema.Array(AuthEnvironmentScope),
bearer_methods_supported: Schema.Array(Schema.Literal("header")),
resource_name: Schema.String,
});
export type AuthMcpProtectedResourceMetadata = typeof AuthMcpProtectedResourceMetadata.Type;
/** RFC 8414 metadata for the authorization server MCP clients sign in through. */
export const AuthMcpAuthorizationServerMetadata = Schema.Struct({
issuer: Schema.String,
authorization_endpoint: Schema.String,
token_endpoint: Schema.String,
registration_endpoint: Schema.String,
response_types_supported: Schema.Array(Schema.Literal("code")),
grant_types_supported: Schema.Array(Schema.Literal("authorization_code")),
code_challenge_methods_supported: Schema.Array(Schema.Literal("S256")),
token_endpoint_auth_methods_supported: Schema.Array(Schema.Literal("none")),
scopes_supported: Schema.Array(AuthEnvironmentScope),
authorization_response_iss_parameter_supported: Schema.Boolean,
});
export type AuthMcpAuthorizationServerMetadata = typeof AuthMcpAuthorizationServerMetadata.Type;
/** RFC 7591 client metadata. Fields the server does not use are dropped. */
export const AuthMcpClientRegistration = Schema.Struct({
client_name: Schema.optionalKey(Schema.String),
redirect_uris: Schema.optionalKey(Schema.Array(Schema.String)),
token_endpoint_auth_method: Schema.optionalKey(Schema.String),
});
export type AuthMcpClientRegistration = typeof AuthMcpClientRegistration.Type;
export const AuthMcpRegisteredClient = Schema.Struct({
client_id: Schema.String,
client_name: Schema.String,
redirect_uris: Schema.Array(Schema.String),
grant_types: Schema.Array(Schema.Literal("authorization_code")),
response_types: Schema.Array(Schema.Literal("code")),
token_endpoint_auth_method: Schema.Literal("none"),
}).pipe(HttpApiSchema.status(201));
export type AuthMcpRegisteredClient = typeof AuthMcpRegisteredClient.Type;
/** RFC 7591 §3.2.2 registration error. */
export class AuthMcpRegistrationError extends Schema.Error<AuthMcpRegistrationError>(
"AuthMcpRegistrationError",
)(
{
error: Schema.Literals(["invalid_client_metadata", "invalid_redirect_uri"]),
error_description: Schema.String,
},
{ httpApiStatus: 400 },
) {
override get message(): string {
return this.error_description;
}
}
/**
* An agent's authorization request, as the approval page received it in its
* URL. Every field is checked by the server, so all are optional here.
*/
export const AuthMcpAuthorizationRequest = Schema.Struct({
response_type: Schema.optionalKey(Schema.String),
client_id: Schema.optionalKey(Schema.String),
redirect_uri: Schema.optionalKey(Schema.String),
code_challenge: Schema.optionalKey(Schema.String),
code_challenge_method: Schema.optionalKey(Schema.String),
state: Schema.optionalKey(Schema.String),
resource: Schema.optionalKey(Schema.String),
});
export type AuthMcpAuthorizationRequest = typeof AuthMcpAuthorizationRequest.Type;
/**
* What the approval page needs to show for an MCP OAuth sign-in. The server
* has already validated the request; nothing here is trusted by the client
* except for display.
*/
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. */
redirectHost: Schema.String,
environmentHost: Schema.String,
/** Present when this browser's session may approve without a pairing code. */
csrfToken: Schema.optionalKey(Schema.String),
/**
* What that session may approve in one click: only access whose scopes it
* holds. Anything else still needs a pairing code. Absent with `csrfToken`.
*/
oneClickAccess: Schema.optionalKey(Schema.Array(AuthMcpClientAccess)),
});
export type AuthMcpApprovalDetails = typeof AuthMcpApprovalDetails.Type;
/**
* Where the approval page sends the browser next: back to the agent with a
* code, a denial, or a protocol error the agent should receive.
*/
export const AuthMcpApprovalRedirect = Schema.Struct({
redirectTo: Schema.String,
});
export type AuthMcpApprovalRedirect = typeof AuthMcpApprovalRedirect.Type;
export const AuthMcpApprovalDecision = Schema.Union([
Schema.TaggedStruct("deny", {}),
Schema.TaggedStruct("pairing-code", {
access: AuthMcpClientAccess,
code: TrimmedNonEmptyString,
}),
/** One click, for a browser session that may approve (see `csrfToken`). */
Schema.TaggedStruct("browser-session", {
access: AuthMcpClientAccess,
csrfToken: Schema.String,
}),
]);
export type AuthMcpApprovalDecision = typeof AuthMcpApprovalDecision.Type;
export const AuthMcpApprovalDecisionRequest = Schema.Struct({
authorization: AuthMcpAuthorizationRequest,
decision: AuthMcpApprovalDecision,
});
export type AuthMcpApprovalDecisionRequest = typeof AuthMcpApprovalDecisionRequest.Type;
/** A problem the approval page shows the user without redirecting anywhere. */
export class AuthMcpApprovalError extends Schema.TaggedError<AuthMcpApprovalError>()(
"AuthMcpApprovalError",
{ message: Schema.String },
{ httpApiStatus: 400 },
) {}
/** RFC 6749 §4.1.3 token request. Every field is checked by the server. */
export const AuthMcpTokenRequest = Schema.Struct({
grant_type: Schema.optionalKey(Schema.String),
code: Schema.optionalKey(Schema.String),
redirect_uri: Schema.optionalKey(Schema.String),
client_id: Schema.optionalKey(Schema.String),
code_verifier: Schema.optionalKey(Schema.String),
resource: Schema.optionalKey(Schema.String),
}).pipe(HttpApiSchema.asFormUrlEncoded());
export type AuthMcpTokenRequest = typeof AuthMcpTokenRequest.Type;
export const AuthMcpTokenResult = Schema.Struct({
access_token: Schema.String,
token_type: Schema.Literal("Bearer"),
expires_in: Schema.Number,
scope: Schema.String,
});
export type AuthMcpTokenResult = typeof AuthMcpTokenResult.Type;
/** RFC 6749 §5.2 token error. */
export class AuthMcpTokenError extends Schema.Error<AuthMcpTokenError>("AuthMcpTokenError")(
{
error: Schema.Literals([
"invalid_request",
"invalid_client",
"invalid_grant",
"unsupported_grant_type",
]),
error_description: Schema.String,
},
{ httpApiStatus: 400 },
) {
override get message(): string {
return this.error_description;
}
}
+66
View File
@@ -15,6 +15,19 @@ import {
AuthBrowserSessionResult,
AuthClientSession,
AuthCreatePairingCredentialInput,
AuthMcpApprovalDecisionRequest,
AuthMcpApprovalDetails,
AuthMcpApprovalError,
AuthMcpApprovalRedirect,
AuthMcpAuthorizationRequest,
AuthMcpAuthorizationServerMetadata,
AuthMcpClientRegistration,
AuthMcpProtectedResourceMetadata,
AuthMcpRegisteredClient,
AuthMcpRegistrationError,
AuthMcpTokenError,
AuthMcpTokenRequest,
AuthMcpTokenResult,
AuthPairingCredentialResult,
AuthPairingLink,
AuthRevokeClientSessionInput,
@@ -514,6 +527,58 @@ class EnvironmentAuthHttpApi extends HttpApiGroup.make("auth")
}).middleware(EnvironmentAuthenticatedAuth),
) {}
/**
* The OAuth authorization server outside agents use to sign in to `/mcp`.
* `authorize` is where the agent sends the browser: it answers a redirect to
* the web app's approval page, or a plain error page for a request that names
* an unverified client or redirect, so the response is not a schema.
*/
class EnvironmentMcpOAuthHttpApi extends HttpApiGroup.make("mcpOAuth")
.add(
HttpApiEndpoint.get("protectedResource", "/.well-known/oauth-protected-resource", {
success: AuthMcpProtectedResourceMetadata,
}),
)
.add(
HttpApiEndpoint.get("mcpProtectedResource", "/.well-known/oauth-protected-resource/mcp", {
success: AuthMcpProtectedResourceMetadata,
}),
)
.add(
HttpApiEndpoint.get("authorizationServer", "/.well-known/oauth-authorization-server", {
success: AuthMcpAuthorizationServerMetadata,
}),
)
.add(
HttpApiEndpoint.post("register", "/oauth/mcp/register", {
payload: AuthMcpClientRegistration,
success: AuthMcpRegisteredClient,
error: AuthMcpRegistrationError,
}),
)
.add(HttpApiEndpoint.get("authorize", "/oauth/mcp/authorize"))
.add(
HttpApiEndpoint.post("approval", "/oauth/mcp/approval", {
payload: AuthMcpAuthorizationRequest,
success: [AuthMcpApprovalDetails, AuthMcpApprovalRedirect],
error: AuthMcpApprovalError,
}),
)
.add(
HttpApiEndpoint.post("decision", "/oauth/mcp/decision", {
payload: AuthMcpApprovalDecisionRequest,
success: AuthMcpApprovalRedirect,
error: AuthMcpApprovalError,
}),
)
.add(
HttpApiEndpoint.post("token", "/oauth/mcp/token", {
payload: AuthMcpTokenRequest,
success: AuthMcpTokenResult,
error: AuthMcpTokenError,
}),
) {}
const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({
threadId: ThreadId,
});
@@ -684,6 +749,7 @@ class EnvironmentWebhooksHttpApi extends HttpApiGroup.make("webhooks")
export class EnvironmentHttpApi extends HttpApi.make("environment")
.add(EnvironmentMetadataHttpApi)
.add(EnvironmentAuthHttpApi)
.add(EnvironmentMcpOAuthHttpApi)
.add(EnvironmentOrchestrationHttpApi)
.add(EnvironmentPullRequestsHttpApi)
.add(EnvironmentProjectsHttpApi)
+12 -1
View File
@@ -8,7 +8,18 @@
* prefix only Vite knows gets answered with index.html; a prefix only the
* server knows redirect-loops through the proxy.
*/
export const DEV_PROXIED_PATH_PREFIXES = ["/api", "/oauth", "/.well-known", "/ws"] as const;
export const DEV_PROXIED_PATH_PREFIXES = ["/api", "/oauth", "/.well-known", "/ws", "/mcp"] as const;
/**
* Prefixes the proxy must forward with the browser's own Host. MCP OAuth
* derives its issuer and resource URLs from the request, and a client
* rejects metadata naming a different origin than the one it fetched.
*/
export const DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES: ReadonlySet<string> = new Set([
"/oauth",
"/.well-known",
"/mcp",
]);
export function isDevProxiedPath(pathname: string): boolean {
return DEV_PROXIED_PATH_PREFIXES.some(