diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index b6bf63792bf62..6e15a12943046 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -1,6 +1,7 @@ import { AuthAccessTokenType, AuthAccessWriteScope, + AuthMcpClientAccess, AuthOrchestrationOperateScope, AuthStandardClientScopes, type AuthAccessTokenResult, @@ -9,7 +10,6 @@ import { type AuthClientSession, type AuthCreatePairingCredentialInput, type AuthEnvironmentScope, - type AuthMcpClientAccess, type AuthPairingLink, type AuthPairingCredentialResult, type AuthSessionId, @@ -48,6 +48,7 @@ import { DESKTOP_RENDERER_ORIGINS } from "../httpCors.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ManagedLimits from "../policy/managedLimits.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import { MCP_APPROVAL_SUBJECT_PREFIX } from "../persistence/AuthPairingLinks.ts"; import { requestUrl } from "../requestUrl.ts"; const DEFAULT_SESSION_SUBJECT = "cli-issued-session"; @@ -488,6 +489,7 @@ export class EnvironmentAuth extends Context.Service< readonly subject?: string; readonly proofKeyThumbprint?: string; readonly purpose?: "startup"; + readonly mcpApproval?: AuthMcpClientAccess; }) => Effect.Effect< IssuedPairingLink, ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError @@ -559,11 +561,17 @@ export class EnvironmentAuth extends Context.Service< }, ServerAuthInternalError >; - /** Spends a code covering all granted scopes. Rejects desktop grants and leaves refused proof-bound codes unspent. */ + /** + * Spends a code covering all granted scopes and returns the level it approves. A level-bound + * code must name `access`. Rejects desktop grants and leaves refused codes unspent. + */ readonly consumeMcpApprovalCode: ( code: string, access: AuthMcpClientAccess, - ) => Effect.Effect; + ) => Effect.Effect< + AuthMcpClientAccess, + ServerAuthMcpApprovalCodeError | ServerAuthInternalError + >; readonly authenticateBrowserSession: ( request: HttpServerRequest.HttpServerRequest, ) => Effect.Effect; @@ -918,6 +926,8 @@ export const make = Effect.gen(function* () { readonly proofKeyThumbprint?: string; readonly requestedScopes?: ReadonlyArray; readonly requiredScopes?: ReadonlyArray; + /** Only an agent sign-in opts in to spending a code issued for it. */ + readonly mcpApproval?: AuthMcpClientAccess; }, ): Effect.Effect< ResolvedBootstrapGrant, @@ -1032,6 +1042,7 @@ export const make = Effect.gen(function* () { ...(input?.label ? { label: input.label } : {}), ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}), ...(input?.purpose ? { purpose: input.purpose } : {}), + ...(input?.mcpApproval ? { mcpApproval: input.mcpApproval } : {}), }); return { id: issued.id, @@ -1066,7 +1077,11 @@ export const make = Effect.gen(function* () { INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT, ]; return pairingLinks - .filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject)) + .filter( + (pairingLink) => + !excludedSubjects.includes(pairingLink.subject) && + !pairingLink.subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX), + ) .map((link) => ({ ...link, ...authScopeResponse(link.scopes) })) .toSorted( (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds, @@ -1132,11 +1147,17 @@ export const make = Effect.gen(function* () { const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) => createPairingLink({ - scopes: input?.scopes ?? AuthStandardClientScopes, + scopes: input?.access + ? mcpClientScopes(input.access) + : (input?.scopes ?? AuthStandardClientScopes), subject: "one-time-token", ...(input?.label ? { label: input.label } : {}), + ...(input?.access ? { mcpApproval: input.access } : {}), }).pipe( - Effect.map(toPairingCredential), + Effect.map((issued) => ({ + ...toPairingCredential(issued), + ...(input?.access ? { access: input.access } : {}), + })), Effect.withSpan("EnvironmentAuth.issuePairingCredential"), ); @@ -1361,7 +1382,10 @@ export const make = Effect.gen(function* () { code, access, ) => - resolveBootstrapGrant(code.trim(), { requiredScopes: mcpClientScopes(access) }).pipe( + resolveBootstrapGrant(code.trim(), { + requiredScopes: mcpClientScopes(access), + mcpApproval: access, + }).pipe( Effect.catchTags({ ServerAuthInvalidCredentialError: () => Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })), @@ -1371,7 +1395,7 @@ export const make = Effect.gen(function* () { Effect.flatMap((grant) => grant.method !== "one-time-token" && grant.method !== "reusable-dev-token" ? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" })) - : Effect.void, + : Effect.succeed(mcpApprovalLevel(grant.subject) ?? access), ), Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"), ); @@ -1410,6 +1434,16 @@ export const make = Effect.gen(function* () { }); }); +const isMcpClientAccess = Schema.is(AuthMcpClientAccess); + +/** The level an approval code's subject names, or undefined for any other code. */ +const mcpApprovalLevel = (subject: string): AuthMcpClientAccess | undefined => { + const level = subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX) + ? subject.slice(MCP_APPROVAL_SUBJECT_PREFIX.length) + : undefined; + return isMcpClientAccess(level) ? level : undefined; +}; + /** Subjects of sessions and links a pairing link created, keyed by how the client paired. */ const LINK_PAIRED_SUBJECTS = { link: "one-time-token", connect: "cloud-connect" } as const; @@ -1440,8 +1474,11 @@ const revokePairedClientsThePolicyDisallows = Effect.fn( session.client.ipAddress !== undefined && !isLocalLoopbackHost(session.client.ipAddress)), ); - const links = (yield* stores.pairingLinks.listActive()).filter((link) => - disallowed.has(link.subject), + const links = (yield* stores.pairingLinks.listActive()).filter( + (link) => + disallowed.has(link.subject) || + // Approval codes let an agent elsewhere sign in, as plain codes do. + (!remoteAllowed && link.subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX)), ); yield* Effect.forEach(sessions, (session) => stores.sessions.revoke(session.sessionId), { discard: true, diff --git a/apps/server/src/auth/EnvironmentAuthAdmin.test.ts b/apps/server/src/auth/EnvironmentAuthAdmin.test.ts index 22e7c4446b8ab..d1bb7851654e8 100644 --- a/apps/server/src/auth/EnvironmentAuthAdmin.test.ts +++ b/apps/server/src/auth/EnvironmentAuthAdmin.test.ts @@ -85,6 +85,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))( const startupPhone = yield* startup("192.168.1.20"); const startupBrowser = yield* startup("127.0.0.1"); yield* environmentAuth.createPairingLink({ subject: "one-time-token" }); + yield* environmentAuth.issuePairingCredential({ access: "auto" }); yield* EnvironmentAuth.make.pipe( Effect.provide( @@ -135,6 +136,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))( subject: "one-time-token", label: "CI phone", }); + // An app approval code is never listed. + yield* environmentAuth.issuePairingCredential({ access: "auto" }); const listedBeforeRevoke = yield* environmentAuth.listPairingLinks(); const revoked = yield* environmentAuth.revokePairingLink(created.id); const listedAfterRevoke = yield* environmentAuth.listPairingLinks(); diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index d2d6c1d3b9967..7de3b890b1c31 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -5,6 +5,7 @@ import { AuthStandardClientScopes, type AuthCreatePairingCredentialInput, EnvironmentHttpApi, + MCP_PEER_LINK_SOFTWARE_ID, mcpClientScopes, } from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; @@ -53,7 +54,7 @@ const makeLayerRoutes = (capture: (auth: EnvironmentAuth.EnvironmentAuth["Servic Layer.provide( McpOAuthHttp.layer.pipe( Layer.provide(McpOAuth.layer), - Layer.provide(ServerSettings.layerTest()), + Layer.provide(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })), ), ), Layer.provide(AuthHttp.layerAuthenticatedAuth), @@ -509,6 +510,90 @@ it.live("a code minted with an access level's scopes approves that access", () = ), ); +it.live("an app approval code approves only an app sign-in, at its own level", () => + withRoutes((handler, auth) => + Effect.gen(function* () { + const clientId = yield* registeredClientId(handler); + const params = authorizeParams(clientId); + const issued = yield* auth.issuePairingCredential({ access: "approval-required" }); + expect(issued.access).toBe("approval-required"); + const code = issued.credential; + expect(code).toMatch(/^SUPERVISED-[2-9A-HJ-NP-Z]{12}$/); + + // Signing in a browser, a token exchange and linking all refuse it and leave it unspent. + const browser = yield* handler( + at("/api/auth/browser-session", { + method: "POST", + headers: { "content-type": "application/json" }, + body: encodeJson({ credential: code }), + }), + ); + expect(browser.status).toBe(401); + const exchanged = yield* auth + .exchangeBootstrapCredentialForAccessToken(code, undefined, { deviceType: "bot" }) + .pipe(Effect.flip); + expect(exchanged._tag).toBe("ServerAuthInvalidCredentialError"); + const peer = yield* handler( + at("/oauth/mcp/register", { + method: "POST", + headers: { "content-type": "application/json" }, + body: encodeJson({ + client_name: "Studio", + software_id: MCP_PEER_LINK_SOFTWARE_ID, + redirect_uris: [REDIRECT], + }), + }), + ).pipe(Effect.flatMap(json<{ client_id: string }>)); + const linked = yield* decide(handler, authorizeParams(peer.client_id), { + _tag: "pairing-code", + access: "approval-required", + code, + }); + expect(linked.status).toBe(400); + + // Supervised and Auto share scopes, so only the code's own level may spend it. + const otherLevel = yield* decide(handler, params, { + _tag: "pairing-code", + access: "auto", + code, + }); + expect(otherLevel.status).toBe(400); + + const approved = yield* decide(handler, params, { + _tag: "pairing-code", + access: "approval-required", + code: code.toLowerCase(), + }); + expect(approved.status).toBe(200); + const token = yield* handler( + at( + "/oauth/mcp/token", + form({ + grant_type: "authorization_code", + code: new URL(approved.redirectTo!).searchParams.get("code")!, + redirect_uri: params.redirect_uri, + client_id: clientId, + code_verifier: verifier, + }), + ), + ).pipe(Effect.flatMap(json<{ access_token: string }>)); + const signedIn = yield* auth.authenticateMcpClient( + HttpServerRequest.fromWeb( + at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }), + ), + ); + expect(signedIn.access).toBe("approval-required"); + expect( + (yield* decide(handler, params, { + _tag: "pairing-code", + access: "approval-required", + code, + })).status, + ).toBe(400); + }), + ), +); + it.live("one-click approves only access the browser session holds the scopes for", () => withRoutes((handler, auth) => Effect.gen(function* () { diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index 0be7c1ebb2624..5e82c7d37eb3b 100644 --- a/apps/server/src/auth/McpOAuth.ts +++ b/apps/server/src/auth/McpOAuth.ts @@ -15,6 +15,7 @@ import { AuthOrchestrationReadScope, MCP_PEER_LINK_SOFTWARE_ID, mcpClientScopes, + parseMcpApprovalCode, type RuntimeMode, } from "@t3tools/contracts"; import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth"; @@ -447,8 +448,15 @@ const make = Effect.gen(function* () { const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) { const { decision } = input; + let access = decision.access; if (decision._tag === "pairing-code") { - yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe( + // An approval code is for one app's sign-in, never for linking another environment. + if (input.authorization.client.peerLink && parseMcpApprovalCode(decision.code)) { + return yield* new McpOAuthPageError({ + description: "Linking needs a plain pairing code, not an app approval code.", + }); + } + access = yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe( Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) => Effect.logError("MCP approval code check failed.", { cause }).pipe( Effect.andThen( @@ -473,10 +481,10 @@ const make = Effect.gen(function* () { }); } } - const code = yield* mintCode(input.authorization, decision.access); + const code = yield* mintCode(input.authorization, access); yield* Effect.logInfo("Approved an MCP client sign-in.", { client: input.authorization.client.name, - access: decision.access, + access, method: decision._tag, }); return redirectWith(input.authorization.redirectUri, { diff --git a/apps/server/src/auth/PairingGrantStore.test.ts b/apps/server/src/auth/PairingGrantStore.test.ts index baa7f388f2bd4..5184beb096807 100644 --- a/apps/server/src/auth/PairingGrantStore.test.ts +++ b/apps/server/src/auth/PairingGrantStore.test.ts @@ -218,6 +218,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PairingGrantStor Stream.runForEach((change) => Queue.offer(changes, change)), Effect.forkScoped({ startImmediately: true }), ); + // An app approval code sends no update, issued or spent; the next belongs to a plain code. + const approval = yield* grants.issueOneTimeToken({ mcpApproval: "auto" }); + yield* grants.consume(approval.credential, { mcpApproval: "auto" }); for (const input of [{}, { label: "Synthetic phone" }]) { const issued = yield* grants.issueOneTimeToken(input); const change = yield* Queue.take(changes); diff --git a/apps/server/src/auth/PairingGrantStore.ts b/apps/server/src/auth/PairingGrantStore.ts index add1c7990f13c..bf9eccee8c51b 100644 --- a/apps/server/src/auth/PairingGrantStore.ts +++ b/apps/server/src/auth/PairingGrantStore.ts @@ -1,7 +1,12 @@ import { AuthStandardClientScopes, type AuthEnvironmentScope, + type AuthMcpClientAccess, type AuthPairingLink, + mcpApprovalCode, + PAIRING_CODE_ALPHABET, + PAIRING_CODE_LENGTH, + parseMcpApprovalCode, type ServerAuthBootstrapMethod, } from "@t3tools/contracts"; import { @@ -215,6 +220,8 @@ export class PairingGrantStore extends Context.Service< readonly label?: string; readonly proofKeyThumbprint?: string; readonly purpose?: "startup"; + /** Issues a hidden `-` code that only an agent sign-in at this level can spend. */ + readonly mcpApproval?: AuthMcpClientAccess; }) => Effect.Effect; readonly listActive: () => Effect.Effect< ReadonlyArray, @@ -229,6 +236,8 @@ export class PairingGrantStore extends Context.Service< readonly requestedScopes?: ReadonlyArray; /** All scopes must be granted; requestedScopes only requires an overlap for OAuth. */ readonly requiredScopes?: ReadonlyArray; + /** Also spends a code issued for an agent sign-in at this level; others refuse them. */ + readonly mcpApproval?: AuthMcpClientAccess; }, ) => Effect.Effect; } @@ -252,13 +261,11 @@ type ConsumeResult = const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5); const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24); const DEV_STARTUP_TTL_HOURS = Duration.hours(24); -const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; -const PAIRING_TOKEN_LENGTH = 12; const PAIRING_TOKEN_REJECTION_LIMIT = - Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length; + Math.floor(256 / PAIRING_CODE_ALPHABET.length) * PAIRING_CODE_ALPHABET.length; const PAIRING_TOKEN_PATTERN = new RegExp( - `^[${PAIRING_TOKEN_ALPHABET}]{${PAIRING_TOKEN_LENGTH}}$`, + `^[${PAIRING_CODE_ALPHABET}]{${PAIRING_CODE_LENGTH}}$`, "i", ); @@ -270,9 +277,9 @@ const make = Effect.gen(function* () { const changesPubSub = yield* PubSub.unbounded(); const generatePairingToken = Effect.gen(function* () { let credential = ""; - while (credential.length < PAIRING_TOKEN_LENGTH) { + while (credential.length < PAIRING_CODE_LENGTH) { const bytes = yield* random - .randomBytes(PAIRING_TOKEN_LENGTH) + .randomBytes(PAIRING_CODE_LENGTH) .pipe( Effect.mapError( (cause) => @@ -283,8 +290,8 @@ const make = Effect.gen(function* () { if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) { continue; } - credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!; - if (credential.length === PAIRING_TOKEN_LENGTH) { + credential += PAIRING_CODE_ALPHABET[byte % PAIRING_CODE_ALPHABET.length]!; + if (credential.length === PAIRING_CODE_LENGTH) { return credential; } } @@ -391,7 +398,9 @@ const make = Effect.gen(function* () { new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }), ), ); - const credential = yield* generatePairingToken; + const token = yield* generatePairingToken; + const mcpApproval = input?.mcpApproval; + const credential = mcpApproval ? mcpApprovalCode(mcpApproval, token) : token; const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup"; const ttl = input?.ttl ?? @@ -405,7 +414,9 @@ const make = Effect.gen(function* () { ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}), expiresAt, }; - const subject = input?.subject ?? "one-time-token"; + const subject = mcpApproval + ? `${AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX}${mcpApproval}` + : (input?.subject ?? "one-time-token"); yield* pairingLinks .create({ id, @@ -429,14 +440,17 @@ const make = Effect.gen(function* () { }), ), ); - yield* emitUpsert({ - id, - scopes: input?.scopes ?? AuthStandardClientScopes, - subject: input?.subject ?? "one-time-token", - ...(input?.label ? { label: input.label } : {}), - createdAt: now, - expiresAt, - }); + // Approval codes stay out of the pairing links and QR codes that clients show. + if (!mcpApproval) { + yield* emitUpsert({ + id, + scopes: input?.scopes ?? AuthStandardClientScopes, + subject, + ...(input?.label ? { label: input.label } : {}), + createdAt: now, + expiresAt, + }); + } return issued; }); @@ -546,10 +560,10 @@ const make = Effect.gen(function* () { return yield* seededResult.error; } - // Only credentials in the issued pairing-code format are case-insensitive. + // Only credentials in the issued pairing-code formats are case-insensitive. const pairingCredential = PAIRING_TOKEN_PATTERN.test(credential) ? credential.toUpperCase() - : credential; + : (parseMcpApprovalCode(credential)?.code ?? credential); // Check scopes in the UPDATE so rejected requests cannot spend one-time links. const consumed = yield* pairingLinks @@ -560,13 +574,20 @@ const make = Effect.gen(function* () { ? { requestedScopes: input.requestedScopes } : {}), ...(input?.requiredScopes !== undefined ? { requiredScopes: input.requiredScopes } : {}), + ...(input?.mcpApproval + ? { + mcpApprovalSubject: `${AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX}${input.mcpApproval}`, + } + : {}), consumedAt: now, now, }) .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause }))); if (Option.isSome(consumed)) { - yield* emitRemoved(consumed.value.id); + if (!consumed.value.subject.startsWith(AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX)) { + yield* emitRemoved(consumed.value.id); + } return { method: consumed.value.method, scopes: consumed.value.scopes, diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index 1dd273dbe64ce..c2a99533fb147 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -17,6 +17,7 @@ import { EnvironmentScopeRequiredError, EnvironmentAuthenticatedAuth, EnvironmentAuthenticatedPrincipal, + mcpClientScopes, } from "@t3tools/contracts"; import type { AuthEnvironmentScope, DpopFailureReason } from "@t3tools/contracts"; import { parseOAuthScope } from "@t3tools/shared/oauthScope"; @@ -446,7 +447,9 @@ export const layer = HttpApiBuilder.group( function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); const session = yield* requireEnvironmentScope(AuthAccessWriteScope); - const delegatedScopes = args.payload.scopes ?? AuthStandardClientScopes; + const delegatedScopes = args.payload.access + ? mcpClientScopes(args.payload.access) + : (args.payload.scopes ?? AuthStandardClientScopes); if ( delegatedScopes.length === 0 || new Set(delegatedScopes).size !== delegatedScopes.length diff --git a/apps/server/src/cloud/CloudLink.lifecycle.test.ts b/apps/server/src/cloud/CloudLink.lifecycle.test.ts index 3e34bf0be2806..f62575fc07310 100644 --- a/apps/server/src/cloud/CloudLink.lifecycle.test.ts +++ b/apps/server/src/cloud/CloudLink.lifecycle.test.ts @@ -142,6 +142,7 @@ describe("releaseManagedTunnelOnShutdown", () => { readonly respondEffect?: Effect.Effect; readonly getExisting?: CliTokenManager.CloudCliTokenManager["Service"]["getExisting"]; readonly latestReachability?: ConnectReachability.ConnectReachability["Service"]["latest"]; + readonly connector?: ManagedEndpointRuntime.ConnectorFacts; } const writeLauncherState = (update: ServiceUpdateRecord) => @@ -208,7 +209,7 @@ describe("releaseManagedTunnelOnShutdown", () => { requestRecovery: () => Effect.void, restartConnector: () => Effect.succeed(false), tunnelConnected: Stream.empty, - inspectConnector: Effect.succeed(null), + inspectConnector: Effect.succeed(harness.connector ?? null), readinessChanged: Stream.empty, withLinkStateLock: (effect) => effect, }), @@ -1079,12 +1080,20 @@ describe("releaseManagedTunnelOnShutdown", () => { expect(state.reachability?.status === "unreachable" && state.reachability.cause).not.toBe( "not_linked", ); + // The address shows before any check passes. + expect(state.tunnelHostname).toBe("prod-abc.t3coderelay.com"); }).pipe( provideReleaseHarness({ store, applyConfigCalls: [], requests: [], latestReachability: Effect.succeedSome(notLinked), + connector: { + pid: 123, + readyConnections: 0, + hostname: "prod-abc.t3coderelay.com", + protocol: null, + }, }), ); }); diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.ts index 37ac9d9b743c1..a4945e8696565 100644 --- a/apps/server/src/cloud/CloudLink.ts +++ b/apps/server/src/cloud/CloudLink.ts @@ -1283,6 +1283,10 @@ const make = Effect.gen(function* () { ], { concurrency: 8 }, ); + // The hostname arrives once cloudflared connects, before any check passes. + const connector = Option.isSome(endpointRuntimeConfig) + ? yield* endpointRuntime.inspectConnector + : null; // A not-linked check predates the stored tunnel config; the next check replaces it. const currentReachability = Option.filter( latestReachability, @@ -1303,6 +1307,7 @@ const make = Effect.gen(function* () { holdWebhooksWhileOffline: Option.isSome(holdWebhooks) && bytesToString(holdWebhooks.value) === "true", ...(Option.isSome(currentReachability) ? { reachability: currentReachability.value } : {}), + ...(connector?.hostname ? { tunnelHostname: connector.hostname } : {}), } satisfies EnvironmentCloudLinkStateResult; }); diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts index 2d3dee882dcd3..5d84c190a0f2a 100644 --- a/apps/server/src/cloud/http.test.ts +++ b/apps/server/src/cloud/http.test.ts @@ -156,7 +156,18 @@ const linkProofClient = Effect.gen(function* () { const payload = (yield* responseJson(response)) as { access_token: string }; return payload.access_token; }); - return { post, exchange }; + const linkableHere = (token: string, origin = NON_LOOPBACK_ORIGIN) => + Effect.promise(() => + handler( + new Request(`${origin}/api/connect/link-state`, { + headers: { authorization: `Bearer ${token}` }, + }), + ), + ).pipe( + Effect.flatMap(responseJson), + Effect.map((state) => (state as { linkableHere?: boolean }).linkableHere), + ); + return { post, exchange, linkableHere }; }); describe("link proof over a non-loopback desktop transport", () => { @@ -195,12 +206,12 @@ describe("link proof over a non-loopback desktop transport", () => { "does not pass desktop trust to a paired client or accept client-supplied provenance", () => Effect.gen(function* () { - const { post, exchange } = yield* linkProofClient; + const { post, exchange, linkableHere } = yield* linkProofClient; const desktop = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN); const paired = yield* post( "/api/auth/pairing-token", { - scopes: ["relay:write"], + scopes: ["relay:read", "relay:write"], label: "desktop-bootstrap", subject: "desktop-bootstrap", }, @@ -227,6 +238,10 @@ describe("link proof over a non-loopback desktop transport", () => { LOOPBACK_ORIGIN, ); expect(loopback.status).toBe(200); + // Clients offer Turn on only to the desktop's own session; SSH forwards look like loopback. + expect(yield* linkableHere(desktop)).toBe(true); + expect(yield* linkableHere(token)).toBe(false); + expect(yield* linkableHere(token, LOOPBACK_ORIGIN)).toBe(false); }), ); diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.ts index 857cb235f267e..c95fcf051bd60 100644 --- a/apps/server/src/cloud/http.ts +++ b/apps/server/src/cloud/http.ts @@ -19,6 +19,7 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as ManagedLimits from "../policy/managedLimits.ts"; import * as CloudLink from "./CloudLink.ts"; import * as ConnectReachability from "./ConnectReachability.ts"; +import { canLinkHere } from "./linkChecks.ts"; import type { RelayRequestError } from "./relayResponse.ts"; import { traceRelayRequest } from "./traceRelayRequest.ts"; @@ -129,9 +130,12 @@ export const layer = HttpApiBuilder.group( ), ) .handle("linkState", () => - requireEnvironmentScope(AuthRelayReadScope).pipe( - Effect.andThen(toHttpError(cloudLink.linkState())), - ), + Effect.gen(function* () { + const principal = yield* requireEnvironmentScope(AuthRelayReadScope); + const state = yield* toHttpError(cloudLink.linkState()); + const request = yield* HttpServerRequest.HttpServerRequest; + return { ...state, linkableHere: canLinkHere(request, principal.subject) }; + }), ) .handle("checkReachability", () => requireEnvironmentScope(AuthRelayReadScope).pipe(Effect.andThen(reachability.check)), diff --git a/apps/server/src/cloud/linkChecks.ts b/apps/server/src/cloud/linkChecks.ts index af26c659b4d98..607e2c08f8a53 100644 --- a/apps/server/src/cloud/linkChecks.ts +++ b/apps/server/src/cloud/linkChecks.ts @@ -79,6 +79,22 @@ export function parseManagedEndpointLocalOrigin(localOrigin: string) { }; } +/** + * Whether clients should offer to turn on T3 Connect over this session: only the desktop app's + * own bootstrap session, from any address (WSL answers on a distro IP), never through a proxy. + * A loopback address alone does not count, since SSH port forwards look like loopback too. + */ +export function canLinkHere( + request: HttpServerRequest.HttpServerRequest, + subject: string, +): boolean { + return ( + subject === "desktop-bootstrap" && + requestAbsoluteUrl(request) !== null && + !hasForwardedAuthorityHeaders(request) + ); +} + export function isAllowedEndpointOrigin(input: { readonly origin: RelayManagedEndpointOrigin; readonly requestUrl: string; diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index f080cc3588b42..ca6caf3178cc0 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -287,6 +287,7 @@ export const make = Effect.gen(function* () { peerLinks: true, mcpModeLimitHeader: true, linkFence: true, + mcpApprovalCodes: true, }, }; diff --git a/apps/server/src/persistence/AuthPairingLinks.ts b/apps/server/src/persistence/AuthPairingLinks.ts index 8754bdbd2edcd..52323f9690af5 100644 --- a/apps/server/src/persistence/AuthPairingLinks.ts +++ b/apps/server/src/persistence/AuthPairingLinks.ts @@ -16,6 +16,12 @@ import { PersistenceSqlError, } from "./Errors.ts"; +/** + * Subjects of codes that approve one agent sign-in at a set level, as `mcp-approval:`. + * Only that sign-in may spend one, so every other use of a pairing code refuses them. + */ +export const MCP_APPROVAL_SUBJECT_PREFIX = "mcp-approval:"; + export const AuthPairingLinkRecord = Schema.Struct({ id: Schema.String, credential: Schema.String, @@ -49,6 +55,8 @@ export const ConsumeAuthPairingLinkInput = Schema.Struct({ proofKeyThumbprint: Schema.NullOr(Schema.String), requestedScopes: Schema.optionalKey(AuthEnvironmentScopes), requiredScopes: Schema.optionalKey(AuthEnvironmentScopes), + /** Also spends a code with exactly this `mcp-approval:` subject. Others are always refused. */ + mcpApprovalSubject: Schema.optionalKey(Schema.String), consumedAt: Schema.DateTimeUtcFromString, now: Schema.DateTimeUtcFromString, }); @@ -167,6 +175,7 @@ export const make = Effect.gen(function* () { proofKeyThumbprint, requestedScopes, requiredScopes, + mcpApprovalSubject, consumedAt, now, }) => @@ -177,6 +186,10 @@ export const make = Effect.gen(function* () { AND revoked_at IS NULL AND consumed_at IS NULL AND expires_at > ${now} + AND ( + subject NOT LIKE ${`${MCP_APPROVAL_SUBJECT_PREFIX}%`} + OR subject = ${mcpApprovalSubject ?? null} + ) AND ( proof_key_thumbprint IS NULL OR proof_key_thumbprint = ${proofKeyThumbprint} diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.ts index 1adfb24e406fd..c474ed0fa6c8f 100644 --- a/apps/web/src/cloud/linkEnvironment.ts +++ b/apps/web/src/cloud/linkEnvironment.ts @@ -7,6 +7,7 @@ import type { HttpClient } from "effect/http"; import { EnvironmentCloudEndpointUnavailableError, type EnvironmentCloudLinkStateResult, + type EnvironmentConnectReachability, EnvironmentHttpBadRequestError, EnvironmentHttpConflictError, EnvironmentHttpForbiddenError, @@ -256,6 +257,24 @@ export const readCloudLinkState: (input: { ); }); +/** Runs the environment's T3 Connect reachability check now; the link state then reports it. */ +export const checkCloudReachability: (input: { + readonly target: CloudLinkTarget; +}) => Effect.Effect = + Effect.fn("linkEnvironment.checkCloudReachability")(function* (input: { + readonly target: CloudLinkTarget; + }) { + return yield* connectRequest( + input.target, + { + method: "POST", + url: (urls) => urls.checkReachability(), + request: ({ client, headers }) => client.checkReachability({ headers }), + }, + "Could not check T3 Connect.", + ); + }); + export const updateCloudPreferences: (input: { readonly target: CloudLinkTarget; readonly publishAgentActivity: boolean; diff --git a/apps/web/src/cloud/linkEnvironmentAtoms.ts b/apps/web/src/cloud/linkEnvironmentAtoms.ts index 66b7f884e9a5e..69bb779fb6ed3 100644 --- a/apps/web/src/cloud/linkEnvironmentAtoms.ts +++ b/apps/web/src/cloud/linkEnvironmentAtoms.ts @@ -5,7 +5,9 @@ import { import { connectionAtomRuntime } from "../connection/runtime"; import { + checkCloudReachability, linkEnvironmentToCloud, + readCloudLinkState, type CloudLinkMode, type CloudLinkTarget, unlinkEnvironmentFromCloud, @@ -47,3 +49,13 @@ export const updateEnvironmentPreferences = createRuntimeCommand(connectionAtomR readonly holdWebhooksWhileOffline?: boolean; }) => updateCloudPreferences(input), }); + +export const checkReachability = createRuntimeCommand(connectionAtomRuntime, { + label: "web:cloud:check-reachability", + execute: (input: { readonly target: CloudLinkTarget }) => checkCloudReachability(input), +}); + +export const readLinkState = createRuntimeCommand(connectionAtomRuntime, { + label: "web:cloud:read-link-state", + execute: (input: { readonly target: CloudLinkTarget }) => readCloudLinkState(input), +}); diff --git a/apps/web/src/cloud/t3ConnectState.ts b/apps/web/src/cloud/t3ConnectState.ts new file mode 100644 index 0000000000000..c468c73d965ea --- /dev/null +++ b/apps/web/src/cloud/t3ConnectState.ts @@ -0,0 +1,69 @@ +import type { EnvironmentCloudLinkStateResult } from "@t3tools/contracts"; +import type { + RelayManagedEndpoint, + RelayManagedEndpointProviderKind, +} from "@t3tools/contracts/relay"; + +// Require managed discovery: stale tunnel config after a publish-only switch causes endpoint_provider_not_managed. +export function isManagedTunnelActive( + linkState: EnvironmentCloudLinkStateResult, + relayProviderKind: RelayManagedEndpointProviderKind | undefined, +) { + const localManagedTunnel = linkState.managedTunnelActive ?? linkState.linked; + return ( + linkState.linkRevoked !== true && + localManagedTunnel && + (relayProviderKind === undefined || relayProviderKind === "cloudflare_tunnel") + ); +} + +// The URL ends up in commands people paste into a shell, so only plain DNS names pass. +const TUNNEL_HOSTNAME = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/i; + +/** + * An environment's MCP URL on its T3 Connect tunnel, or null. This machine reports its own + * tunnel hostname; a saved machine's comes from T3 Connect, and only a tunnel counts there, + * since a publish-only link registers its local address as `manual`. + */ +export function t3ConnectMcpUrl(input: { + readonly thisMachine: boolean; + readonly tunnelHostname: string | undefined; + readonly relayEndpoint: RelayManagedEndpoint | undefined; +}): string | null { + const url = input.thisMachine + ? URL.parse(`https://${input.tunnelHostname ?? ""}`) + : input.relayEndpoint?.providerKind === "cloudflare_tunnel" + ? URL.parse(input.relayEndpoint.httpBaseUrl) + : null; + return url?.protocol === "https:" && TUNNEL_HOSTNAME.test(url.hostname) + ? `${url.origin}/mcp` + : null; +} + +/** Where T3 Connect can be turned on for an environment: from here, only by policy, or on its host. */ +export type T3ConnectTurnOn = + | { readonly kind: "here" } + | { readonly kind: "policy"; readonly reason: string } + | { readonly kind: "on-host" }; + +/** + * Settings and the MCP wizard share this, so a Turn on control shows only where linking works. + * `linkableHere` is the environment's own answer for this session (its link state). + */ +export function resolveT3ConnectTurnOn(input: { + readonly desktopApp: boolean; + readonly linkableHere: boolean; + readonly cloudConfigured: boolean; + readonly canReadRelay: boolean; + readonly canWriteRelay: boolean; + readonly connectDenial: string | undefined; +}): T3ConnectTurnOn { + if (input.connectDenial !== undefined) return { kind: "policy", reason: input.connectDenial }; + return input.desktopApp && + input.linkableHere && + input.cloudConfigured && + input.canReadRelay && + input.canWriteRelay + ? { kind: "here" } + : { kind: "on-host" }; +} diff --git a/apps/web/src/cloud/useCloudLinkController.ts b/apps/web/src/cloud/useCloudLinkController.ts index d47572891037c..c59eb5eee6855 100644 --- a/apps/web/src/cloud/useCloudLinkController.ts +++ b/apps/web/src/cloud/useCloudLinkController.ts @@ -1,14 +1,8 @@ import { useAtomValue } from "@effect/atom-react"; import { useAuth } from "@clerk/react"; import { findErrorTraceId } from "@t3tools/client-runtime/errors"; -import { - AuthRelayReadScope, - AuthRelayWriteScope, - type EnvironmentCloudLinkStateResult, - type EnvironmentId, -} from "@t3tools/contracts"; +import { AuthRelayReadScope, AuthRelayWriteScope, type EnvironmentId } from "@t3tools/contracts"; import { ManagedRelay } from "@t3tools/client-runtime/relay"; -import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay"; import { isAtomCommandInterrupted, settlePromise, @@ -32,6 +26,7 @@ import { } from "./linkEnvironmentAtoms"; import { readCachedCloudLinkState, useCloudLinkState } from "./cloudLinkState"; import { resolveRelayClerkTokenOptions } from "./publicConfig"; +import { isManagedTunnelActive } from "./t3ConnectState"; export interface CloudLinkDesiredState { readonly managedTunnel: boolean; @@ -39,19 +34,6 @@ export interface CloudLinkDesiredState { readonly holdWebhooksWhileOffline?: boolean; } -// Require managed discovery: stale tunnel config after a publish-only switch causes endpoint_provider_not_managed. -function isManagedTunnelActive( - linkState: EnvironmentCloudLinkStateResult, - relayProviderKind: RelayManagedEndpointProviderKind | undefined, -) { - const localManagedTunnel = linkState.managedTunnelActive ?? linkState.linked; - return ( - linkState.linkRevoked !== true && - localManagedTunnel && - (relayProviderKind === undefined || relayProviderKind === "cloudflare_tunnel") - ); -} - const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError); const isManagedRelayClientError = Schema.is(ManagedRelay.ManagedRelayClientError); diff --git a/apps/web/src/cloud/useT3ConnectTurnOn.ts b/apps/web/src/cloud/useT3ConnectTurnOn.ts new file mode 100644 index 0000000000000..5683c735b421b --- /dev/null +++ b/apps/web/src/cloud/useT3ConnectTurnOn.ts @@ -0,0 +1,30 @@ +import { + AuthRelayReadScope, + AuthRelayWriteScope, + type EnvironmentId, + managedCapabilityDenial, +} from "@t3tools/contracts"; + +import { isElectron } from "../env"; +import { useManagedPolicy } from "../state/managedPolicy"; +import { useEnvironmentScope } from "../state/session"; +import { useCloudLinkState } from "./cloudLinkState"; +import { hasCloudPublicConfig } from "./publicConfig"; +import { resolveT3ConnectTurnOn } from "./t3ConnectState"; + +/** Whether this client can turn on T3 Connect for `environmentId`, and if not, why. */ +export function useT3ConnectTurnOn(environmentId: EnvironmentId | null) { + const canReadRelay = useEnvironmentScope(environmentId, AuthRelayReadScope); + const canWriteRelay = useEnvironmentScope(environmentId, AuthRelayWriteScope); + const connectDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "connect"); + const linkState = useCloudLinkState(environmentId).data; + return resolveT3ConnectTurnOn({ + desktopApp: isElectron, + // Unknown while loading and on older servers, which keep today's switch in Settings. + linkableHere: linkState?.linkableHere ?? true, + cloudConfigured: hasCloudPublicConfig(), + canReadRelay, + canWriteRelay, + connectDenial, + }); +} diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 5d08f4c7f6e8d..6352b577eb70a 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -73,6 +73,7 @@ import { MonitorIcon, PinIcon, PinOffIcon, + PlugIcon, SquarePenIcon, TextSearchIcon, UserPlusIcon, @@ -247,6 +248,7 @@ import { ProjectFilePicker } from "./files/ProjectFilePicker"; import { openLinkPullRequestDialog } from "./pullRequest/LinkPullRequestDialog"; import { canShareWithGuestAtom } from "./chat/guestShareAvailability"; import { openGuestShareDialog } from "./chat/guestShareDialogState"; +import { openUseInAnotherApp } from "./mcp/UseInAnotherAppDialog"; import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog"; import { settingsForThisPlatform, SETTINGS_SECTION_LABELS } from "./settings/settingsSearch"; import { primaryServerKeybindingsAtom } from "../state/server"; @@ -1602,6 +1604,34 @@ function OpenCommandPaletteDialog(props: { }); } + actionItems.push({ + kind: "action", + value: "action:use-in-another-app", + searchTerms: [ + "mcp", + "connector", + "another app", + "poke", + "claude", + "chatgpt", + "grok", + "muse", + "instinct", + "openclaw", + "hermes", + ], + title: "Use T3 Code in another app (MCP)", + icon: , + run: async () => { + openUseInAnotherApp( + currentProjectEnvironmentId ?? + (paletteRouteTarget?.kind === "server" + ? paletteRouteTarget.threadRef.environmentId + : null), + ); + }, + }); + actionItems.push({ kind: "action", value: "action:usage", diff --git a/apps/web/src/components/auth/ConnectAgentSurface.logic.test.ts b/apps/web/src/components/auth/ConnectAgentSurface.logic.test.ts index b5d7d8ebc9900..6eef0b5248844 100644 --- a/apps/web/src/components/auth/ConnectAgentSurface.logic.test.ts +++ b/apps/web/src/components/auth/ConnectAgentSurface.logic.test.ts @@ -1,13 +1,43 @@ import { expect, it } from "vite-plus/test"; -import { RuntimeMode } from "@t3tools/contracts"; +import { AuthMcpClientAccess, RuntimeMode } from "@t3tools/contracts"; -import { resolveMcpAccess } from "./ConnectAgentSurface.logic"; +import { resolveApprovalDecision, resolveMcpAccess } from "./ConnectAgentSurface.logic"; it.each(RuntimeMode.literals)("keeps MCP access within the %s policy ceiling", (maxRuntimeMode) => { const ceiling = { organization: "Example", maxRuntimeMode }; - expect(resolveMcpAccess("auto", ceiling)).toBe( + expect(resolveMcpAccess("auto", ceiling, false)).toBe( maxRuntimeMode === "full-access" ? "auto" : maxRuntimeMode, ); - expect(resolveMcpAccess("read-only", ceiling)).toBe("read-only"); - expect(resolveMcpAccess("approval-required", ceiling)).toBe("approval-required"); + expect(resolveMcpAccess("read-only", ceiling, false)).toBe("read-only"); + expect(resolveMcpAccess("approval-required", ceiling, false)).toBe("approval-required"); +}); + +it("checks a typed code even in a signed-in browser, and approves without one at Read only", () => { + const signedOut = { + clientName: "Poke", + redirectHost: "poke.com", + environmentHost: "prod-a1.t3coderelay.com", + }; + const details = { ...signedOut, csrfToken: "csrf", oneClickAccess: AuthMcpClientAccess.literals }; + const access = resolveMcpAccess(null, undefined, false); + + // A typed code starts at Auto, and an expired one must fail rather than fall back to this session. + expect( + resolveApprovalDecision({ + code: " 7K2P9QXR4MZT ", + access: resolveMcpAccess(null, undefined, true), + details, + }), + ).toEqual({ _tag: "pairing-code", access: "auto", code: "7K2P9QXR4MZT" }); + expect(resolveApprovalDecision({ code: "auto-q8rz3nwd5ktc", access, details })).toEqual({ + _tag: "pairing-code", + access: "auto", + code: "auto-q8rz3nwd5ktc", + }); + expect(resolveApprovalDecision({ code: "", access, details })).toEqual({ + _tag: "browser-session", + access: "read-only", + csrfToken: "csrf", + }); + expect(resolveApprovalDecision({ code: "", access, details: signedOut })).toBeNull(); }); diff --git a/apps/web/src/components/auth/ConnectAgentSurface.logic.ts b/apps/web/src/components/auth/ConnectAgentSurface.logic.ts index 351716b8e9682..62eec0bddc8b6 100644 --- a/apps/web/src/components/auth/ConnectAgentSurface.logic.ts +++ b/apps/web/src/components/auth/ConnectAgentSurface.logic.ts @@ -1,16 +1,47 @@ import { + type AuthMcpApprovalDecision, type AuthMcpApprovalDetails, type AuthMcpClientAccess, isRuntimeModeAbove, + parseMcpApprovalCode, } from "@t3tools/contracts"; +/** + * The picker's access, lowered to a managed ceiling: the user's choice, else Auto for a typed + * code, else Read only, since approving without a code says nothing about what the user wants. + */ export function resolveMcpAccess( - access: AuthMcpClientAccess, + requested: AuthMcpClientAccess | null, ceiling: AuthMcpApprovalDetails["runtimeModeCeiling"], -) { + hasCode: boolean, +): AuthMcpClientAccess { + const access = requested ?? (hasCode ? "auto" : "read-only"); return access !== "read-only" && ceiling !== undefined && isRuntimeModeAbove(access, ceiling.maxRuntimeMode) ? ceiling.maxRuntimeMode : access; } + +/** + * What Approve sends. A typed code is always checked as a code, even when the browser's + * session could approve, and a level-bound code sends its own level. Null: nothing to send. + */ +export function resolveApprovalDecision(input: { + readonly code: string; + readonly access: AuthMcpClientAccess; + readonly details: AuthMcpApprovalDetails; +}): Exclude | null { + const code = input.code.trim(); + if (code.length > 0) { + return { + _tag: "pairing-code", + access: parseMcpApprovalCode(code)?.access ?? input.access, + code, + }; + } + const { csrfToken, oneClickAccess } = input.details; + return csrfToken !== undefined && (oneClickAccess ?? []).includes(input.access) + ? { _tag: "browser-session", access: input.access, csrfToken } + : null; +} diff --git a/apps/web/src/components/auth/ConnectAgentSurface.tsx b/apps/web/src/components/auth/ConnectAgentSurface.tsx index ec6aa5b3abc6d..0a15ba5760de4 100644 --- a/apps/web/src/components/auth/ConnectAgentSurface.tsx +++ b/apps/web/src/components/auth/ConnectAgentSurface.tsx @@ -6,6 +6,7 @@ import { AuthMcpAuthorizationRequest, isRuntimeModeAbove, managedRuntimeModeCeilingMessage, + parseMcpApprovalCode, } from "@t3tools/contracts"; import { Radio as RadioPrimitive } from "@base-ui/react/radio"; import { isLoopbackHost } from "@t3tools/shared/preview"; @@ -18,7 +19,7 @@ import { type ReactNode, useEffect, useState } from "react"; import { PrimaryEnvironmentHttpClient } from "~/environments/primary/httpClient"; import { runPrimaryHttp } from "~/lib/runtime"; import { cn } from "~/lib/utils"; -import { resolveMcpAccess } from "./ConnectAgentSurface.logic"; +import { resolveApprovalDecision, resolveMcpAccess } from "./ConnectAgentSurface.logic"; import { runtimeModeConfig } from "../chat/runtimeModeConfig"; import { Alert, AlertDescription } from "../ui/alert"; import { Button } from "../ui/button"; @@ -85,20 +86,16 @@ function readAuthorizationRequest(): AuthMcpAuthorizationRequest { return decodeAuthorizationRequest(Object.fromEntries(new URL(window.location.href).searchParams)); } -/** Sessions can grant only scopes they hold. */ -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({ status: "loading" }); - const [requestedAccess, setAccess] = useState("auto"); + const [requestedAccess, setAccess] = useState(null); + const [pairingCode, setPairingCode] = useState(""); const access = resolveMcpAccess( requestedAccess, loaded.status === "ready" ? loaded.details.runtimeModeCeiling : undefined, + pairingCode.trim().length > 0, ); - const [pairingCode, setPairingCode] = useState(""); const [errorMessage, setErrorMessage] = useState(""); const [pending, setPending] = useState<"approve" | "deny" | null>(null); @@ -126,15 +123,13 @@ export function ConnectAgentSurface() { const decide = async (choice: "approve" | "deny") => { if (loaded.status !== "ready") return; - setPending(choice); - setErrorMessage(""); - const { csrfToken } = loaded.details; - const decision: AuthMcpApprovalDecision = + const decision: AuthMcpApprovalDecision | null = choice === "deny" ? { _tag: "deny" } - : csrfToken !== undefined && oneClickApproves(loaded.details, access) - ? { _tag: "browser-session", access, csrfToken } - : { _tag: "pairing-code", access, code: pairingCode.trim() }; + : resolveApprovalDecision({ code: pairingCode, access, details: loaded.details }); + if (decision === null) return; + setPending(choice); + setErrorMessage(""); const answer = await runApproval((client) => client.mcpOAuth.decision({ payload: { authorization, decision } }), ); @@ -170,8 +165,10 @@ export function ConnectAgentSurface() { } const { details } = loaded; - const oneClick = oneClickApproves(details, access); - const canApprove = pending === null && (oneClick || pairingCode.trim().length > 0); + const canApprove = + pending === null && resolveApprovalDecision({ code: pairingCode, access, details }) !== null; + // A code from "Use T3 Code in another app" names its level, so the page does not ask again. + const codeAccess = parseMcpApprovalCode(pairingCode)?.access; return ( @@ -184,20 +181,23 @@ export function ConnectAgentSurface() { } /> -

- {redirectsToThisComputer(details.redirectHost) ? ( - <> - The name is chosen by the agent. Approval returns to {details.redirectHost} on the - computer that opened this page. Only approve a sign-in you just started. - - ) : ( - <> - The name is chosen by the agent. Approval gives access to whoever runs{" "} - {details.redirectHost}. Only - approve a sign-in you just started there. - - )} -

+
+
App
+
+ {details.clientName} · name set by the app +
+
Access goes to
+
+ {details.redirectHost} + {redirectsToThisComputer(details.redirectHost) ? ( + + {" "} + on the computer that opened this page + + ) : null} +
+
+

Only approve a sign-in you just started.

- - What it may do - - setAccess(value as AuthMcpClientAccess)} - > - {AuthMcpClientAccess.literals.map((option) => ( - - ))} - + + setPairingCode(event.currentTarget.value)} + placeholder="Paste a code" + spellCheck={false} + value={pairingCode} + />

- Beyond read only, it can start, message and stop threads, and none of them can run with - more than the mode you pick. + Get one from Use T3 Code in another app (MCP), Settings → Sharing & access, or{" "} + t3 auth pairing create on this machine.

- {oneClick ? null : ( + {codeAccess ? ( +

+ Access{" "} + {accessConfig[codeAccess].label} +

+ ) : (
- - setPairingCode(event.currentTarget.value)} - placeholder="Paste a one-time pairing code" - spellCheck={false} - value={pairingCode} - /> + + What it may do + + setAccess(value as AuthMcpClientAccess)} + > + {AuthMcpClientAccess.literals.map((option) => ( + + ))} +

- Create one in Settings → Sharing & access, or run t3 auth pairing create{" "} - on this machine. + Beyond read only, it can start, message and stop threads, and none of them can run + with more than the mode you pick.

)} @@ -262,7 +267,11 @@ export function ConnectAgentSurface() {
+ ) : null} + {step === 2 ? ( + + ) : ( + + )} + + ) : null} + + ); +} + +/** The level the Access step starts at: Auto, else the next one down that can be granted. */ +const DEFAULT_LEVELS: readonly AuthMcpClientAccess[] = [ + "auto", + "auto-accept-edits", + "approval-required", + "read-only", +]; + +/** Why each level cannot be granted on this environment; absent when it can. */ +function useGrantableLevels(environment: EnvironmentPresentation) { + const environmentId = environment.environmentId; + const session = useEnvironmentSessionState(environmentId).data; + const canMint = useEnvironmentScope(environmentId, AuthAccessWriteScope); + const policy = useManagedPolicy(environmentId); + // The server refuses codes for any level when its policy keeps remote clients out. + const remoteDenial = managedCapabilityDenial(policy, "remoteClients"); + return new Map( + AuthMcpClientAccess.literals.flatMap((level) => { + const reason = + remoteDenial ?? + (!canMint + ? `This device needs the Manage access permission on ${environment.label}.` + : session === null || + !mcpClientScopes(level).every((scope) => sessionGrantsScope(session, scope)) + ? `This device cannot grant this on ${environment.label}.` + : level === "read-only" + ? undefined + : managedRuntimeModeDenial(policy, level)); + return reason === undefined ? [] : [[level, reason] as const]; + }), + ); +} + +function useGate(environment: EnvironmentPresentation) { + const environmentId = environment.environmentId; + const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); + const controller = useCloudLinkController(environmentId); + const canReadRelay = useEnvironmentScope(environmentId, AuthRelayReadScope); + const thisMachine = + environmentId === usePrimaryEnvironmentId() || + isDesktopLocalConnectionTarget(environment.entry.target); + const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom); + const refreshDiscovery = useAtomCommand(relayEnvironmentDiscovery.refresh, { + reportFailure: false, + }); + const runCheck = useAtomCommand(checkReachability, { reportFailure: false }); + const readState = useAtomCommand(readLinkState, { reportFailure: false }); + // The gate opens on a check it ran, or on a newer one the link state reports. A failed run + // counts only server checks newer than `since` (see afterFailedCheck); null waits for a retry. + const [check, setCheck] = useState< + | "idle" + | "running" + | { readonly result: EnvironmentConnectReachability | null; readonly since: string | null } + >("idle"); + const [connecting, setConnecting] = useState(false); + const linkState = controller.linkState.data; + const reported = linkState?.reachability; + const serverConfig = environment.serverConfig; + const connected = environment.connection.phase === "connected"; + const relayEntry = discovery.environments.get(environmentId); + const gate = resolveMcpGate({ + signedIn: isSignedIn, + connected, + approvalCodes: + serverConfig === null + ? undefined + : serverConfig.environment.capabilities.mcpApprovalCodes === true, + canReadRelay, + linkState, + linkStateError: controller.linkState.error, + thisMachine, + relay: + !discovery.refreshing && (discovery.offline || Option.isSome(discovery.error)) + ? { status: "failed" } + : discovery.listed + ? { + status: "listed", + endpoint: relayEntry?.environment.endpoint, + availability: relayEntry?.availability, + } + : { status: "loading" }, + reachability: + typeof check === "string" + ? "checking" + : reported !== undefined && check.since !== null && reported.checkedAt > check.since + ? reported + : check.result, + }); + const runReachabilityCheck = async () => { + setCheck("running"); + // A saved machine's address comes from T3 Connect's list, which can be stale. + if (!thisMachine) void refreshDiscovery(); + const prior = readCachedCloudLinkState({ environmentId }); + const result = await runCheck({ target: { environmentId } }); + controller.linkState.refresh(); + if (result._tag === "Success") { + setCheck({ result: result.value, since: result.value.checkedAt }); + return; + } + const latest = await readState({ target: { environmentId } }); + setCheck(afterFailedCheck(prior, latest._tag === "Success" ? latest.value : null)); + }; + const turnOn = async () => { + setConnecting(true); + const ok = await controller.reconcileCloudState({ + managedTunnel: true, + publish: controller.publishAgentActivity, + }); + if (!ok) setConnecting(false); + }; + // A cached link state can name a tunnel on a disconnected machine; checking it would fail and + // spend the one automatic check. + const canCheck = connected && linkState !== null && isManagedTunnelActive(linkState, undefined); + const checkOnce = useEffectEvent(() => { + if (check === "idle") void runReachabilityCheck(); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the server to check its tunnel once one exists + useEffect(() => { + if (canCheck) queueMicrotask(checkOnce); + }, [canCheck]); + // T3 Connect lists machines only once something asks, and a saved machine's gate reads that list. + const discoverIfUnasked = useEffectEvent(() => { + if (!thisMachine && !discovery.listed && !discovery.refreshing) void refreshDiscovery(); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks T3 Connect for its machine list once the wizard opens signed in + useEffect(() => { + if (isSignedIn) discoverIfUnasked(); + }, [isSignedIn]); + const waiting = gate.kind === "offline" || (connecting && gate.kind === "turn-on"); + const refreshLinkState = useEffectEvent(() => controller.linkState.refresh()); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- polls the server's link state while the tunnel starts; the server has no push for it + useEffect(() => { + if (!waiting) return; + const interval = window.setInterval(() => refreshLinkState(), 5_000); + return () => window.clearInterval(interval); + }, [waiting]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- stops showing Connecting once a started tunnel has had time to come up + useEffect(() => { + if (!connecting) return; + const timeout = window.setTimeout(() => setConnecting(false), 90_000); + return () => window.clearTimeout(timeout); + }, [connecting]); + return { + gate, + connecting: connecting && gate.kind !== "open", + check: runReachabilityCheck, + // A disconnected machine cannot be checked; its list entry says when it is back. + refreshList: () => void refreshDiscovery(), + turnOn, + operationError: controller.operationError, + tunnelLimit: controller.tunnelLimit, + }; +} + +type Gate = ReturnType; + +function GateScreen({ + environment, + gate: { gate, connecting, check, refreshList, turnOn, operationError, tunnelLimit }, +}: { + readonly environment: EnvironmentPresentation; + readonly gate: Gate; +}) { + const name = environment.label; + const turnOnHere = useT3ConnectTurnOn(environment.environmentId); + const { openAuthPrompt } = useT3ConnectAuthPrompt(); + const retry = (onClick: () => void) => ( + + ); + const checkAgain = retry(() => void check()); + switch (gate.kind) { + case "checking": + return ( +

+ + Checking T3 Connect… +

+ ); + case "sign-in": + return ( + + {/* Clerk's sign-in is its own modal, so this dialog closes first. */} + + + ); + case "disconnected": + return gate.relay === null ? ( + + ) : ( + + {retry(refreshList)} + + ); + case "update": + return ; + case "no-relay-read": + return ( + + ); + case "error": + return ( + + {checkAgain} + + ); + case "turn-on": + case "offline": { + if (gate.kind === "offline" && !connecting) { + const reachability = gate.reachability; + return ( + + {checkAgain} + + ); + } + return ( + + {turnOnHere.kind === "here" ? ( +
+ + {operationError ? ( +

{operationError}

+ ) : null} + {tunnelLimit !== null ? ( + <> +

+ Your T3 Connect account is out of tunnels. +

+ + + ) : null} +
+ ) : turnOnHere.kind === "policy" ? ( +

{turnOnHere.reason}

+ ) : ( +
+ +

Restart T3 Code on {name}.

+ {checkAgain} +
+ )} +
+ ); + } + case "open": + return null; + } +} + +function GateMessage({ + title, + lines = [], + children, +}: { + readonly title: string; + readonly lines?: readonly string[]; + readonly children?: ReactNode; +}) { + return ( +
+

{title}

+ {lines.length > 0 ? ( +
+ {lines.map((line) => ( +

{line}

+ ))} +
+ ) : null} + {children} +
+ ); +} + +function AppStep({ + choice, + onChoose, +}: { + readonly choice: Choice | null; + readonly onChoose: (choice: Choice) => void; +}) { + return ( +
+

Which app?

+
+ {MCP_APPS.filter((app) => !app.hidden).map((app) => ( + + ))} +
+ +
+ ); +} + +function ConnectStep({ + environment, + mcpUrl, + choice, + access, +}: { + readonly environment: EnvironmentPresentation; + readonly mcpUrl: string; + readonly choice: Choice; + readonly access: AuthMcpClientAccess; +}) { + const [anotherWay, setAnotherWay] = useState(choice === "other"); + const app = choice === "other" ? null : choice; + const code = ( + + ); + if (anotherWay || app === null) { + const message = app?.handoff.kind === "copy-message" ? app.handoff.message(mcpUrl) : null; + return ( +
+ + {message ? : null} +
    + {(app?.steps ?? OTHER_MCP_APP_STEPS).map((step) => ( +
  1. {step}
  2. + ))} +
+ {app === null ? ( +

+ Apps that require their own client ID cannot connect. +

+ ) : app.docs ? ( + openLink(app.docs ?? "")}>{app.name} help + ) : null} + {code} + {app === null ? null : ( + setAnotherWay(false)}> + {app.handoff.kind === "commands" ? "Back to commands" : "Back to one click"} + + )} + +
+ ); + } + return ( +
+ + + {code} + setAnotherWay(true)}>Set up another way + +
+ ); +} + +function TextButton({ + onClick, + children, +}: { + readonly onClick: () => void; + readonly children: ReactNode; +}) { + return ( + + ); +} + +function openLink(url: string) { + void readLocalApi() + ?.shell.openExternal(url) + .catch((error: unknown) => + toastManager.add({ + type: "error", + title: "Could not open the link", + description: error instanceof Error ? error.message : url, + }), + ); +} + +function PrimaryAction({ app, mcpUrl }: { readonly app: McpApp; readonly mcpUrl: string }) { + const action = mcpHandoffAction(app, mcpUrl); + const note = app.note ?

{app.note}

: null; + if (action === null) { + return ( +
+ {app.handoff.kind === "commands" + ? app.handoff + .commands(mcpUrl) + .map((command) => ) + : null} +

Run these where {app.name} runs.

+ {note} +
+ ); + } + const { copy, link } = action; + const handOff = async () => { + if (copy !== null) { + // The app opens only once the copy lands, so it never gets an older clipboard. + const copied = await writeTextToClipboard(copy.text, copy.title).catch(() => false); + if (!copied) { + toastManager.add({ + type: "error", + title: "Could not copy", + description: "Use Set up another way.", + }); + return; + } + toastManager.add({ + type: "success", + title: copy.title, + // A browser can block an open that follows the copy; this keeps a way through. + ...(isElectron + ? {} + : { actionProps: { children: `Open ${app.name}`, onClick: () => openLink(link) } }), + }); + } + openLink(link); + }; + return ( +
+ + {note} +
+ ); +} + +/** "Get code" mints on click; the code is never copied or sent anywhere by itself. */ +function ApprovalCode({ + environmentId, + name, + access, +}: { + readonly environmentId: EnvironmentId; + readonly name: string; + readonly access: AuthMcpClientAccess; +}) { + const [code, setCode] = useState<{ + readonly credential: string; + readonly expiresAt: number; + } | null>(null); + const [pending, setPending] = useState(false); + const [error, setError] = useState(null); + const now = useNowSecond(); + const live = code !== null && now < code.expiresAt; + const mint = async () => { + setPending(true); + setError(null); + const result = await mintMcpApprovalCodeOn(environmentId, access); + setPending(false); + if (Result.isSuccess(result)) { + setCode({ + credential: result.success.credential, + expiresAt: result.success.expiresAt.epochMilliseconds, + }); + } else { + setError(`Could not get a code from ${name}. Try again.`); + } + }; + const left = code === null ? 0 : Math.max(0, Math.floor((code.expiresAt - now) / 1000)); + return ( +
+
+ + Code to approve {accessConfig[access].label} + + {live ? null : ( + + )} +
+ {code !== null ? ( + live ? ( + <> + +

+ Expires {Math.floor(left / 60)}:{String(left % 60).padStart(2, "0")} · one use +

+ + ) : ( +

The code expired.

+ ) + ) : null} + {error ?

{error}

: null} +
+ ); +} + +function CopyRow({ label, value }: { readonly label: string; readonly value: string }) { + const { copyToClipboard, isCopied } = useCopyToClipboard({ timeout: 1500, target: label }); + return ( +
+ {label} + {value} + +
+ ); +} + +const levelRank = (level: AuthMcpClientAccess) => AuthMcpClientAccess.literals.indexOf(level); + +/** Machines this environment links to, at the level a call forwarded there gets. */ +function LinkedLine({ + environment, + access, +}: { + readonly environment: EnvironmentPresentation; + readonly access: AuthMcpClientAccess; +}) { + const offered = offersLinkedEnvironments(environment.serverConfig); + const links = useEnvironmentQuery( + offered + ? peerLinkEnvironment.list({ environmentId: environment.environmentId, input: {} }) + : null, + ).data?.links; + const identities = useEnvironmentIdentities(); + if (!offered || links === undefined || links.length === 0) return null; + const named = links.map((link) => { + const name = + identities.find((identity) => identity.environmentId === link.environmentId)?.label ?? + link.label; + // A forwarded call keeps the lower of the app's level and the link's own. + const level = levelRank(link.access) < levelRank(access) ? link.access : access; + return `${name} · ${link.status === "expired" ? "Expired" : accessConfig[level].label}`; + }); + return

Linked: {named.join(", ")}

; +} + +/** Opens Sharing & access on this environment, where its clients and T3 Connect tunnels live. */ +function ManageAccessButton({ + environment, + label = "Manage access", +}: { + readonly environment: EnvironmentPresentation; + readonly label?: string; +}) { + const navigate = useNavigate(); + return ( + + ); +} diff --git a/apps/web/src/components/mcp/logos/chatgpt.png b/apps/web/src/components/mcp/logos/chatgpt.png new file mode 100644 index 0000000000000..c31e8cd671893 Binary files /dev/null and b/apps/web/src/components/mcp/logos/chatgpt.png differ diff --git a/apps/web/src/components/mcp/logos/claude.png b/apps/web/src/components/mcp/logos/claude.png new file mode 100644 index 0000000000000..97cd6632ddfce Binary files /dev/null and b/apps/web/src/components/mcp/logos/claude.png differ diff --git a/apps/web/src/components/mcp/logos/gemini.png b/apps/web/src/components/mcp/logos/gemini.png new file mode 100644 index 0000000000000..08aa0dd821cbe Binary files /dev/null and b/apps/web/src/components/mcp/logos/gemini.png differ diff --git a/apps/web/src/components/mcp/logos/grokbot.png b/apps/web/src/components/mcp/logos/grokbot.png new file mode 100644 index 0000000000000..dd9a384be3c78 Binary files /dev/null and b/apps/web/src/components/mcp/logos/grokbot.png differ diff --git a/apps/web/src/components/mcp/logos/hermes.png b/apps/web/src/components/mcp/logos/hermes.png new file mode 100644 index 0000000000000..0bd2f8348a597 Binary files /dev/null and b/apps/web/src/components/mcp/logos/hermes.png differ diff --git a/apps/web/src/components/mcp/logos/instinct.png b/apps/web/src/components/mcp/logos/instinct.png new file mode 100644 index 0000000000000..e1b2d36c2030c Binary files /dev/null and b/apps/web/src/components/mcp/logos/instinct.png differ diff --git a/apps/web/src/components/mcp/logos/muse.png b/apps/web/src/components/mcp/logos/muse.png new file mode 100644 index 0000000000000..a4578f1533bb8 Binary files /dev/null and b/apps/web/src/components/mcp/logos/muse.png differ diff --git a/apps/web/src/components/mcp/logos/openclaw.png b/apps/web/src/components/mcp/logos/openclaw.png new file mode 100644 index 0000000000000..523a781e391fa Binary files /dev/null and b/apps/web/src/components/mcp/logos/openclaw.png differ diff --git a/apps/web/src/components/mcp/logos/poke.png b/apps/web/src/components/mcp/logos/poke.png new file mode 100644 index 0000000000000..cefa5c3a1ec6e Binary files /dev/null and b/apps/web/src/components/mcp/logos/poke.png differ diff --git a/apps/web/src/components/mcp/mcpApps.test.ts b/apps/web/src/components/mcp/mcpApps.test.ts new file mode 100644 index 0000000000000..0e9f85f84aa1d --- /dev/null +++ b/apps/web/src/components/mcp/mcpApps.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { MCP_APPS, mcpHandoffAction } from "./mcpApps"; + +const MCP_URL = "https://prod-a1.t3coderelay.com/mcp?x=1&y=two words"; + +describe("MCP app links", () => { + it("fill in T3 Code and the encoded URL", () => { + const opened = (id: string) => { + const app = MCP_APPS.find((candidate) => candidate.id === id)!; + return new URL(mcpHandoffAction(app, MCP_URL)!.link); + }; + const poke = opened("poke"); + expect(poke.searchParams.get("name")).toBe("T3 Code"); + expect(poke.searchParams.get("url")).toBe(MCP_URL); + const claude = opened("claude"); + expect(claude.searchParams.get("connectorName")).toBe("T3 Code"); + expect(claude.searchParams.get("connectorUrl")).toBe(MCP_URL); + }); + + // The desktop app opens only http and https links. + it.each(MCP_APPS.map((app) => [app.name, app] as const))("%s opens only https", (_, app) => { + const link = mcpHandoffAction(app, MCP_URL)?.link; + for (const url of [link, app.docs].filter((value) => value != null)) { + expect(new URL(url).protocol).toBe("https:"); + } + }); +}); diff --git a/apps/web/src/components/mcp/mcpApps.ts b/apps/web/src/components/mcp/mcpApps.ts new file mode 100644 index 0000000000000..c2285157a8f02 --- /dev/null +++ b/apps/web/src/components/mcp/mcpApps.ts @@ -0,0 +1,201 @@ +import chatgptLogo from "./logos/chatgpt.png"; +import claudeLogo from "./logos/claude.png"; +import geminiLogo from "./logos/gemini.png"; +import grokBotLogo from "./logos/grokbot.png"; +import hermesLogo from "./logos/hermes.png"; +import instinctLogo from "./logos/instinct.png"; +import museLogo from "./logos/muse.png"; +import openClawLogo from "./logos/openclaw.png"; +import pokeLogo from "./logos/poke.png"; + +/** How the Connect step hands T3 Code's MCP URL to an app. Every link is https. */ +export type McpAppHandoff = + /** Opens the app's add form with T3 Code filled in. */ + | { readonly kind: "open"; readonly link: (mcpUrl: string) => string } + /** Copies the URL, then opens the page it goes on. */ + | { readonly kind: "copy-url"; readonly link: string } + /** Copies a message for the app's chat, then opens the app. */ + | { + readonly kind: "copy-message"; + readonly link: string; + readonly message: (mcpUrl: string) => string; + } + /** Commands to run where the app runs. */ + | { readonly kind: "commands"; readonly commands: (mcpUrl: string) => readonly string[] }; + +export interface McpApp { + readonly id: string; + readonly name: string; + readonly logo: string; + readonly handoff: McpAppHandoff; + /** "Set up another way", next to the URL. */ + readonly steps: readonly string[]; + /** One line under the primary action. */ + readonly note?: string; + readonly docs?: string; + /** Kept out of the grid until its sign-in works. */ + readonly hidden?: boolean; +} + +const encoded = encodeURIComponent; + +export const MCP_APPS: readonly McpApp[] = [ + { + id: "poke", + name: "Poke", + logo: pokeLogo, + handoff: { + kind: "open", + link: (url) => `https://poke.com/integrations/new?name=T3%20Code&url=${encoded(url)}`, + }, + steps: ["Open poke.com/integrations/new.", "Paste the URL and add the integration."], + docs: "https://poke.com/docs/mcp-servers", + }, + { + id: "claude", + name: "Claude", + logo: claudeLogo, + handoff: { + kind: "open", + link: (url) => + `https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=T3%20Code&connectorUrl=${encoded(url)}`, + }, + steps: [ + "In Claude, open Customize, then Connectors.", + "Choose Add custom connector and paste the URL.", + "The Free plan allows one custom connector.", + ], + docs: "https://claude.com/docs/connectors/building/directory-vs-custom", + }, + { + id: "chatgpt", + name: "ChatGPT", + logo: chatgptLogo, + handoff: { kind: "copy-url", link: "https://chatgpt.com/plugins" }, + steps: [ + "Open chatgpt.com/plugins on the web, then + and Add custom MCP server.", + "Paste the URL. Choose OAuth.", + "Create it as a plugin, then install it.", + ], + docs: "https://developers.openai.com/api/docs/guides/custom-mcp-server", + }, + { + id: "grok-bot", + name: "Grok Bot", + logo: grokBotLogo, + // The app has no web chat, and its prompt links need a Bot id. + handoff: { + kind: "copy-message", + link: "https://x.ai/bot", + message: (url) => `Add the MCP server ${url} and connect it.`, + }, + steps: ["Send this message to any of your Grok Bots."], + note: "Shared with all your Grok Bots.", + docs: "https://docs.x.ai/grok-bot/computer-and-apps", + }, + { + id: "gemini", + name: "Gemini", + logo: geminiLogo, + handoff: { kind: "copy-url", link: "https://gemini.google.com/apps" }, + steps: [ + "In Gemini, open Settings, then Connected apps.", + "Choose Custom apps, then Add, and paste the URL.", + ], + docs: "https://support.google.com/gemini/answer/17209137", + // Gemini's sign-in and its tool schema checks do not work with T3 Code yet. + hidden: true, + }, + { + id: "muse", + name: "Muse", + logo: museLogo, + handoff: { + kind: "copy-message", + link: "https://muse.ai", + message: (url) => `Create a custom connector for the MCP server ${url}.`, + }, + steps: ["Send this message to Muse."], + docs: "https://www.meta.com/help/artificial-intelligence/1687253048996149/", + }, + { + id: "instinct", + name: "Instinct", + logo: instinctLogo, + handoff: { + kind: "copy-message", + link: "https://app.instinct.com", + message: (url) => `Connect the MCP server ${url}.`, + }, + steps: ["In Instinct, open Settings, then MCP connections, if your account has it."], + }, + { + id: "openclaw", + name: "OpenClaw", + logo: openClawLogo, + handoff: { + kind: "commands", + commands: (url) => [ + // Its MCP commands refuse to write while the Gateway runs. + "openclaw gateway stop", + `openclaw mcp add t3code --url ${url} --transport streamable-http --auth oauth`, + "openclaw mcp login t3code", + "openclaw gateway start", + ], + }, + steps: [ + "Open the Control UI, then + and Plugins, and choose Add MCP server.", + "Paste the URL, and choose Streamable HTTP and OAuth.", + "Select Sign in for it under Settings → MCP.", + ], + docs: "https://docs.openclaw.ai/tools/mcp", + }, + { + id: "hermes-agent", + name: "Hermes Agent", + logo: hermesLogo, + handoff: { + kind: "commands", + commands: (url) => [ + // `add` signs in on its first connection (30 s by default, too short to get a code); + // `login` would clear that sign-in and need a second code. + `hermes mcp add t3code --url ${url} --auth oauth --connect-timeout 315`, + ], + }, + steps: [ + "Add t3code under mcp_servers in ~/.hermes/config.yaml, with the URL and auth: oauth.", + "Run hermes mcp login t3code.", + ], + note: "On a remote host, paste the final URL back when asked.", + docs: "https://hermes-agent.nousresearch.com/docs/user-guide/features/mcp", + }, +]; + +/** The "Something else…" choice: the URL and general steps only. */ +export const OTHER_MCP_APP_STEPS = ["Add a remote MCP server with OAuth."] as const; + +/** + * The primary button for `app`: its label, the https page it opens, and what it copies first. + * Null for apps set up with commands. It never copies the approval code. + */ +export function mcpHandoffAction(app: McpApp, mcpUrl: string) { + const { handoff } = app; + switch (handoff.kind) { + case "open": + return { label: `Open in ${app.name}`, link: handoff.link(mcpUrl), copy: null }; + case "copy-url": + return { + label: `Copy URL and open ${app.name}`, + link: handoff.link, + copy: { text: mcpUrl, title: "URL copied" }, + }; + case "copy-message": + return { + label: `Copy message and open ${app.name}`, + link: handoff.link, + copy: { text: handoff.message(mcpUrl), title: "Message copied" }, + }; + case "commands": + return null; + } +} diff --git a/apps/web/src/components/mcp/mcpGate.test.ts b/apps/web/src/components/mcp/mcpGate.test.ts new file mode 100644 index 0000000000000..2a8943d6a47d1 --- /dev/null +++ b/apps/web/src/components/mcp/mcpGate.test.ts @@ -0,0 +1,203 @@ +import type { EnvironmentCloudLinkStateResult } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { afterFailedCheck, resolveMcpGate } from "./mcpGate"; + +const reachable = { + status: "reachable", + checkedAt: "2026-11-08T00:00:00.000Z", + readyConnections: 4, + protocol: "quic", +} as const; + +const tunnel: EnvironmentCloudLinkStateResult = { + linked: true, + cloudUserId: "user_1", + relayUrl: "https://relay.example.test", + relayIssuer: "https://relay.example.test", + managedTunnelActive: true, + publishAgentActivity: true, + tunnelHostname: "prod-a1.t3coderelay.com", +}; + +const savedTunnel = { + httpBaseUrl: "https://prod-b2.t3coderelay.com", + wsBaseUrl: "wss://prod-b2.t3coderelay.com", + providerKind: "cloudflare_tunnel", +} as const; + +const open = { + signedIn: true, + connected: true, + approvalCodes: true, + canReadRelay: true, + linkState: tunnel, + linkStateError: null, + thisMachine: true, + relay: { status: "listed", endpoint: undefined }, + reachability: reachable, +} satisfies Parameters[0]; + +const saved = { + ...open, + thisMachine: false, + relay: { status: "listed", endpoint: savedTunnel }, +} satisfies Parameters[0]; + +describe("resolveMcpGate", () => { + it("opens on a fresh reachable check, at the tunnel's MCP URL", () => { + expect(resolveMcpGate(open)).toEqual({ + kind: "open", + mcpUrl: "https://prod-a1.t3coderelay.com/mcp", + }); + // A saved machine's address comes from T3 Connect, not from what it reports itself. + expect(resolveMcpGate(saved)).toEqual({ + kind: "open", + mcpUrl: "https://prod-b2.t3coderelay.com/mcp", + }); + // A disconnected saved machine follows T3 Connect's list. Offline or an unreadable list keeps + // a retry; only a list showing nothing wrong asks to reconnect. + const away = { ...saved, connected: false }; + const listed = ( + availability: "checking" | "online" | "offline" | "error", + providerKind: "cloudflare_tunnel" | "manual" = "cloudflare_tunnel", + ) => ({ + ...away, + relay: { + status: "listed", + endpoint: { ...savedTunnel, providerKind }, + availability, + } as const, + }); + expect(resolveMcpGate(listed("checking")).kind).toBe("checking"); + expect(resolveMcpGate(listed("offline"))).toEqual({ kind: "disconnected", relay: "offline" }); + expect(resolveMcpGate(listed("error"))).toEqual({ kind: "disconnected", relay: "failed" }); + // T3 Connect refuses to check a publish-only link, so that failure says nothing. + expect(resolveMcpGate(listed("error", "manual"))).toEqual({ + kind: "disconnected", + relay: null, + }); + expect(resolveMcpGate({ ...away, relay: { status: "failed" } })).toEqual({ + kind: "disconnected", + relay: "failed", + }); + expect(resolveMcpGate(listed("online"))).toEqual({ kind: "disconnected", relay: null }); + // This machine's probe outranks a stale publish-only record in that list. + expect( + resolveMcpGate({ + ...open, + relay: { status: "listed", endpoint: { ...savedTunnel, providerKind: "manual" } }, + }).kind, + ).toBe("open"); + }); + + it.each([ + ["no T3 Connect sign-in", { ...open, signedIn: false }, "sign-in"], + ["no permission to read T3 Connect", { ...open, canReadRelay: false }, "no-relay-read"], + ["a server without approval codes", { ...open, approvalCodes: false }, "update"], + ["no tunnel", { ...open, linkState: { ...tunnel, managedTunnelActive: false } }, "turn-on"], + ["a removed link", { ...open, linkState: { ...tunnel, linkRevoked: true } }, "turn-on"], + [ + "a publish-only link's local address", + { + ...saved, + relay: { + status: "listed", + endpoint: { + ...savedTunnel, + httpBaseUrl: "http://127.0.0.1:3773", + providerKind: "manual", + }, + }, + }, + "turn-on", + ], + [ + "a saved machine T3 Connect does not list", + { ...saved, relay: { status: "listed", endpoint: undefined } }, + "turn-on", + ], + ["T3 Connect's list still loading", { ...saved, relay: { status: "loading" } }, "checking"], + [ + "a disconnected saved machine while T3 Connect's list refreshes", + { ...saved, connected: false, relay: { status: "loading" } }, + "checking", + ], + [ + "no tunnel, before T3 Connect's list loads", + { + ...saved, + linkState: { ...tunnel, managedTunnelActive: false }, + relay: { status: "loading" }, + }, + "turn-on", + ], + ["the check still running", { ...open, reachability: "checking" }, "checking"], + [ + "an offline tunnel", + { + ...open, + reachability: { + status: "unreachable", + checkedAt: "2026-11-08T00:00:00.000Z", + cause: "no_connector", + reason: "Cloudflare has no live connection from this machine for the tunnel.", + hint: null, + fix: "Restart T3 Code.", + }, + }, + "offline", + ], + ["a failed check", { ...open, reachability: null }, "offline"], + [ + "no tunnel address yet", + { ...open, linkState: { ...tunnel, tunnelHostname: undefined } }, + "offline", + ], + [ + "a hostname that is not a plain DNS name", + { ...open, linkState: { ...tunnel, tunnelHostname: "a.com;touch$IFS/tmp/x" } }, + "offline", + ], + ] as const)("stays closed with %s", (_, input, kind) => { + expect(resolveMcpGate(input).kind).toBe(kind); + }); +}); + +describe("afterFailedCheck", () => { + const at = (checkedAt: string) => ({ ...tunnel, reachability: { ...reachable, checkedAt } }); + const older = at("2026-11-08T00:00:00.000Z"); + const newer = at("2026-11-08T00:01:00.000Z"); + + it.each([ + [ + "a check the server finished anyway", + older, + newer, + { result: newer.reachability, since: newer.reachability.checkedAt }, + ], + ["no newer check", newer, newer, { result: null, since: newer.reachability.checkedAt }], + [ + "nothing known before, so the read is only a baseline", + null, + newer, + { result: null, since: newer.reachability.checkedAt }, + ], + [ + "no read after, so the old result is the baseline", + older, + null, + { result: null, since: older.reachability.checkedAt }, + ], + ["nothing read at all, so only a retry counts", null, null, { result: null, since: null }], + [ + "a first server check", + tunnel, + newer, + { result: newer.reachability, since: newer.reachability.checkedAt }, + ], + ["no server check yet, so any later one counts", tunnel, null, { result: null, since: "" }], + ] as const)("with %s", (_, prior, latest, expected) => { + expect(afterFailedCheck(prior, latest)).toEqual(expected); + }); +}); diff --git a/apps/web/src/components/mcp/mcpGate.ts b/apps/web/src/components/mcp/mcpGate.ts new file mode 100644 index 0000000000000..3234bf698a6ac --- /dev/null +++ b/apps/web/src/components/mcp/mcpGate.ts @@ -0,0 +1,121 @@ +import type { + EnvironmentCloudLinkStateResult, + EnvironmentConnectReachability, +} from "@t3tools/contracts"; +import type { Discovery } from "@t3tools/client-runtime/relay"; +import type { RelayManagedEndpoint } from "@t3tools/contracts/relay"; + +import { isManagedTunnelActive, t3ConnectMcpUrl } from "~/cloud/t3ConnectState"; + +type Unreachable = Extract; + +/** + * What stands between the user and the wizard's steps. Only `open` lets them go on: cloud apps + * need a public address, so the environment must answer on its T3 Connect tunnel. + */ +export type McpGate = + | { readonly kind: "checking" } + | { readonly kind: "sign-in" } + /** + * `relay`: T3 Connect reports the saved machine offline, or its list could not be read; both + * keep a retry. Null when that list shows nothing wrong, so the user should reconnect. + */ + | { readonly kind: "disconnected"; readonly relay: "offline" | "failed" | null } + | { readonly kind: "update" } + | { readonly kind: "no-relay-read" } + | { readonly kind: "error"; readonly message: string } + | { readonly kind: "turn-on" } + | { readonly kind: "offline"; readonly reachability: Unreachable | null } + | { readonly kind: "open"; readonly mcpUrl: string }; + +export function resolveMcpGate(input: { + /** Undefined until T3 Connect sign-in has loaded. */ + readonly signedIn: boolean | undefined; + readonly connected: boolean; + /** The environment's `mcpApprovalCodes` capability; undefined until its config loads. */ + readonly approvalCodes: boolean | undefined; + readonly canReadRelay: boolean; + readonly linkState: EnvironmentCloudLinkStateResult | null; + readonly linkStateError: string | null; + /** A backend this device runs; its link state names its own tunnel. */ + readonly thisMachine: boolean; + /** The account's machines on T3 Connect, where a saved machine's address and health come from. */ + readonly relay: + | { readonly status: "loading" | "failed" } + | { + readonly status: "listed"; + readonly endpoint: RelayManagedEndpoint | undefined; + readonly availability?: Discovery.RelayEnvironmentAvailability | undefined; + }; + /** A check run for this gate: its answer, "checking" until it has one, or null if it failed. */ + readonly reachability: EnvironmentConnectReachability | "checking" | null; +}): McpGate { + if (input.signedIn === undefined) return { kind: "checking" }; + if (!input.signedIn) return { kind: "sign-in" }; + const { relay } = input; + if (!input.connected) { + if (input.thisMachine) return { kind: "disconnected", relay: null }; + // T3 Connect checks only its own tunnels; a publish-only link's check always fails. + const availability = + relay.status === "listed" && relay.endpoint?.providerKind === "cloudflare_tunnel" + ? relay.availability + : undefined; + // A refresh empties the list first, so wait for it instead of flashing "Connect first". + if (relay.status === "loading" || availability === "checking") return { kind: "checking" }; + if (relay.status === "failed" || availability === "error") { + return { kind: "disconnected", relay: "failed" }; + } + return { kind: "disconnected", relay: availability === "offline" ? "offline" : null }; + } + if (input.approvalCodes === undefined) return { kind: "checking" }; + if (!input.approvalCodes) return { kind: "update" }; + if (!input.canReadRelay) return { kind: "no-relay-read" }; + if (input.linkStateError !== null) return { kind: "error", message: input.linkStateError }; + const { linkState } = input; + if (linkState === null) return { kind: "checking" }; + // This machine reports its own tunnel and the probe proves it; the list speaks for saved ones. + const endpoint = !input.thisMachine && relay.status === "listed" ? relay.endpoint : undefined; + if (!isManagedTunnelActive(linkState, endpoint?.providerKind)) return { kind: "turn-on" }; + if (!input.thisMachine) { + if (relay.status === "loading") return { kind: "checking" }; + if (relay.status === "failed") return { kind: "error", message: "Could not reach T3 Connect." }; + if (endpoint === undefined) return { kind: "turn-on" }; + } + const { reachability } = input; + if (reachability === "checking") return { kind: "checking" }; + const mcpUrl = t3ConnectMcpUrl({ + thisMachine: input.thisMachine, + tunnelHostname: linkState.tunnelHostname, + relayEndpoint: endpoint, + }); + if (reachability?.status === "reachable" && mcpUrl !== null) return { kind: "open", mcpUrl }; + return { + kind: "offline", + reachability: reachability?.status === "unreachable" ? reachability : null, + }; +} + +/** + * What a failed check request leaves: `prior` is the link state from before it, `latest` a read + * after it (null when unread). The server may still have checked, so a result newer than `prior` + * counts. Otherwise only a later server check does; with nothing read at all, only a retry does. + */ +export function afterFailedCheck( + prior: EnvironmentCloudLinkStateResult | null, + latest: EnvironmentCloudLinkStateResult | null, +): { readonly result: EnvironmentConnectReachability | null; readonly since: string | null } { + const fresh = latest?.reachability; + const known = prior?.reachability; + if ( + fresh !== undefined && + prior !== null && + (known === undefined || fresh.checkedAt > known.checkedAt) + ) { + return { result: fresh, since: fresh.checkedAt }; + } + const baseline = latest ?? prior; + return { + result: null, + since: baseline === null ? null : (baseline.reachability?.checkedAt ?? ""), + }; +} diff --git a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx index 75e3c972ee797..f58bf7b1d1ce9 100644 --- a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx +++ b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx @@ -1,5 +1,5 @@ import { AUTH_SCOPE_OPTIONS as PAIRING_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions"; -import { PlusIcon, QrCodeIcon } from "lucide-react"; +import { PlugIcon, PlusIcon, QrCodeIcon } from "lucide-react"; import { type ReactNode, memo, useId, useState } from "react"; import { AuthAccessWriteScope, @@ -59,6 +59,7 @@ import { readEnvironmentScope } from "~/state/session"; import { useManagedPolicy, usePrimaryManagedPolicy } from "~/state/managedPolicy"; import { useAtomCommand } from "~/state/use-atom-command"; import { ManagedControl } from "../ManagedPolicy"; +import { openUseInAnotherApp } from "../mcp/UseInAnotherAppDialog"; import { ConnectionStatusDot } from "../ConnectionStatusDot"; import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows"; import { @@ -640,7 +641,11 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHead }; return ( -
+
+