The best way to control Claude Code, Codex and more from any computer or phone
feat(web,server): use T3 Code in another app (MCP) (#33196)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Nov 9, 2026 at 04:03 UTC
965ddc1d6caec14ad5adead211fcb4e3f1f6b030
49 files changed
+2201
-226
apps/server/src/auth/EnvironmentAuth.ts
+47
-10
@@ -1,6 +1,7 @@
1
import {
2
AuthAccessTokenType,
3
AuthAccessWriteScope,
4
+ AuthMcpClientAccess,
5
AuthOrchestrationOperateScope,
6
AuthStandardClientScopes,
7
type AuthAccessTokenResult,
@@ -9,7 +10,6 @@ import {
10
type AuthClientSession,
11
type AuthCreatePairingCredentialInput,
12
type AuthEnvironmentScope,
12
- type AuthMcpClientAccess,
13
type AuthPairingLink,
14
type AuthPairingCredentialResult,
15
type AuthSessionId,
@@ -48,6 +48,7 @@ import { DESKTOP_RENDERER_ORIGINS } from "../httpCors.ts";
48
import * as SqlitePersistence from "../persistence/Sqlite.ts";
49
import * as ManagedLimits from "../policy/managedLimits.ts";
50
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
51
+import { MCP_APPROVAL_SUBJECT_PREFIX } from "../persistence/AuthPairingLinks.ts";
52
import { requestUrl } from "../requestUrl.ts";
53
54
const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
@@ -488,6 +489,7 @@ export class EnvironmentAuth extends Context.Service<
489
readonly subject?: string;
490
readonly proofKeyThumbprint?: string;
491
readonly purpose?: "startup";
492
+ readonly mcpApproval?: AuthMcpClientAccess;
493
}) => Effect.Effect<
494
IssuedPairingLink,
495
ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError
@@ -559,11 +561,17 @@ export class EnvironmentAuth extends Context.Service<
561
},
562
ServerAuthInternalError
563
>;
562
- /** Spends a code covering all granted scopes. Rejects desktop grants and leaves refused proof-bound codes unspent. */
564
+ /**
565
+ * Spends a code covering all granted scopes and returns the level it approves. A level-bound
566
+ * code must name `access`. Rejects desktop grants and leaves refused codes unspent.
567
+ */
568
readonly consumeMcpApprovalCode: (
569
code: string,
570
access: AuthMcpClientAccess,
566
- ) => Effect.Effect<void, ServerAuthMcpApprovalCodeError | ServerAuthInternalError>;
571
+ ) => Effect.Effect<
572
+ AuthMcpClientAccess,
573
+ ServerAuthMcpApprovalCodeError | ServerAuthInternalError
574
+ >;
575
readonly authenticateBrowserSession: (
576
request: HttpServerRequest.HttpServerRequest,
577
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
@@ -918,6 +926,8 @@ export const make = Effect.gen(function* () {
926
readonly proofKeyThumbprint?: string;
927
readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
928
readonly requiredScopes?: ReadonlyArray<AuthEnvironmentScope>;
929
+ /** Only an agent sign-in opts in to spending a code issued for it. */
930
+ readonly mcpApproval?: AuthMcpClientAccess;
931
},
932
): Effect.Effect<
933
ResolvedBootstrapGrant,
@@ -1032,6 +1042,7 @@ export const make = Effect.gen(function* () {
1042
...(input?.label ? { label: input.label } : {}),
1043
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
1044
...(input?.purpose ? { purpose: input.purpose } : {}),
1045
+ ...(input?.mcpApproval ? { mcpApproval: input.mcpApproval } : {}),
1046
});
1047
return {
1048
id: issued.id,
@@ -1066,7 +1077,11 @@ export const make = Effect.gen(function* () {
1077
INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
1078
];
1079
return pairingLinks
1069
- .filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))
1080
+ .filter(
1081
+ (pairingLink) =>
1082
+ !excludedSubjects.includes(pairingLink.subject) &&
1083
+ !pairingLink.subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX),
1084
+ )
1085
.map((link) => ({ ...link, ...authScopeResponse(link.scopes) }))
1086
.toSorted(
1087
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
@@ -1132,11 +1147,17 @@ export const make = Effect.gen(function* () {
1147
1148
const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) =>
1149
createPairingLink({
1135
- scopes: input?.scopes ?? AuthStandardClientScopes,
1150
+ scopes: input?.access
1151
+ ? mcpClientScopes(input.access)
1152
+ : (input?.scopes ?? AuthStandardClientScopes),
1153
subject: "one-time-token",
1154
...(input?.label ? { label: input.label } : {}),
1155
+ ...(input?.access ? { mcpApproval: input.access } : {}),
1156
}).pipe(
1139
- Effect.map(toPairingCredential),
1157
+ Effect.map((issued) => ({
1158
+ ...toPairingCredential(issued),
1159
+ ...(input?.access ? { access: input.access } : {}),
1160
+ })),
1161
Effect.withSpan("EnvironmentAuth.issuePairingCredential"),
1162
);
1163
@@ -1361,7 +1382,10 @@ export const make = Effect.gen(function* () {
1382
code,
1383
access,
1384
) =>
1364
- resolveBootstrapGrant(code.trim(), { requiredScopes: mcpClientScopes(access) }).pipe(
1385
+ resolveBootstrapGrant(code.trim(), {
1386
+ requiredScopes: mcpClientScopes(access),
1387
+ mcpApproval: access,
1388
+ }).pipe(
1389
Effect.catchTags({
1390
ServerAuthInvalidCredentialError: () =>
1391
Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
@@ -1371,7 +1395,7 @@ export const make = Effect.gen(function* () {
1395
Effect.flatMap((grant) =>
1396
grant.method !== "one-time-token" && grant.method !== "reusable-dev-token"
1397
? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" }))
1374
- : Effect.void,
1398
+ : Effect.succeed(mcpApprovalLevel(grant.subject) ?? access),
1399
),
1400
Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"),
1401
);
@@ -1410,6 +1434,16 @@ export const make = Effect.gen(function* () {
1434
});
1435
});
1436
1437
+const isMcpClientAccess = Schema.is(AuthMcpClientAccess);
1438
+
1439
+/** The level an approval code's subject names, or undefined for any other code. */
1440
+const mcpApprovalLevel = (subject: string): AuthMcpClientAccess | undefined => {
1441
+ const level = subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX)
1442
+ ? subject.slice(MCP_APPROVAL_SUBJECT_PREFIX.length)
1443
+ : undefined;
1444
+ return isMcpClientAccess(level) ? level : undefined;
1445
+};
1446
+
1447
/** Subjects of sessions and links a pairing link created, keyed by how the client paired. */
1448
const LINK_PAIRED_SUBJECTS = { link: "one-time-token", connect: "cloud-connect" } as const;
1449
@@ -1440,8 +1474,11 @@ const revokePairedClientsThePolicyDisallows = Effect.fn(
1474
session.client.ipAddress !== undefined &&
1475
!isLocalLoopbackHost(session.client.ipAddress)),
1476
);
1443
- const links = (yield* stores.pairingLinks.listActive()).filter((link) =>
1444
- disallowed.has(link.subject),
1477
+ const links = (yield* stores.pairingLinks.listActive()).filter(
1478
+ (link) =>
1479
+ disallowed.has(link.subject) ||
1480
+ // Approval codes let an agent elsewhere sign in, as plain codes do.
1481
+ (!remoteAllowed && link.subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX)),
1482
);
1483
yield* Effect.forEach(sessions, (session) => stores.sessions.revoke(session.sessionId), {
1484
discard: true,
apps/server/src/auth/EnvironmentAuthAdmin.test.ts
+3
@@ -85,6 +85,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))(
85
const startupPhone = yield* startup("192.168.1.20");
86
const startupBrowser = yield* startup("127.0.0.1");
87
yield* environmentAuth.createPairingLink({ subject: "one-time-token" });
88
+ yield* environmentAuth.issuePairingCredential({ access: "auto" });
89
90
yield* EnvironmentAuth.make.pipe(
91
Effect.provide(
@@ -135,6 +136,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))(
136
subject: "one-time-token",
137
label: "CI phone",
138
});
139
+ // An app approval code is never listed.
140
+ yield* environmentAuth.issuePairingCredential({ access: "auto" });
141
const listedBeforeRevoke = yield* environmentAuth.listPairingLinks();
142
const revoked = yield* environmentAuth.revokePairingLink(created.id);
143
const listedAfterRevoke = yield* environmentAuth.listPairingLinks();
apps/server/src/auth/McpOAuth.test.ts
+86
-1
@@ -5,6 +5,7 @@ import {
5
AuthStandardClientScopes,
6
type AuthCreatePairingCredentialInput,
7
EnvironmentHttpApi,
8
+ MCP_PEER_LINK_SOFTWARE_ID,
9
mcpClientScopes,
10
} from "@t3tools/contracts";
11
import { expect, it } from "@effect/vitest";
@@ -53,7 +54,7 @@ const makeLayerRoutes = (capture: (auth: EnvironmentAuth.EnvironmentAuth["Servic
54
Layer.provide(
55
McpOAuthHttp.layer.pipe(
56
Layer.provide(McpOAuth.layer),
56
- Layer.provide(ServerSettings.layerTest()),
57
+ Layer.provide(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
58
),
59
),
60
Layer.provide(AuthHttp.layerAuthenticatedAuth),
@@ -509,6 +510,90 @@ it.live("a code minted with an access level's scopes approves that access", () =
510
),
511
);
512
513
+it.live("an app approval code approves only an app sign-in, at its own level", () =>
514
+ withRoutes((handler, auth) =>
515
+ Effect.gen(function* () {
516
+ const clientId = yield* registeredClientId(handler);
517
+ const params = authorizeParams(clientId);
518
+ const issued = yield* auth.issuePairingCredential({ access: "approval-required" });
519
+ expect(issued.access).toBe("approval-required");
520
+ const code = issued.credential;
521
+ expect(code).toMatch(/^SUPERVISED-[2-9A-HJ-NP-Z]{12}$/);
522
+
523
+ // Signing in a browser, a token exchange and linking all refuse it and leave it unspent.
524
+ const browser = yield* handler(
525
+ at("/api/auth/browser-session", {
526
+ method: "POST",
527
+ headers: { "content-type": "application/json" },
528
+ body: encodeJson({ credential: code }),
529
+ }),
530
+ );
531
+ expect(browser.status).toBe(401);
532
+ const exchanged = yield* auth
533
+ .exchangeBootstrapCredentialForAccessToken(code, undefined, { deviceType: "bot" })
534
+ .pipe(Effect.flip);
535
+ expect(exchanged._tag).toBe("ServerAuthInvalidCredentialError");
536
+ const peer = yield* handler(
537
+ at("/oauth/mcp/register", {
538
+ method: "POST",
539
+ headers: { "content-type": "application/json" },
540
+ body: encodeJson({
541
+ client_name: "Studio",
542
+ software_id: MCP_PEER_LINK_SOFTWARE_ID,
543
+ redirect_uris: [REDIRECT],
544
+ }),
545
+ }),
546
+ ).pipe(Effect.flatMap(json<{ client_id: string }>));
547
+ const linked = yield* decide(handler, authorizeParams(peer.client_id), {
548
+ _tag: "pairing-code",
549
+ access: "approval-required",
550
+ code,
551
+ });
552
+ expect(linked.status).toBe(400);
553
+
554
+ // Supervised and Auto share scopes, so only the code's own level may spend it.
555
+ const otherLevel = yield* decide(handler, params, {
556
+ _tag: "pairing-code",
557
+ access: "auto",
558
+ code,
559
+ });
560
+ expect(otherLevel.status).toBe(400);
561
+
562
+ const approved = yield* decide(handler, params, {
563
+ _tag: "pairing-code",
564
+ access: "approval-required",
565
+ code: code.toLowerCase(),
566
+ });
567
+ expect(approved.status).toBe(200);
568
+ const token = yield* handler(
569
+ at(
570
+ "/oauth/mcp/token",
571
+ form({
572
+ grant_type: "authorization_code",
573
+ code: new URL(approved.redirectTo!).searchParams.get("code")!,
574
+ redirect_uri: params.redirect_uri,
575
+ client_id: clientId,
576
+ code_verifier: verifier,
577
+ }),
578
+ ),
579
+ ).pipe(Effect.flatMap(json<{ access_token: string }>));
580
+ const signedIn = yield* auth.authenticateMcpClient(
581
+ HttpServerRequest.fromWeb(
582
+ at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }),
583
+ ),
584
+ );
585
+ expect(signedIn.access).toBe("approval-required");
586
+ expect(
587
+ (yield* decide(handler, params, {
588
+ _tag: "pairing-code",
589
+ access: "approval-required",
590
+ code,
591
+ })).status,
592
+ ).toBe(400);
593
+ }),
594
+ ),
595
+);
596
+
597
it.live("one-click approves only access the browser session holds the scopes for", () =>
598
withRoutes((handler, auth) =>
599
Effect.gen(function* () {
apps/server/src/auth/McpOAuth.ts
+11
-3
@@ -15,6 +15,7 @@ import {
15
AuthOrchestrationReadScope,
16
MCP_PEER_LINK_SOFTWARE_ID,
17
mcpClientScopes,
18
+ parseMcpApprovalCode,
19
type RuntimeMode,
20
} from "@t3tools/contracts";
21
import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
@@ -447,8 +448,15 @@ const make = Effect.gen(function* () {
448
449
const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) {
450
const { decision } = input;
451
+ let access = decision.access;
452
if (decision._tag === "pairing-code") {
451
- yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
453
+ // An approval code is for one app's sign-in, never for linking another environment.
454
+ if (input.authorization.client.peerLink && parseMcpApprovalCode(decision.code)) {
455
+ return yield* new McpOAuthPageError({
456
+ description: "Linking needs a plain pairing code, not an app approval code.",
457
+ });
458
+ }
459
+ access = yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
460
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
461
Effect.logError("MCP approval code check failed.", { cause }).pipe(
462
Effect.andThen(
@@ -473,10 +481,10 @@ const make = Effect.gen(function* () {
481
});
482
}
483
}
476
- const code = yield* mintCode(input.authorization, decision.access);
484
+ const code = yield* mintCode(input.authorization, access);
485
yield* Effect.logInfo("Approved an MCP client sign-in.", {
486
client: input.authorization.client.name,
479
- access: decision.access,
487
+ access,
488
method: decision._tag,
489
});
490
return redirectWith(input.authorization.redirectUri, {
apps/server/src/auth/PairingGrantStore.test.ts
+3
@@ -218,6 +218,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PairingGrantStor
218
Stream.runForEach((change) => Queue.offer(changes, change)),
219
Effect.forkScoped({ startImmediately: true }),
220
);
221
+ // An app approval code sends no update, issued or spent; the next belongs to a plain code.
222
+ const approval = yield* grants.issueOneTimeToken({ mcpApproval: "auto" });
223
+ yield* grants.consume(approval.credential, { mcpApproval: "auto" });
224
for (const input of [{}, { label: "Synthetic phone" }]) {
225
const issued = yield* grants.issueOneTimeToken(input);
226
const change = yield* Queue.take(changes);
apps/server/src/auth/PairingGrantStore.ts
+42
-21
@@ -1,7 +1,12 @@
1
import {
2
AuthStandardClientScopes,
3
type AuthEnvironmentScope,
4
+ type AuthMcpClientAccess,
5
type AuthPairingLink,
6
+ mcpApprovalCode,
7
+ PAIRING_CODE_ALPHABET,
8
+ PAIRING_CODE_LENGTH,
9
+ parseMcpApprovalCode,
10
type ServerAuthBootstrapMethod,
11
} from "@t3tools/contracts";
12
import {
@@ -215,6 +220,8 @@ export class PairingGrantStore extends Context.Service<
220
readonly label?: string;
221
readonly proofKeyThumbprint?: string;
222
readonly purpose?: "startup";
223
+ /** Issues a hidden `<LEVEL>-` code that only an agent sign-in at this level can spend. */
224
+ readonly mcpApproval?: AuthMcpClientAccess;
225
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
226
readonly listActive: () => Effect.Effect<
227
ReadonlyArray<AuthPairingLink>,
@@ -229,6 +236,8 @@ export class PairingGrantStore extends Context.Service<
236
readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
237
/** All scopes must be granted; requestedScopes only requires an overlap for OAuth. */
238
readonly requiredScopes?: ReadonlyArray<AuthEnvironmentScope>;
239
+ /** Also spends a code issued for an agent sign-in at this level; others refuse them. */
240
+ readonly mcpApproval?: AuthMcpClientAccess;
241
},
242
) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
243
}
@@ -252,13 +261,11 @@ type ConsumeResult =
261
const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
262
const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
263
const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
255
-const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
256
-const PAIRING_TOKEN_LENGTH = 12;
264
const PAIRING_TOKEN_REJECTION_LIMIT =
258
- Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;
265
+ Math.floor(256 / PAIRING_CODE_ALPHABET.length) * PAIRING_CODE_ALPHABET.length;
266
267
const PAIRING_TOKEN_PATTERN = new RegExp(
261
- `^[${PAIRING_TOKEN_ALPHABET}]{${PAIRING_TOKEN_LENGTH}}$`,
268
+ `^[${PAIRING_CODE_ALPHABET}]{${PAIRING_CODE_LENGTH}}$`,
269
"i",
270
);
271
@@ -270,9 +277,9 @@ const make = Effect.gen(function* () {
277
const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
278
const generatePairingToken = Effect.gen(function* () {
279
let credential = "";
273
- while (credential.length < PAIRING_TOKEN_LENGTH) {
280
+ while (credential.length < PAIRING_CODE_LENGTH) {
281
const bytes = yield* random
275
- .randomBytes(PAIRING_TOKEN_LENGTH)
282
+ .randomBytes(PAIRING_CODE_LENGTH)
283
.pipe(
284
Effect.mapError(
285
(cause) =>
@@ -283,8 +290,8 @@ const make = Effect.gen(function* () {
290
if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {
291
continue;
292
}
286
- credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!;
287
- if (credential.length === PAIRING_TOKEN_LENGTH) {
293
+ credential += PAIRING_CODE_ALPHABET[byte % PAIRING_CODE_ALPHABET.length]!;
294
+ if (credential.length === PAIRING_CODE_LENGTH) {
295
return credential;
296
}
297
}
@@ -391,7 +398,9 @@ const make = Effect.gen(function* () {
398
new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }),
399
),
400
);
394
- const credential = yield* generatePairingToken;
401
+ const token = yield* generatePairingToken;
402
+ const mcpApproval = input?.mcpApproval;
403
+ const credential = mcpApproval ? mcpApprovalCode(mcpApproval, token) : token;
404
const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
405
const ttl =
406
input?.ttl ??
@@ -405,7 +414,9 @@ const make = Effect.gen(function* () {
414
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
415
expiresAt,
416
};
408
- const subject = input?.subject ?? "one-time-token";
417
+ const subject = mcpApproval
418
+ ? `${AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX}${mcpApproval}`
419
+ : (input?.subject ?? "one-time-token");
420
yield* pairingLinks
421
.create({
422
id,
@@ -429,14 +440,17 @@ const make = Effect.gen(function* () {
440
}),
441
),
442
);
432
- yield* emitUpsert({
433
- id,
434
- scopes: input?.scopes ?? AuthStandardClientScopes,
435
- subject: input?.subject ?? "one-time-token",
436
- ...(input?.label ? { label: input.label } : {}),
437
- createdAt: now,
438
- expiresAt,
439
- });
443
+ // Approval codes stay out of the pairing links and QR codes that clients show.
444
+ if (!mcpApproval) {
445
+ yield* emitUpsert({
446
+ id,
447
+ scopes: input?.scopes ?? AuthStandardClientScopes,
448
+ subject,
449
+ ...(input?.label ? { label: input.label } : {}),
450
+ createdAt: now,
451
+ expiresAt,
452
+ });
453
+ }
454
return issued;
455
});
456
@@ -546,10 +560,10 @@ const make = Effect.gen(function* () {
560
return yield* seededResult.error;
561
}
562
549
- // Only credentials in the issued pairing-code format are case-insensitive.
563
+ // Only credentials in the issued pairing-code formats are case-insensitive.
564
const pairingCredential = PAIRING_TOKEN_PATTERN.test(credential)
565
? credential.toUpperCase()
552
- : credential;
566
+ : (parseMcpApprovalCode(credential)?.code ?? credential);
567
568
// Check scopes in the UPDATE so rejected requests cannot spend one-time links.
569
const consumed = yield* pairingLinks
@@ -560,13 +574,20 @@ const make = Effect.gen(function* () {
574
? { requestedScopes: input.requestedScopes }
575
: {}),
576
...(input?.requiredScopes !== undefined ? { requiredScopes: input.requiredScopes } : {}),
577
+ ...(input?.mcpApproval
578
+ ? {
579
+ mcpApprovalSubject: `${AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX}${input.mcpApproval}`,
580
+ }
581
+ : {}),
582
consumedAt: now,
583
now,
584
})
585
.pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
586
587
if (Option.isSome(consumed)) {
569
- yield* emitRemoved(consumed.value.id);
588
+ if (!consumed.value.subject.startsWith(AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX)) {
589
+ yield* emitRemoved(consumed.value.id);
590
+ }
591
return {
592
method: consumed.value.method,
593
scopes: consumed.value.scopes,
apps/server/src/auth/http.ts
+4
-1
@@ -17,6 +17,7 @@ import {
17
EnvironmentScopeRequiredError,
18
EnvironmentAuthenticatedAuth,
19
EnvironmentAuthenticatedPrincipal,
20
+ mcpClientScopes,
21
} from "@t3tools/contracts";
22
import type { AuthEnvironmentScope, DpopFailureReason } from "@t3tools/contracts";
23
import { parseOAuthScope } from "@t3tools/shared/oauthScope";
@@ -446,7 +447,9 @@ export const layer = HttpApiBuilder.group(
447
function* (args) {
448
yield* annotateEnvironmentRequest(args.endpoint.name);
449
const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
449
- const delegatedScopes = args.payload.scopes ?? AuthStandardClientScopes;
450
+ const delegatedScopes = args.payload.access
451
+ ? mcpClientScopes(args.payload.access)
452
+ : (args.payload.scopes ?? AuthStandardClientScopes);
453
if (
454
delegatedScopes.length === 0 ||
455
new Set<AuthEnvironmentScope>(delegatedScopes).size !== delegatedScopes.length
apps/server/src/cloud/CloudLink.lifecycle.test.ts
+10
-1
@@ -142,6 +142,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
142
readonly respondEffect?: Effect.Effect<Response>;
143
readonly getExisting?: CliTokenManager.CloudCliTokenManager["Service"]["getExisting"];
144
readonly latestReachability?: ConnectReachability.ConnectReachability["Service"]["latest"];
145
+ readonly connector?: ManagedEndpointRuntime.ConnectorFacts;
146
}
147
148
const writeLauncherState = (update: ServiceUpdateRecord) =>
@@ -208,7 +209,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
209
requestRecovery: () => Effect.void,
210
restartConnector: () => Effect.succeed(false),
211
tunnelConnected: Stream.empty,
211
- inspectConnector: Effect.succeed(null),
212
+ inspectConnector: Effect.succeed(harness.connector ?? null),
213
readinessChanged: Stream.empty,
214
withLinkStateLock: (effect) => effect,
215
}),
@@ -1079,12 +1080,20 @@ describe("releaseManagedTunnelOnShutdown", () => {
1080
expect(state.reachability?.status === "unreachable" && state.reachability.cause).not.toBe(
1081
"not_linked",
1082
);
1083
+ // The address shows before any check passes.
1084
+ expect(state.tunnelHostname).toBe("prod-abc.t3coderelay.com");
1085
}).pipe(
1086
provideReleaseHarness({
1087
store,
1088
applyConfigCalls: [],
1089
requests: [],
1090
latestReachability: Effect.succeedSome(notLinked),
1091
+ connector: {
1092
+ pid: 123,
1093
+ readyConnections: 0,
1094
+ hostname: "prod-abc.t3coderelay.com",
1095
+ protocol: null,
1096
+ },
1097
}),
1098
);
1099
});
apps/server/src/cloud/CloudLink.ts
+5
@@ -1283,6 +1283,10 @@ const make = Effect.gen(function* () {
1283
],
1284
{ concurrency: 8 },
1285
);
1286
+ // The hostname arrives once cloudflared connects, before any check passes.
1287
+ const connector = Option.isSome(endpointRuntimeConfig)
1288
+ ? yield* endpointRuntime.inspectConnector
1289
+ : null;
1290
// A not-linked check predates the stored tunnel config; the next check replaces it.
1291
const currentReachability = Option.filter(
1292
latestReachability,
@@ -1303,6 +1307,7 @@ const make = Effect.gen(function* () {
1307
holdWebhooksWhileOffline:
1308
Option.isSome(holdWebhooks) && bytesToString(holdWebhooks.value) === "true",
1309
...(Option.isSome(currentReachability) ? { reachability: currentReachability.value } : {}),
1310
+ ...(connector?.hostname ? { tunnelHostname: connector.hostname } : {}),
1311
} satisfies EnvironmentCloudLinkStateResult;
1312
});
1313
apps/server/src/cloud/http.test.ts
+18
-3
@@ -156,7 +156,18 @@ const linkProofClient = Effect.gen(function* () {
156
const payload = (yield* responseJson(response)) as { access_token: string };
157
return payload.access_token;
158
});
159
- return { post, exchange };
159
+ const linkableHere = (token: string, origin = NON_LOOPBACK_ORIGIN) =>
160
+ Effect.promise(() =>
161
+ handler(
162
+ new Request(`${origin}/api/connect/link-state`, {
163
+ headers: { authorization: `Bearer ${token}` },
164
+ }),
165
+ ),
166
+ ).pipe(
167
+ Effect.flatMap(responseJson),
168
+ Effect.map((state) => (state as { linkableHere?: boolean }).linkableHere),
169
+ );
170
+ return { post, exchange, linkableHere };
171
});
172
173
describe("link proof over a non-loopback desktop transport", () => {
@@ -195,12 +206,12 @@ describe("link proof over a non-loopback desktop transport", () => {
206
"does not pass desktop trust to a paired client or accept client-supplied provenance",
207
() =>
208
Effect.gen(function* () {
198
- const { post, exchange } = yield* linkProofClient;
209
+ const { post, exchange, linkableHere } = yield* linkProofClient;
210
const desktop = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
211
const paired = yield* post(
212
"/api/auth/pairing-token",
213
{
203
- scopes: ["relay:write"],
214
+ scopes: ["relay:read", "relay:write"],
215
label: "desktop-bootstrap",
216
subject: "desktop-bootstrap",
217
},
@@ -227,6 +238,10 @@ describe("link proof over a non-loopback desktop transport", () => {
238
LOOPBACK_ORIGIN,
239
);
240
expect(loopback.status).toBe(200);
241
+ // Clients offer Turn on only to the desktop's own session; SSH forwards look like loopback.
242
+ expect(yield* linkableHere(desktop)).toBe(true);
243
+ expect(yield* linkableHere(token)).toBe(false);
244
+ expect(yield* linkableHere(token, LOOPBACK_ORIGIN)).toBe(false);
245
}),
246
);
247
apps/server/src/cloud/http.ts
+7
-3
@@ -19,6 +19,7 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
19
import * as ManagedLimits from "../policy/managedLimits.ts";
20
import * as CloudLink from "./CloudLink.ts";
21
import * as ConnectReachability from "./ConnectReachability.ts";
22
+import { canLinkHere } from "./linkChecks.ts";
23
import type { RelayRequestError } from "./relayResponse.ts";
24
import { traceRelayRequest } from "./traceRelayRequest.ts";
25
@@ -129,9 +130,12 @@ export const layer = HttpApiBuilder.group(
130
),
131
)
132
.handle("linkState", () =>
132
- requireEnvironmentScope(AuthRelayReadScope).pipe(
133
- Effect.andThen(toHttpError(cloudLink.linkState())),
134
- ),
133
+ Effect.gen(function* () {
134
+ const principal = yield* requireEnvironmentScope(AuthRelayReadScope);
135
+ const state = yield* toHttpError(cloudLink.linkState());
136
+ const request = yield* HttpServerRequest.HttpServerRequest;
137
+ return { ...state, linkableHere: canLinkHere(request, principal.subject) };
138
+ }),
139
)
140
.handle("checkReachability", () =>
141
requireEnvironmentScope(AuthRelayReadScope).pipe(Effect.andThen(reachability.check)),
apps/server/src/cloud/linkChecks.ts
+16
@@ -79,6 +79,22 @@ export function parseManagedEndpointLocalOrigin(localOrigin: string) {
79
};
80
}
81
82
+/**
83
+ * Whether clients should offer to turn on T3 Connect over this session: only the desktop app's
84
+ * own bootstrap session, from any address (WSL answers on a distro IP), never through a proxy.
85
+ * A loopback address alone does not count, since SSH port forwards look like loopback too.
86
+ */
87
+export function canLinkHere(
88
+ request: HttpServerRequest.HttpServerRequest,
89
+ subject: string,
90
+): boolean {
91
+ return (
92
+ subject === "desktop-bootstrap" &&
93
+ requestAbsoluteUrl(request) !== null &&
94
+ !hasForwardedAuthorityHeaders(request)
95
+ );
96
+}
97
+
98
export function isAllowedEndpointOrigin(input: {
99
readonly origin: RelayManagedEndpointOrigin;
100
readonly requestUrl: string;
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -287,6 +287,7 @@ export const make = Effect.gen(function* () {
287
peerLinks: true,
288
mcpModeLimitHeader: true,
289
linkFence: true,
290
+ mcpApprovalCodes: true,
291
},
292
};
293
apps/server/src/persistence/AuthPairingLinks.ts
+13
@@ -16,6 +16,12 @@ import {
16
PersistenceSqlError,
17
} from "./Errors.ts";
18
19
+/**
20
+ * Subjects of codes that approve one agent sign-in at a set level, as `mcp-approval:<level>`.
21
+ * Only that sign-in may spend one, so every other use of a pairing code refuses them.
22
+ */
23
+export const MCP_APPROVAL_SUBJECT_PREFIX = "mcp-approval:";
24
+
25
export const AuthPairingLinkRecord = Schema.Struct({
26
id: Schema.String,
27
credential: Schema.String,
@@ -49,6 +55,8 @@ export const ConsumeAuthPairingLinkInput = Schema.Struct({
55
proofKeyThumbprint: Schema.NullOr(Schema.String),
56
requestedScopes: Schema.optionalKey(AuthEnvironmentScopes),
57
requiredScopes: Schema.optionalKey(AuthEnvironmentScopes),
58
+ /** Also spends a code with exactly this `mcp-approval:` subject. Others are always refused. */
59
+ mcpApprovalSubject: Schema.optionalKey(Schema.String),
60
consumedAt: Schema.DateTimeUtcFromString,
61
now: Schema.DateTimeUtcFromString,
62
});
@@ -167,6 +175,7 @@ export const make = Effect.gen(function* () {
175
proofKeyThumbprint,
176
requestedScopes,
177
requiredScopes,
178
+ mcpApprovalSubject,
179
consumedAt,
180
now,
181
}) =>
@@ -177,6 +186,10 @@ export const make = Effect.gen(function* () {
186
AND revoked_at IS NULL
187
AND consumed_at IS NULL
188
AND expires_at > ${now}
189
+ AND (
190
+ subject NOT LIKE ${`${MCP_APPROVAL_SUBJECT_PREFIX}%`}
191
+ OR subject = ${mcpApprovalSubject ?? null}
192
+ )
193
AND (
194
proof_key_thumbprint IS NULL
195
OR proof_key_thumbprint = ${proofKeyThumbprint}
apps/web/src/cloud/linkEnvironment.ts
+19
@@ -7,6 +7,7 @@ import type { HttpClient } from "effect/http";
7
import {
8
EnvironmentCloudEndpointUnavailableError,
9
type EnvironmentCloudLinkStateResult,
10
+ type EnvironmentConnectReachability,
11
EnvironmentHttpBadRequestError,
12
EnvironmentHttpConflictError,
13
EnvironmentHttpForbiddenError,
@@ -256,6 +257,24 @@ export const readCloudLinkState: (input: {
257
);
258
});
259
260
+/** Runs the environment's T3 Connect reachability check now; the link state then reports it. */
261
+export const checkCloudReachability: (input: {
262
+ readonly target: CloudLinkTarget;
263
+}) => Effect.Effect<EnvironmentConnectReachability, CloudEnvironmentLinkError, CloudLinkServices> =
264
+ Effect.fn("linkEnvironment.checkCloudReachability")(function* (input: {
265
+ readonly target: CloudLinkTarget;
266
+ }) {
267
+ return yield* connectRequest(
268
+ input.target,
269
+ {
270
+ method: "POST",
271
+ url: (urls) => urls.checkReachability(),
272
+ request: ({ client, headers }) => client.checkReachability({ headers }),
273
+ },
274
+ "Could not check T3 Connect.",
275
+ );
276
+ });
277
+
278
export const updateCloudPreferences: (input: {
279
readonly target: CloudLinkTarget;
280
readonly publishAgentActivity: boolean;
apps/web/src/cloud/linkEnvironmentAtoms.ts
+12
@@ -5,7 +5,9 @@ import {
5
6
import { connectionAtomRuntime } from "../connection/runtime";
7
import {
8
+ checkCloudReachability,
9
linkEnvironmentToCloud,
10
+ readCloudLinkState,
11
type CloudLinkMode,
12
type CloudLinkTarget,
13
unlinkEnvironmentFromCloud,
@@ -47,3 +49,13 @@ export const updateEnvironmentPreferences = createRuntimeCommand(connectionAtomR
49
readonly holdWebhooksWhileOffline?: boolean;
50
}) => updateCloudPreferences(input),
51
});
52
+
53
+export const checkReachability = createRuntimeCommand(connectionAtomRuntime, {
54
+ label: "web:cloud:check-reachability",
55
+ execute: (input: { readonly target: CloudLinkTarget }) => checkCloudReachability(input),
56
+});
57
+
58
+export const readLinkState = createRuntimeCommand(connectionAtomRuntime, {
59
+ label: "web:cloud:read-link-state",
60
+ execute: (input: { readonly target: CloudLinkTarget }) => readCloudLinkState(input),
61
+});
apps/web/src/cloud/t3ConnectState.ts
new
+69
@@ -0,0 +1,69 @@
1
+import type { EnvironmentCloudLinkStateResult } from "@t3tools/contracts";
2
+import type {
3
+ RelayManagedEndpoint,
4
+ RelayManagedEndpointProviderKind,
5
+} from "@t3tools/contracts/relay";
6
+
7
+// Require managed discovery: stale tunnel config after a publish-only switch causes endpoint_provider_not_managed.
8
+export function isManagedTunnelActive(
9
+ linkState: EnvironmentCloudLinkStateResult,
10
+ relayProviderKind: RelayManagedEndpointProviderKind | undefined,
11
+) {
12
+ const localManagedTunnel = linkState.managedTunnelActive ?? linkState.linked;
13
+ return (
14
+ linkState.linkRevoked !== true &&
15
+ localManagedTunnel &&
16
+ (relayProviderKind === undefined || relayProviderKind === "cloudflare_tunnel")
17
+ );
18
+}
19
+
20
+// The URL ends up in commands people paste into a shell, so only plain DNS names pass.
21
+const TUNNEL_HOSTNAME = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/i;
22
+
23
+/**
24
+ * An environment's MCP URL on its T3 Connect tunnel, or null. This machine reports its own
25
+ * tunnel hostname; a saved machine's comes from T3 Connect, and only a tunnel counts there,
26
+ * since a publish-only link registers its local address as `manual`.
27
+ */
28
+export function t3ConnectMcpUrl(input: {
29
+ readonly thisMachine: boolean;
30
+ readonly tunnelHostname: string | undefined;
31
+ readonly relayEndpoint: RelayManagedEndpoint | undefined;
32
+}): string | null {
33
+ const url = input.thisMachine
34
+ ? URL.parse(`https://${input.tunnelHostname ?? ""}`)
35
+ : input.relayEndpoint?.providerKind === "cloudflare_tunnel"
36
+ ? URL.parse(input.relayEndpoint.httpBaseUrl)
37
+ : null;
38
+ return url?.protocol === "https:" && TUNNEL_HOSTNAME.test(url.hostname)
39
+ ? `${url.origin}/mcp`
40
+ : null;
41
+}
42
+
43
+/** Where T3 Connect can be turned on for an environment: from here, only by policy, or on its host. */
44
+export type T3ConnectTurnOn =
45
+ | { readonly kind: "here" }
46
+ | { readonly kind: "policy"; readonly reason: string }
47
+ | { readonly kind: "on-host" };
48
+
49
+/**
50
+ * Settings and the MCP wizard share this, so a Turn on control shows only where linking works.
51
+ * `linkableHere` is the environment's own answer for this session (its link state).
52
+ */
53
+export function resolveT3ConnectTurnOn(input: {
54
+ readonly desktopApp: boolean;
55
+ readonly linkableHere: boolean;
56
+ readonly cloudConfigured: boolean;
57
+ readonly canReadRelay: boolean;
58
+ readonly canWriteRelay: boolean;
59
+ readonly connectDenial: string | undefined;
60
+}): T3ConnectTurnOn {
61
+ if (input.connectDenial !== undefined) return { kind: "policy", reason: input.connectDenial };
62
+ return input.desktopApp &&
63
+ input.linkableHere &&
64
+ input.cloudConfigured &&
65
+ input.canReadRelay &&
66
+ input.canWriteRelay
67
+ ? { kind: "here" }
68
+ : { kind: "on-host" };
69
+}
apps/web/src/cloud/useCloudLinkController.ts
+2
-20
@@ -1,14 +1,8 @@
1
import { useAtomValue } from "@effect/atom-react";
2
import { useAuth } from "@clerk/react";
3
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
4
-import {
5
- AuthRelayReadScope,
6
- AuthRelayWriteScope,
7
- type EnvironmentCloudLinkStateResult,
8
- type EnvironmentId,
9
-} from "@t3tools/contracts";
4
+import { AuthRelayReadScope, AuthRelayWriteScope, type EnvironmentId } from "@t3tools/contracts";
5
import { ManagedRelay } from "@t3tools/client-runtime/relay";
11
-import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";
6
import {
7
isAtomCommandInterrupted,
8
settlePromise,
@@ -32,6 +26,7 @@ import {
26
} from "./linkEnvironmentAtoms";
27
import { readCachedCloudLinkState, useCloudLinkState } from "./cloudLinkState";
28
import { resolveRelayClerkTokenOptions } from "./publicConfig";
29
+import { isManagedTunnelActive } from "./t3ConnectState";
30
31
export interface CloudLinkDesiredState {
32
readonly managedTunnel: boolean;
@@ -39,19 +34,6 @@ export interface CloudLinkDesiredState {
34
readonly holdWebhooksWhileOffline?: boolean;
35
}
36
42
-// Require managed discovery: stale tunnel config after a publish-only switch causes endpoint_provider_not_managed.
43
-function isManagedTunnelActive(
44
- linkState: EnvironmentCloudLinkStateResult,
45
- relayProviderKind: RelayManagedEndpointProviderKind | undefined,
46
-) {
47
- const localManagedTunnel = linkState.managedTunnelActive ?? linkState.linked;
48
- return (
49
- linkState.linkRevoked !== true &&
50
- localManagedTunnel &&
51
- (relayProviderKind === undefined || relayProviderKind === "cloudflare_tunnel")
52
- );
53
-}
54
-
37
const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError);
38
const isManagedRelayClientError = Schema.is(ManagedRelay.ManagedRelayClientError);
39
apps/web/src/cloud/useT3ConnectTurnOn.ts
new
+30
@@ -0,0 +1,30 @@
1
+import {
2
+ AuthRelayReadScope,
3
+ AuthRelayWriteScope,
4
+ type EnvironmentId,
5
+ managedCapabilityDenial,
6
+} from "@t3tools/contracts";
7
+
8
+import { isElectron } from "../env";
9
+import { useManagedPolicy } from "../state/managedPolicy";
10
+import { useEnvironmentScope } from "../state/session";
11
+import { useCloudLinkState } from "./cloudLinkState";
12
+import { hasCloudPublicConfig } from "./publicConfig";
13
+import { resolveT3ConnectTurnOn } from "./t3ConnectState";
14
+
15
+/** Whether this client can turn on T3 Connect for `environmentId`, and if not, why. */
16
+export function useT3ConnectTurnOn(environmentId: EnvironmentId | null) {
17
+ const canReadRelay = useEnvironmentScope(environmentId, AuthRelayReadScope);
18
+ const canWriteRelay = useEnvironmentScope(environmentId, AuthRelayWriteScope);
19
+ const connectDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "connect");
20
+ const linkState = useCloudLinkState(environmentId).data;
21
+ return resolveT3ConnectTurnOn({
22
+ desktopApp: isElectron,
23
+ // Unknown while loading and on older servers, which keep today's switch in Settings.
24
+ linkableHere: linkState?.linkableHere ?? true,
25
+ cloudConfigured: hasCloudPublicConfig(),
26
+ canReadRelay,
27
+ canWriteRelay,
28
+ connectDenial,
29
+ });
30
+}
apps/web/src/components/CommandPalette.tsx
+30
@@ -73,6 +73,7 @@ import {
73
MonitorIcon,
74
PinIcon,
75
PinOffIcon,
76
+ PlugIcon,
77
SquarePenIcon,
78
TextSearchIcon,
79
UserPlusIcon,
@@ -247,6 +248,7 @@ import { ProjectFilePicker } from "./files/ProjectFilePicker";
248
import { openLinkPullRequestDialog } from "./pullRequest/LinkPullRequestDialog";
249
import { canShareWithGuestAtom } from "./chat/guestShareAvailability";
250
import { openGuestShareDialog } from "./chat/guestShareDialogState";
251
+import { openUseInAnotherApp } from "./mcp/UseInAnotherAppDialog";
252
import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";
253
import { settingsForThisPlatform, SETTINGS_SECTION_LABELS } from "./settings/settingsSearch";
254
import { primaryServerKeybindingsAtom } from "../state/server";
@@ -1602,6 +1604,34 @@ function OpenCommandPaletteDialog(props: {
1604
});
1605
}
1606
1607
+ actionItems.push({
1608
+ kind: "action",
1609
+ value: "action:use-in-another-app",
1610
+ searchTerms: [
1611
+ "mcp",
1612
+ "connector",
1613
+ "another app",
1614
+ "poke",
1615
+ "claude",
1616
+ "chatgpt",
1617
+ "grok",
1618
+ "muse",
1619
+ "instinct",
1620
+ "openclaw",
1621
+ "hermes",
1622
+ ],
1623
+ title: "Use T3 Code in another app (MCP)",
1624
+ icon: <PlugIcon className={ITEM_ICON_CLASS} />,
1625
+ run: async () => {
1626
+ openUseInAnotherApp(
1627
+ currentProjectEnvironmentId ??
1628
+ (paletteRouteTarget?.kind === "server"
1629
+ ? paletteRouteTarget.threadRef.environmentId
1630
+ : null),
1631
+ );
1632
+ },
1633
+ });
1634
+
1635
actionItems.push({
1636
kind: "action",
1637
value: "action:usage",
apps/web/src/components/auth/ConnectAgentSurface.logic.test.ts
+35
-5
@@ -1,13 +1,43 @@
1
import { expect, it } from "vite-plus/test";
2
-import { RuntimeMode } from "@t3tools/contracts";
2
+import { AuthMcpClientAccess, RuntimeMode } from "@t3tools/contracts";
3
4
-import { resolveMcpAccess } from "./ConnectAgentSurface.logic";
4
+import { resolveApprovalDecision, resolveMcpAccess } from "./ConnectAgentSurface.logic";
5
6
it.each(RuntimeMode.literals)("keeps MCP access within the %s policy ceiling", (maxRuntimeMode) => {
7
const ceiling = { organization: "Example", maxRuntimeMode };
8
- expect(resolveMcpAccess("auto", ceiling)).toBe(
8
+ expect(resolveMcpAccess("auto", ceiling, false)).toBe(
9
maxRuntimeMode === "full-access" ? "auto" : maxRuntimeMode,
10
);
11
- expect(resolveMcpAccess("read-only", ceiling)).toBe("read-only");
12
- expect(resolveMcpAccess("approval-required", ceiling)).toBe("approval-required");
11
+ expect(resolveMcpAccess("read-only", ceiling, false)).toBe("read-only");
12
+ expect(resolveMcpAccess("approval-required", ceiling, false)).toBe("approval-required");
13
+});
14
+
15
+it("checks a typed code even in a signed-in browser, and approves without one at Read only", () => {
16
+ const signedOut = {
17
+ clientName: "Poke",
18
+ redirectHost: "poke.com",
19
+ environmentHost: "prod-a1.t3coderelay.com",
20
+ };
21
+ const details = { ...signedOut, csrfToken: "csrf", oneClickAccess: AuthMcpClientAccess.literals };
22
+ const access = resolveMcpAccess(null, undefined, false);
23
+
24
+ // A typed code starts at Auto, and an expired one must fail rather than fall back to this session.
25
+ expect(
26
+ resolveApprovalDecision({
27
+ code: " 7K2P9QXR4MZT ",
28
+ access: resolveMcpAccess(null, undefined, true),
29
+ details,
30
+ }),
31
+ ).toEqual({ _tag: "pairing-code", access: "auto", code: "7K2P9QXR4MZT" });
32
+ expect(resolveApprovalDecision({ code: "auto-q8rz3nwd5ktc", access, details })).toEqual({
33
+ _tag: "pairing-code",
34
+ access: "auto",
35
+ code: "auto-q8rz3nwd5ktc",
36
+ });
37
+ expect(resolveApprovalDecision({ code: "", access, details })).toEqual({
38
+ _tag: "browser-session",
39
+ access: "read-only",
40
+ csrfToken: "csrf",
41
+ });
42
+ expect(resolveApprovalDecision({ code: "", access, details: signedOut })).toBeNull();
43
});
apps/web/src/components/auth/ConnectAgentSurface.logic.ts
+33
-2
@@ -1,16 +1,47 @@
1
import {
2
+ type AuthMcpApprovalDecision,
3
type AuthMcpApprovalDetails,
4
type AuthMcpClientAccess,
5
isRuntimeModeAbove,
6
+ parseMcpApprovalCode,
7
} from "@t3tools/contracts";
8
9
+/**
10
+ * The picker's access, lowered to a managed ceiling: the user's choice, else Auto for a typed
11
+ * code, else Read only, since approving without a code says nothing about what the user wants.
12
+ */
13
export function resolveMcpAccess(
8
- access: AuthMcpClientAccess,
14
+ requested: AuthMcpClientAccess | null,
15
ceiling: AuthMcpApprovalDetails["runtimeModeCeiling"],
10
-) {
16
+ hasCode: boolean,
17
+): AuthMcpClientAccess {
18
+ const access = requested ?? (hasCode ? "auto" : "read-only");
19
return access !== "read-only" &&
20
ceiling !== undefined &&
21
isRuntimeModeAbove(access, ceiling.maxRuntimeMode)
22
? ceiling.maxRuntimeMode
23
: access;
24
}
25
+
26
+/**
27
+ * What Approve sends. A typed code is always checked as a code, even when the browser's
28
+ * session could approve, and a level-bound code sends its own level. Null: nothing to send.
29
+ */
30
+export function resolveApprovalDecision(input: {
31
+ readonly code: string;
32
+ readonly access: AuthMcpClientAccess;
33
+ readonly details: AuthMcpApprovalDetails;
34
+}): Exclude<AuthMcpApprovalDecision, { readonly _tag: "deny" }> | null {
35
+ const code = input.code.trim();
36
+ if (code.length > 0) {
37
+ return {
38
+ _tag: "pairing-code",
39
+ access: parseMcpApprovalCode(code)?.access ?? input.access,
40
+ code,
41
+ };
42
+ }
43
+ const { csrfToken, oneClickAccess } = input.details;
44
+ return csrfToken !== undefined && (oneClickAccess ?? []).includes(input.access)
45
+ ? { _tag: "browser-session", access: input.access, csrfToken }
46
+ : null;
47
+}
apps/web/src/components/auth/ConnectAgentSurface.tsx
+91
-75
@@ -6,6 +6,7 @@ import {
6
AuthMcpAuthorizationRequest,
7
isRuntimeModeAbove,
8
managedRuntimeModeCeilingMessage,
9
+ parseMcpApprovalCode,
10
} from "@t3tools/contracts";
11
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
12
import { isLoopbackHost } from "@t3tools/shared/preview";
@@ -18,7 +19,7 @@ import { type ReactNode, useEffect, useState } from "react";
19
import { PrimaryEnvironmentHttpClient } from "~/environments/primary/httpClient";
20
import { runPrimaryHttp } from "~/lib/runtime";
21
import { cn } from "~/lib/utils";
21
-import { resolveMcpAccess } from "./ConnectAgentSurface.logic";
22
+import { resolveApprovalDecision, resolveMcpAccess } from "./ConnectAgentSurface.logic";
23
import { runtimeModeConfig } from "../chat/runtimeModeConfig";
24
import { Alert, AlertDescription } from "../ui/alert";
25
import { Button } from "../ui/button";
@@ -85,20 +86,16 @@ function readAuthorizationRequest(): AuthMcpAuthorizationRequest {
86
return decodeAuthorizationRequest(Object.fromEntries(new URL(window.location.href).searchParams));
87
}
88
88
-/** Sessions can grant only scopes they hold. */
89
-function oneClickApproves(details: AuthMcpApprovalDetails, access: AuthMcpClientAccess) {
90
- return details.csrfToken !== undefined && (details.oneClickAccess ?? []).includes(access);
91
-}
92
-
89
export function ConnectAgentSurface() {
90
const [authorization] = useState(readAuthorizationRequest);
91
const [loaded, setLoaded] = useState<Loaded>({ status: "loading" });
96
- const [requestedAccess, setAccess] = useState<AuthMcpClientAccess>("auto");
92
+ const [requestedAccess, setAccess] = useState<AuthMcpClientAccess | null>(null);
93
+ const [pairingCode, setPairingCode] = useState("");
94
const access = resolveMcpAccess(
95
requestedAccess,
96
loaded.status === "ready" ? loaded.details.runtimeModeCeiling : undefined,
97
+ pairingCode.trim().length > 0,
98
);
101
- const [pairingCode, setPairingCode] = useState("");
99
const [errorMessage, setErrorMessage] = useState("");
100
const [pending, setPending] = useState<"approve" | "deny" | null>(null);
101
@@ -126,15 +123,13 @@ export function ConnectAgentSurface() {
123
124
const decide = async (choice: "approve" | "deny") => {
125
if (loaded.status !== "ready") return;
129
- setPending(choice);
130
- setErrorMessage("");
131
- const { csrfToken } = loaded.details;
132
- const decision: AuthMcpApprovalDecision =
126
+ const decision: AuthMcpApprovalDecision | null =
127
choice === "deny"
128
? { _tag: "deny" }
135
- : csrfToken !== undefined && oneClickApproves(loaded.details, access)
136
- ? { _tag: "browser-session", access, csrfToken }
137
- : { _tag: "pairing-code", access, code: pairingCode.trim() };
129
+ : resolveApprovalDecision({ code: pairingCode, access, details: loaded.details });
130
+ if (decision === null) return;
131
+ setPending(choice);
132
+ setErrorMessage("");
133
const answer = await runApproval((client) =>
134
client.mcpOAuth.decision({ payload: { authorization, decision } }),
135
);
@@ -170,8 +165,10 @@ export function ConnectAgentSurface() {
165
}
166
167
const { details } = loaded;
173
- const oneClick = oneClickApproves(details, access);
174
- const canApprove = pending === null && (oneClick || pairingCode.trim().length > 0);
168
+ const canApprove =
169
+ pending === null && resolveApprovalDecision({ code: pairingCode, access, details }) !== null;
170
+ // A code from "Use T3 Code in another app" names its level, so the page does not ask again.
171
+ const codeAccess = parseMcpApprovalCode(pairingCode)?.access;
172
173
return (
174
<StandalonePage>
@@ -184,20 +181,23 @@ export function ConnectAgentSurface() {
181
</>
182
}
183
/>
187
- <p className="mt-2 text-xs text-muted-foreground">
188
- {redirectsToThisComputer(details.redirectHost) ? (
189
- <>
190
- The name is chosen by the agent. Approval returns to {details.redirectHost} on the
191
- computer that opened this page. Only approve a sign-in you just started.
192
- </>
193
- ) : (
194
- <>
195
- The name is chosen by the agent. Approval gives access to whoever runs{" "}
196
- <span className="font-medium text-foreground">{details.redirectHost}</span>. Only
197
- approve a sign-in you just started there.
198
- </>
199
- )}
200
- </p>
184
+ <dl className="mt-4 grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1 text-sm">
185
+ <dt className="text-muted-foreground">App</dt>
186
+ <dd className="min-w-0 break-words">
187
+ {details.clientName} <span className="text-muted-foreground">· name set by the app</span>
188
+ </dd>
189
+ <dt className="text-muted-foreground">Access goes to</dt>
190
+ <dd className="min-w-0 break-words font-medium">
191
+ {details.redirectHost}
192
+ {redirectsToThisComputer(details.redirectHost) ? (
193
+ <span className="font-normal text-muted-foreground">
194
+ {" "}
195
+ on the computer that opened this page
196
+ </span>
197
+ ) : null}
198
+ </dd>
199
+ </dl>
200
+ <p className="mt-2 text-xs text-muted-foreground">Only approve a sign-in you just started.</p>
201
202
<form
203
className="mt-6 space-y-5"
@@ -207,49 +207,54 @@ export function ConnectAgentSurface() {
207
}}
208
>
209
<div className="space-y-2">
210
- <span id="connect-agent-access-label" className="text-sm font-medium">
211
- What it may do
212
- </span>
213
- <RadioGroup
214
- aria-labelledby="connect-agent-access-label"
215
- value={access}
216
- onValueChange={(value) => setAccess(value as AuthMcpClientAccess)}
217
- >
218
- {AuthMcpClientAccess.literals.map((option) => (
219
- <AccessOption
220
- key={option}
221
- access={option}
222
- selected={option === access}
223
- managedReason={ceilingReason(details, option)}
224
- />
225
- ))}
226
- </RadioGroup>
210
+ <label className="text-sm font-medium" htmlFor="connect-agent-pairing-code">
211
+ Sign-in code
212
+ </label>
213
+ <Input
214
+ id="connect-agent-pairing-code"
215
+ autoCapitalize="none"
216
+ autoComplete="one-time-code"
217
+ autoCorrect="off"
218
+ disabled={pending !== null}
219
+ nativeInput
220
+ onChange={(event) => setPairingCode(event.currentTarget.value)}
221
+ placeholder="Paste a code"
222
+ spellCheck={false}
223
+ value={pairingCode}
224
+ />
225
<p className="text-xs text-muted-foreground">
228
- Beyond read only, it can start, message and stop threads, and none of them can run with
229
- more than the mode you pick.
226
+ Get one from Use T3 Code in another app (MCP), Settings → Sharing & access, or{" "}
227
+ <code>t3 auth pairing create</code> on this machine.
228
</p>
229
</div>
230
233
- {oneClick ? null : (
231
+ {codeAccess ? (
232
+ <p className="text-sm">
233
+ <span className="text-muted-foreground">Access</span>{" "}
234
+ <span className="font-medium">{accessConfig[codeAccess].label}</span>
235
+ </p>
236
+ ) : (
237
<div className="space-y-2">
235
- <label className="text-sm font-medium" htmlFor="connect-agent-pairing-code">
236
- Pairing code
237
- </label>
238
- <Input
239
- id="connect-agent-pairing-code"
240
- autoCapitalize="none"
241
- autoComplete="one-time-code"
242
- autoCorrect="off"
243
- disabled={pending !== null}
244
- nativeInput
245
- onChange={(event) => setPairingCode(event.currentTarget.value)}
246
- placeholder="Paste a one-time pairing code"
247
- spellCheck={false}
248
- value={pairingCode}
249
- />
238
+ <span id="connect-agent-access-label" className="text-sm font-medium">
239
+ What it may do
240
+ </span>
241
+ <RadioGroup
242
+ aria-labelledby="connect-agent-access-label"
243
+ value={access}
244
+ onValueChange={(value) => setAccess(value as AuthMcpClientAccess)}
245
+ >
246
+ {AuthMcpClientAccess.literals.map((option) => (
247
+ <AccessOption
248
+ key={option}
249
+ access={option}
250
+ selected={option === access}
251
+ disabledReason={ceilingReason(details, option)}
252
+ />
253
+ ))}
254
+ </RadioGroup>
255
<p className="text-xs text-muted-foreground">
251
- Create one in Settings → Sharing & access, or run <code>t3 auth pairing create</code>{" "}
252
- on this machine.
256
+ Beyond read only, it can start, message and stop threads, and none of them can run
257
+ with more than the mode you pick.
258
</p>
259
</div>
260
)}
@@ -262,7 +267,11 @@ export function ConnectAgentSurface() {
267
268
<div className="flex flex-wrap gap-2">
269
<Button disabled={!canApprove} type="submit">
265
- {pending === "approve" ? "Approving…" : "Approve"}
270
+ {pending === "approve"
271
+ ? "Approving…"
272
+ : codeAccess
273
+ ? `Approve ${accessConfig[codeAccess].label}`
274
+ : "Approve"}
275
</Button>
276
<Button
277
disabled={pending !== null}
@@ -298,20 +307,25 @@ function ceilingReason(details: AuthMcpApprovalDetails, access: AuthMcpClientAcc
307
: managedRuntimeModeCeilingMessage(ceiling.organization, ceiling.maxRuntimeMode);
308
}
309
301
-function AccessOption({
310
+/** One access level in a radio group; `description` replaces the level's own, null hides it. */
311
+export function AccessOption({
312
access,
313
selected,
304
- managedReason,
314
+ disabledReason,
315
+ description,
316
}: {
317
readonly access: AuthMcpClientAccess;
318
readonly selected: boolean;
308
- readonly managedReason: string | undefined;
319
+ readonly disabledReason: string | undefined;
320
+ readonly description?: string | null;
321
}) {
310
- const { label, description, icon: Icon } = accessConfig[access];
322
+ const { label, icon: Icon } = accessConfig[access];
323
+ const detail =
324
+ disabledReason ?? (description === undefined ? accessConfig[access].description : description);
325
return (
326
<RadioPrimitive.Root
327
value={access}
314
- disabled={managedReason !== undefined}
328
+ disabled={disabledReason !== undefined}
329
className={cn(
330
"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]",
331
"focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
@@ -329,7 +343,9 @@ function AccessOption({
343
/>
344
<span className="min-w-0">
345
<span className="block text-sm font-medium text-foreground">{label}</span>
332
- <span className="block text-xs text-muted-foreground">{managedReason ?? description}</span>
346
+ {detail === null ? null : (
347
+ <span className="block text-xs text-muted-foreground">{detail}</span>
348
+ )}
349
</span>
350
</RadioPrimitive.Root>
351
);
apps/web/src/components/mcp/UseInAnotherAppDialog.tsx
new
+817
@@ -0,0 +1,817 @@
1
+import { useAuth } from "@clerk/react";
2
+import { useAtomValue } from "@effect/atom-react";
3
+import { offersLinkedEnvironments } from "@t3tools/client-runtime/link-request";
4
+import {
5
+ AuthAccessWriteScope,
6
+ AuthMcpClientAccess,
7
+ AuthRelayReadScope,
8
+ type EnvironmentConnectReachability,
9
+ type EnvironmentId,
10
+ managedCapabilityDenial,
11
+ managedRuntimeModeDenial,
12
+ mcpClientScopes,
13
+ sessionGrantsScope,
14
+} from "@t3tools/contracts";
15
+import { useNavigate } from "@tanstack/react-router";
16
+import { Check, Copy } from "lucide";
17
+import * as Option from "effect/Option";
18
+import { Atom } from "effect/reactivity";
19
+import * as Result from "effect/Result";
20
+import { type ReactNode, useEffect, useEffectEvent, useState } from "react";
21
+
22
+import { checkReachability, readLinkState } from "~/cloud/linkEnvironmentAtoms";
23
+import { isManagedTunnelActive } from "~/cloud/t3ConnectState";
24
+import { hasCloudPublicConfig } from "~/cloud/publicConfig";
25
+import { readCachedCloudLinkState } from "~/cloud/cloudLinkState";
26
+import { useCloudLinkController } from "~/cloud/useCloudLinkController";
27
+import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
28
+import { isElectron } from "~/env";
29
+import { useT3ConnectTurnOn } from "~/cloud/useT3ConnectTurnOn";
30
+import { useCopyToClipboard, writeTextToClipboard } from "~/hooks/useCopyToClipboard";
31
+import { useNowSecond } from "~/hooks/useNowSecond";
32
+import { readLocalApi } from "~/localApi";
33
+import { appAtomRegistry } from "~/rpc/atomRegistry";
34
+import {
35
+ type EnvironmentPresentation,
36
+ useEnvironmentIdentities,
37
+ usePrimaryEnvironmentId,
38
+} from "~/state/environments";
39
+import { useManagedPolicy } from "~/state/managedPolicy";
40
+import { mintMcpApprovalCodeOn } from "~/state/peerPairingCode";
41
+import { peerLinkEnvironment } from "~/state/peerLinks";
42
+import { useEnvironmentQuery } from "~/state/query";
43
+import { relayEnvironmentDiscovery } from "~/state/relay";
44
+import { useEnvironmentScope, useEnvironmentSessionState } from "~/state/session";
45
+import { useAtomCommand } from "~/state/use-atom-command";
46
+import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";
47
+import { CommandBlock } from "../CommandBlock";
48
+import { MorphIcon } from "../MorphIcon";
49
+import { AccessOption, accessConfig } from "../auth/ConnectAgentSurface";
50
+import { useAccessEnvironment } from "../settings/useAccessEnvironment";
51
+import { Button } from "../ui/button";
52
+import { Dialog } from "../ui/dialog";
53
+import { RadioGroup } from "../ui/radio-group";
54
+import { Spinner } from "../ui/spinner";
55
+import { toastManager } from "../ui/toast";
56
+import { WizardFooter, WizardHeader, WizardPanel, WizardPopup, WizardSteps } from "../ui/wizard";
57
+import { afterFailedCheck, resolveMcpGate } from "./mcpGate";
58
+import { MCP_APPS, type McpApp, mcpHandoffAction, OTHER_MCP_APP_STEPS } from "./mcpApps";
59
+
60
+const requestAtom = Atom.make<{ readonly environmentId: EnvironmentId | null } | null>(null).pipe(
61
+ Atom.keepAlive,
62
+ Atom.withLabel("mcp:use-in-another-app"),
63
+);
64
+
65
+/** Opens the wizard for `environmentId`, or for the one Sharing & access picks when null. */
66
+export function openUseInAnotherApp(environmentId: EnvironmentId | null): void {
67
+ appAtomRegistry.set(requestAtom, { environmentId });
68
+}
69
+
70
+const close = () => appAtomRegistry.set(requestAtom, null);
71
+
72
+/** Hosted once at the root, so Cmd-K and Settings can open it from anywhere. */
73
+export function UseInAnotherAppDialogHost() {
74
+ const request = useAtomValue(requestAtom);
75
+ return request === null ? null : <UseInAnotherAppDialog requested={request.environmentId} />;
76
+}
77
+
78
+function UseInAnotherAppDialog({ requested }: { readonly requested: EnvironmentId | null }) {
79
+ const { environment, label } = useAccessEnvironment(requested);
80
+ const title = `Use T3 Code in another app (MCP) · ${label ?? "T3 Code"}`;
81
+ return (
82
+ <Dialog open onOpenChange={(open) => (open ? undefined : close())}>
83
+ <WizardPopup>
84
+ {environment !== null && hasCloudPublicConfig() ? (
85
+ <Wizard key={environment.environmentId} environment={environment} title={title} />
86
+ ) : (
87
+ <>
88
+ <WizardHeader title={title} />
89
+ <WizardPanel>
90
+ <GateMessage
91
+ title={
92
+ environment === null
93
+ ? "Connect to an environment first."
94
+ : "T3 Connect is not available in this build."
95
+ }
96
+ />
97
+ </WizardPanel>
98
+ </>
99
+ )}
100
+ </WizardPopup>
101
+ </Dialog>
102
+ );
103
+}
104
+
105
+const STEPS = ["App", "Access", "Connect"] as const;
106
+type Step = 0 | 1 | 2;
107
+type Choice = McpApp | "other";
108
+
109
+function Wizard({
110
+ environment,
111
+ title,
112
+}: {
113
+ readonly environment: EnvironmentPresentation;
114
+ readonly title: string;
115
+}) {
116
+ const gate = useGate(environment);
117
+ const levels = useGrantableLevels(environment);
118
+ const [step, setStep] = useState<Step>(0);
119
+ const [choice, setChoice] = useState<Choice | null>(null);
120
+ const [picked, setPicked] = useState<AuthMcpClientAccess | null>(null);
121
+ const access = picked ?? DEFAULT_LEVELS.find((level) => levels.get(level) === undefined) ?? null;
122
+ const open = gate.gate.kind === "open";
123
+ const appName = choice === null || choice === "other" ? "the app" : choice.name;
124
+ return (
125
+ <>
126
+ <WizardHeader title={title}>
127
+ {open ? (
128
+ <WizardSteps
129
+ steps={STEPS}
130
+ currentStep={step}
131
+ isStepDisabled={(index) => index > step}
132
+ onStepChange={(index) => setStep(index as Step)}
133
+ />
134
+ ) : null}
135
+ </WizardHeader>
136
+ <WizardPanel>
137
+ {gate.gate.kind !== "open" ? (
138
+ <GateScreen environment={environment} gate={gate} />
139
+ ) : step === 0 ? (
140
+ <AppStep choice={choice} onChoose={setChoice} />
141
+ ) : step === 1 ? (
142
+ <section className="space-y-3">
143
+ <h3 className="text-sm font-medium">What can {appName} do?</h3>
144
+ <RadioGroup
145
+ aria-label={`What can ${appName} do?`}
146
+ value={access}
147
+ onValueChange={(value) => setPicked(value as AuthMcpClientAccess)}
148
+ >
149
+ {AuthMcpClientAccess.literals.map((level) => (
150
+ <AccessOption
151
+ key={level}
152
+ access={level}
153
+ selected={level === access}
154
+ disabledReason={levels.get(level)}
155
+ description={
156
+ level === "full-access" ? "Runs commands and edits files without asking" : null
157
+ }
158
+ />
159
+ ))}
160
+ </RadioGroup>
161
+ </section>
162
+ ) : choice !== null && access !== null ? (
163
+ <ConnectStep
164
+ environment={environment}
165
+ mcpUrl={gate.gate.mcpUrl}
166
+ choice={choice}
167
+ access={access}
168
+ />
169
+ ) : null}
170
+ </WizardPanel>
171
+ {open ? (
172
+ <WizardFooter
173
+ leading={step === 2 ? <ManageAccessButton environment={environment} /> : undefined}
174
+ >
175
+ {step === 1 ? (
176
+ <Button variant="outline" onClick={() => setStep(0)}>
177
+ Back
178
+ </Button>
179
+ ) : null}
180
+ {step === 2 ? (
181
+ <Button onClick={close}>Done</Button>
182
+ ) : (
183
+ <Button
184
+ disabled={step === 0 ? choice === null : access === null}
185
+ onClick={() => setStep(step === 0 ? 1 : 2)}
186
+ >
187
+ Next
188
+ </Button>
189
+ )}
190
+ </WizardFooter>
191
+ ) : null}
192
+ </>
193
+ );
194
+}
195
+
196
+/** The level the Access step starts at: Auto, else the next one down that can be granted. */
197
+const DEFAULT_LEVELS: readonly AuthMcpClientAccess[] = [
198
+ "auto",
199
+ "auto-accept-edits",
200
+ "approval-required",
201
+ "read-only",
202
+];
203
+
204
+/** Why each level cannot be granted on this environment; absent when it can. */
205
+function useGrantableLevels(environment: EnvironmentPresentation) {
206
+ const environmentId = environment.environmentId;
207
+ const session = useEnvironmentSessionState(environmentId).data;
208
+ const canMint = useEnvironmentScope(environmentId, AuthAccessWriteScope);
209
+ const policy = useManagedPolicy(environmentId);
210
+ // The server refuses codes for any level when its policy keeps remote clients out.
211
+ const remoteDenial = managedCapabilityDenial(policy, "remoteClients");
212
+ return new Map(
213
+ AuthMcpClientAccess.literals.flatMap((level) => {
214
+ const reason =
215
+ remoteDenial ??
216
+ (!canMint
217
+ ? `This device needs the Manage access permission on ${environment.label}.`
218
+ : session === null ||
219
+ !mcpClientScopes(level).every((scope) => sessionGrantsScope(session, scope))
220
+ ? `This device cannot grant this on ${environment.label}.`
221
+ : level === "read-only"
222
+ ? undefined
223
+ : managedRuntimeModeDenial(policy, level));
224
+ return reason === undefined ? [] : [[level, reason] as const];
225
+ }),
226
+ );
227
+}
228
+
229
+function useGate(environment: EnvironmentPresentation) {
230
+ const environmentId = environment.environmentId;
231
+ const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
232
+ const controller = useCloudLinkController(environmentId);
233
+ const canReadRelay = useEnvironmentScope(environmentId, AuthRelayReadScope);
234
+ const thisMachine =
235
+ environmentId === usePrimaryEnvironmentId() ||
236
+ isDesktopLocalConnectionTarget(environment.entry.target);
237
+ const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
238
+ const refreshDiscovery = useAtomCommand(relayEnvironmentDiscovery.refresh, {
239
+ reportFailure: false,
240
+ });
241
+ const runCheck = useAtomCommand(checkReachability, { reportFailure: false });
242
+ const readState = useAtomCommand(readLinkState, { reportFailure: false });
243
+ // The gate opens on a check it ran, or on a newer one the link state reports. A failed run
244
+ // counts only server checks newer than `since` (see afterFailedCheck); null waits for a retry.
245
+ const [check, setCheck] = useState<
246
+ | "idle"
247
+ | "running"
248
+ | { readonly result: EnvironmentConnectReachability | null; readonly since: string | null }
249
+ >("idle");
250
+ const [connecting, setConnecting] = useState(false);
251
+ const linkState = controller.linkState.data;
252
+ const reported = linkState?.reachability;
253
+ const serverConfig = environment.serverConfig;
254
+ const connected = environment.connection.phase === "connected";
255
+ const relayEntry = discovery.environments.get(environmentId);
256
+ const gate = resolveMcpGate({
257
+ signedIn: isSignedIn,
258
+ connected,
259
+ approvalCodes:
260
+ serverConfig === null
261
+ ? undefined
262
+ : serverConfig.environment.capabilities.mcpApprovalCodes === true,
263
+ canReadRelay,
264
+ linkState,
265
+ linkStateError: controller.linkState.error,
266
+ thisMachine,
267
+ relay:
268
+ !discovery.refreshing && (discovery.offline || Option.isSome(discovery.error))
269
+ ? { status: "failed" }
270
+ : discovery.listed
271
+ ? {
272
+ status: "listed",
273
+ endpoint: relayEntry?.environment.endpoint,
274
+ availability: relayEntry?.availability,
275
+ }
276
+ : { status: "loading" },
277
+ reachability:
278
+ typeof check === "string"
279
+ ? "checking"
280
+ : reported !== undefined && check.since !== null && reported.checkedAt > check.since
281
+ ? reported
282
+ : check.result,
283
+ });
284
+ const runReachabilityCheck = async () => {
285
+ setCheck("running");
286
+ // A saved machine's address comes from T3 Connect's list, which can be stale.
287
+ if (!thisMachine) void refreshDiscovery();
288
+ const prior = readCachedCloudLinkState({ environmentId });
289
+ const result = await runCheck({ target: { environmentId } });
290
+ controller.linkState.refresh();
291
+ if (result._tag === "Success") {
292
+ setCheck({ result: result.value, since: result.value.checkedAt });
293
+ return;
294
+ }
295
+ const latest = await readState({ target: { environmentId } });
296
+ setCheck(afterFailedCheck(prior, latest._tag === "Success" ? latest.value : null));
297
+ };
298
+ const turnOn = async () => {
299
+ setConnecting(true);
300
+ const ok = await controller.reconcileCloudState({
301
+ managedTunnel: true,
302
+ publish: controller.publishAgentActivity,
303
+ });
304
+ if (!ok) setConnecting(false);
305
+ };
306
+ // A cached link state can name a tunnel on a disconnected machine; checking it would fail and
307
+ // spend the one automatic check.
308
+ const canCheck = connected && linkState !== null && isManagedTunnelActive(linkState, undefined);
309
+ const checkOnce = useEffectEvent(() => {
310
+ if (check === "idle") void runReachabilityCheck();
311
+ });
312
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the server to check its tunnel once one exists
313
+ useEffect(() => {
314
+ if (canCheck) queueMicrotask(checkOnce);
315
+ }, [canCheck]);
316
+ // T3 Connect lists machines only once something asks, and a saved machine's gate reads that list.
317
+ const discoverIfUnasked = useEffectEvent(() => {
318
+ if (!thisMachine && !discovery.listed && !discovery.refreshing) void refreshDiscovery();
319
+ });
320
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks T3 Connect for its machine list once the wizard opens signed in
321
+ useEffect(() => {
322
+ if (isSignedIn) discoverIfUnasked();
323
+ }, [isSignedIn]);
324
+ const waiting = gate.kind === "offline" || (connecting && gate.kind === "turn-on");
325
+ const refreshLinkState = useEffectEvent(() => controller.linkState.refresh());
326
+ // 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
327
+ useEffect(() => {
328
+ if (!waiting) return;
329
+ const interval = window.setInterval(() => refreshLinkState(), 5_000);
330
+ return () => window.clearInterval(interval);
331
+ }, [waiting]);
332
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- stops showing Connecting once a started tunnel has had time to come up
333
+ useEffect(() => {
334
+ if (!connecting) return;
335
+ const timeout = window.setTimeout(() => setConnecting(false), 90_000);
336
+ return () => window.clearTimeout(timeout);
337
+ }, [connecting]);
338
+ return {
339
+ gate,
340
+ connecting: connecting && gate.kind !== "open",
341
+ check: runReachabilityCheck,
342
+ // A disconnected machine cannot be checked; its list entry says when it is back.
343
+ refreshList: () => void refreshDiscovery(),
344
+ turnOn,
345
+ operationError: controller.operationError,
346
+ tunnelLimit: controller.tunnelLimit,
347
+ };
348
+}
349
+
350
+type Gate = ReturnType<typeof useGate>;
351
+
352
+function GateScreen({
353
+ environment,
354
+ gate: { gate, connecting, check, refreshList, turnOn, operationError, tunnelLimit },
355
+}: {
356
+ readonly environment: EnvironmentPresentation;
357
+ readonly gate: Gate;
358
+}) {
359
+ const name = environment.label;
360
+ const turnOnHere = useT3ConnectTurnOn(environment.environmentId);
361
+ const { openAuthPrompt } = useT3ConnectAuthPrompt();
362
+ const retry = (onClick: () => void) => (
363
+ <Button variant="outline" onClick={onClick}>
364
+ Check again
365
+ </Button>
366
+ );
367
+ const checkAgain = retry(() => void check());
368
+ switch (gate.kind) {
369
+ case "checking":
370
+ return (
371
+ <p role="status" className="flex items-center gap-2 text-sm text-muted-foreground">
372
+ <Spinner size="sm" tone="muted" />
373
+ Checking T3 Connect…
374
+ </p>
375
+ );
376
+ case "sign-in":
377
+ return (
378
+ <GateMessage
379
+ title="Sign in to T3 Connect"
380
+ lines={[
381
+ `Apps like Poke and Claude run in the cloud. They need a public address to reach ${name}.`,
382
+ `T3 Connect gives ${name} that address. Each app still needs your approval.`,
383
+ ]}
384
+ >
385
+ {/* Clerk's sign-in is its own modal, so this dialog closes first. */}
386
+ <Button
387
+ onClick={() => {
388
+ close();
389
+ openAuthPrompt();
390
+ }}
391
+ >
392
+ Sign in to T3 Connect
393
+ </Button>
394
+ </GateMessage>
395
+ );
396
+ case "disconnected":
397
+ return gate.relay === null ? (
398
+ <GateMessage title={`Connect to ${name} first.`} />
399
+ ) : (
400
+ <GateMessage
401
+ title={
402
+ gate.relay === "offline"
403
+ ? `${name}'s T3 Connect is offline`
404
+ : `Can't check T3 Connect on ${name}`
405
+ }
406
+ >
407
+ {retry(refreshList)}
408
+ </GateMessage>
409
+ );
410
+ case "update":
411
+ return <GateMessage title={`Update T3 Code on ${name}`} />;
412
+ case "no-relay-read":
413
+ return (
414
+ <GateMessage
415
+ title={`Can't check T3 Connect on ${name}`}
416
+ lines={[`This device needs the View relay permission on ${name}.`]}
417
+ />
418
+ );
419
+ case "error":
420
+ return (
421
+ <GateMessage title={`Can't check T3 Connect on ${name}`} lines={[gate.message]}>
422
+ {checkAgain}
423
+ </GateMessage>
424
+ );
425
+ case "turn-on":
426
+ case "offline": {
427
+ if (gate.kind === "offline" && !connecting) {
428
+ const reachability = gate.reachability;
429
+ return (
430
+ <GateMessage
431
+ title={
432
+ reachability ? `${name}'s T3 Connect is offline` : `Can't check T3 Connect on ${name}`
433
+ }
434
+ lines={reachability ? [reachability.reason, `Fix: ${reachability.fix}`] : []}
435
+ >
436
+ {checkAgain}
437
+ </GateMessage>
438
+ );
439
+ }
440
+ return (
441
+ <GateMessage
442
+ title={`Turn on T3 Connect for ${name}`}
443
+ lines={[
444
+ `${name} gets a public https address, with no router setup.`,
445
+ "Only apps you approve can use it. You can turn it off in Settings.",
446
+ ]}
447
+ >
448
+ {turnOnHere.kind === "here" ? (
449
+ <div className="space-y-2">
450
+ <Button disabled={connecting} onClick={() => void turnOn()}>
451
+ {connecting ? "Connecting…" : "Turn on"}
452
+ </Button>
453
+ {operationError ? (
454
+ <p className="text-xs text-destructive-foreground">{operationError}</p>
455
+ ) : null}
456
+ {tunnelLimit !== null ? (
457
+ <>
458
+ <p className="text-sm text-destructive-foreground">
459
+ Your T3 Connect account is out of tunnels.
460
+ </p>
461
+ <ManageAccessButton environment={environment} label="Manage tunnels" />
462
+ </>
463
+ ) : null}
464
+ </div>
465
+ ) : turnOnHere.kind === "policy" ? (
466
+ <p className="text-sm text-muted-foreground">{turnOnHere.reason}</p>
467
+ ) : (
468
+ <div className="space-y-2 text-sm">
469
+ <CommandBlock command="t3 connect link" />
470
+ <p>Restart T3 Code on {name}.</p>
471
+ {checkAgain}
472
+ </div>
473
+ )}
474
+ </GateMessage>
475
+ );
476
+ }
477
+ case "open":
478
+ return null;
479
+ }
480
+}
481
+
482
+function GateMessage({
483
+ title,
484
+ lines = [],
485
+ children,
486
+}: {
487
+ readonly title: string;
488
+ readonly lines?: readonly string[];
489
+ readonly children?: ReactNode;
490
+}) {
491
+ return (
492
+ <section className="space-y-3">
493
+ <h3 className="text-base font-medium">{title}</h3>
494
+ {lines.length > 0 ? (
495
+ <div className="space-y-1 text-sm text-muted-foreground">
496
+ {lines.map((line) => (
497
+ <p key={line}>{line}</p>
498
+ ))}
499
+ </div>
500
+ ) : null}
501
+ {children}
502
+ </section>
503
+ );
504
+}
505
+
506
+function AppStep({
507
+ choice,
508
+ onChoose,
509
+}: {
510
+ readonly choice: Choice | null;
511
+ readonly onChoose: (choice: Choice) => void;
512
+}) {
513
+ return (
514
+ <section className="space-y-3">
515
+ <h3 className="text-sm font-medium">Which app?</h3>
516
+ <div className="grid grid-cols-3 gap-2 sm:grid-cols-4">
517
+ {MCP_APPS.filter((app) => !app.hidden).map((app) => (
518
+ <button
519
+ key={app.id}
520
+ type="button"
521
+ aria-pressed={choice === app}
522
+ onClick={() => onChoose(app)}
523
+ className="flex min-w-0 flex-col items-center gap-2 rounded-lg border border-transparent px-1 py-3 outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring aria-pressed:border-primary aria-pressed:bg-primary/8"
524
+ >
525
+ <img
526
+ src={app.logo}
527
+ alt=""
528
+ className="size-10 rounded-lg ring-1 ring-black/10 dark:ring-white/12"
529
+ />
530
+ <span className="max-w-full truncate whitespace-nowrap text-xs font-medium">
531
+ {app.name}
532
+ </span>
533
+ </button>
534
+ ))}
535
+ </div>
536
+ <button
537
+ type="button"
538
+ aria-pressed={choice === "other"}
539
+ onClick={() => onChoose("other")}
540
+ className="w-full rounded-lg border border-border px-3 py-2.5 text-sm font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring aria-pressed:border-primary aria-pressed:bg-primary/8"
541
+ >
542
+ Something else…
543
+ </button>
544
+ </section>
545
+ );
546
+}
547
+
548
+function ConnectStep({
549
+ environment,
550
+ mcpUrl,
551
+ choice,
552
+ access,
553
+}: {
554
+ readonly environment: EnvironmentPresentation;
555
+ readonly mcpUrl: string;
556
+ readonly choice: Choice;
557
+ readonly access: AuthMcpClientAccess;
558
+}) {
559
+ const [anotherWay, setAnotherWay] = useState(choice === "other");
560
+ const app = choice === "other" ? null : choice;
561
+ const code = (
562
+ <ApprovalCode
563
+ key={access}
564
+ environmentId={environment.environmentId}
565
+ name={environment.label}
566
+ access={access}
567
+ />
568
+ );
569
+ if (anotherWay || app === null) {
570
+ const message = app?.handoff.kind === "copy-message" ? app.handoff.message(mcpUrl) : null;
571
+ return (
572
+ <section className="space-y-4">
573
+ <CopyRow label="URL" value={mcpUrl} />
574
+ {message ? <CopyRow label="Message" value={message} /> : null}
575
+ <ol className="list-decimal space-y-1 ps-5 text-sm">
576
+ {(app?.steps ?? OTHER_MCP_APP_STEPS).map((step) => (
577
+ <li key={step}>{step}</li>
578
+ ))}
579
+ </ol>
580
+ {app === null ? (
581
+ <p className="text-xs text-muted-foreground">
582
+ Apps that require their own client ID cannot connect.
583
+ </p>
584
+ ) : app.docs ? (
585
+ <TextButton onClick={() => openLink(app.docs ?? "")}>{app.name} help</TextButton>
586
+ ) : null}
587
+ {code}
588
+ {app === null ? null : (
589
+ <TextButton onClick={() => setAnotherWay(false)}>
590
+ {app.handoff.kind === "commands" ? "Back to commands" : "Back to one click"}
591
+ </TextButton>
592
+ )}
593
+ <LinkedLine environment={environment} access={access} />
594
+ </section>
595
+ );
596
+ }
597
+ return (
598
+ <section className="space-y-4">
599
+ <PrimaryAction app={app} mcpUrl={mcpUrl} />
600
+ <CopyRow label="URL" value={mcpUrl} />
601
+ {code}
602
+ <TextButton onClick={() => setAnotherWay(true)}>Set up another way</TextButton>
603
+ <LinkedLine environment={environment} access={access} />
604
+ </section>
605
+ );
606
+}
607
+
608
+function TextButton({
609
+ onClick,
610
+ children,
611
+}: {
612
+ readonly onClick: () => void;
613
+ readonly children: ReactNode;
614
+}) {
615
+ return (
616
+ <button
617
+ type="button"
618
+ onClick={onClick}
619
+ className="block text-sm font-medium underline-offset-4 outline-none hover:underline focus-visible:underline"
620
+ >
621
+ {children}
622
+ </button>
623
+ );
624
+}
625
+
626
+function openLink(url: string) {
627
+ void readLocalApi()
628
+ ?.shell.openExternal(url)
629
+ .catch((error: unknown) =>
630
+ toastManager.add({
631
+ type: "error",
632
+ title: "Could not open the link",
633
+ description: error instanceof Error ? error.message : url,
634
+ }),
635
+ );
636
+}
637
+
638
+function PrimaryAction({ app, mcpUrl }: { readonly app: McpApp; readonly mcpUrl: string }) {
639
+ const action = mcpHandoffAction(app, mcpUrl);
640
+ const note = app.note ? <p className="text-xs text-muted-foreground">{app.note}</p> : null;
641
+ if (action === null) {
642
+ return (
643
+ <div className="space-y-2">
644
+ {app.handoff.kind === "commands"
645
+ ? app.handoff
646
+ .commands(mcpUrl)
647
+ .map((command) => <CommandBlock key={command} command={command} />)
648
+ : null}
649
+ <p className="text-xs text-muted-foreground">Run these where {app.name} runs.</p>
650
+ {note}
651
+ </div>
652
+ );
653
+ }
654
+ const { copy, link } = action;
655
+ const handOff = async () => {
656
+ if (copy !== null) {
657
+ // The app opens only once the copy lands, so it never gets an older clipboard.
658
+ const copied = await writeTextToClipboard(copy.text, copy.title).catch(() => false);
659
+ if (!copied) {
660
+ toastManager.add({
661
+ type: "error",
662
+ title: "Could not copy",
663
+ description: "Use Set up another way.",
664
+ });
665
+ return;
666
+ }
667
+ toastManager.add({
668
+ type: "success",
669
+ title: copy.title,
670
+ // A browser can block an open that follows the copy; this keeps a way through.
671
+ ...(isElectron
672
+ ? {}
673
+ : { actionProps: { children: `Open ${app.name}`, onClick: () => openLink(link) } }),
674
+ });
675
+ }
676
+ openLink(link);
677
+ };
678
+ return (
679
+ <div className="space-y-2">
680
+ <Button className="w-full" onClick={() => void handOff()}>
681
+ {action.label}
682
+ </Button>
683
+ {note}
684
+ </div>
685
+ );
686
+}
687
+
688
+/** "Get code" mints on click; the code is never copied or sent anywhere by itself. */
689
+function ApprovalCode({
690
+ environmentId,
691
+ name,
692
+ access,
693
+}: {
694
+ readonly environmentId: EnvironmentId;
695
+ readonly name: string;
696
+ readonly access: AuthMcpClientAccess;
697
+}) {
698
+ const [code, setCode] = useState<{
699
+ readonly credential: string;
700
+ readonly expiresAt: number;
701
+ } | null>(null);
702
+ const [pending, setPending] = useState(false);
703
+ const [error, setError] = useState<string | null>(null);
704
+ const now = useNowSecond();
705
+ const live = code !== null && now < code.expiresAt;
706
+ const mint = async () => {
707
+ setPending(true);
708
+ setError(null);
709
+ const result = await mintMcpApprovalCodeOn(environmentId, access);
710
+ setPending(false);
711
+ if (Result.isSuccess(result)) {
712
+ setCode({
713
+ credential: result.success.credential,
714
+ expiresAt: result.success.expiresAt.epochMilliseconds,
715
+ });
716
+ } else {
717
+ setError(`Could not get a code from ${name}. Try again.`);
718
+ }
719
+ };
720
+ const left = code === null ? 0 : Math.max(0, Math.floor((code.expiresAt - now) / 1000));
721
+ return (
722
+ <div className="space-y-1.5">
723
+ <div className="flex flex-wrap items-center justify-between gap-2">
724
+ <span className="text-sm">
725
+ Code to approve <span className="font-medium">{accessConfig[access].label}</span>
726
+ </span>
727
+ {live ? null : (
728
+ <Button size="sm" variant="outline" disabled={pending} onClick={() => void mint()}>
729
+ {pending ? "Getting code…" : code === null ? "Get code" : "New code"}
730
+ </Button>
731
+ )}
732
+ </div>
733
+ {code !== null ? (
734
+ live ? (
735
+ <>
736
+ <CopyRow label="Code" value={code.credential} />
737
+ <p className="text-xs text-muted-foreground">
738
+ Expires {Math.floor(left / 60)}:{String(left % 60).padStart(2, "0")} · one use
739
+ </p>
740
+ </>
741
+ ) : (
742
+ <p className="text-xs text-muted-foreground">The code expired.</p>
743
+ )
744
+ ) : null}
745
+ {error ? <p className="text-xs text-destructive-foreground">{error}</p> : null}
746
+ </div>
747
+ );
748
+}
749
+
750
+function CopyRow({ label, value }: { readonly label: string; readonly value: string }) {
751
+ const { copyToClipboard, isCopied } = useCopyToClipboard({ timeout: 1500, target: label });
752
+ return (
753
+ <div className="flex min-w-0 items-center gap-2 rounded-lg border border-border bg-muted/50 px-3 py-2">
754
+ <span className="shrink-0 text-xs text-muted-foreground">{label}</span>
755
+ <span className="min-w-0 flex-1 truncate font-mono text-sm">{value}</span>
756
+ <Button
757
+ size="icon-xs"
758
+ variant="ghost"
759
+ aria-label={`Copy ${label}`}
760
+ onClick={() => copyToClipboard(value, undefined)}
761
+ >
762
+ <MorphIcon className="size-3.5" icon={isCopied ? Check : Copy} />
763
+ </Button>
764
+ </div>
765
+ );
766
+}
767
+
768
+const levelRank = (level: AuthMcpClientAccess) => AuthMcpClientAccess.literals.indexOf(level);
769
+
770
+/** Machines this environment links to, at the level a call forwarded there gets. */
771
+function LinkedLine({
772
+ environment,
773
+ access,
774
+}: {
775
+ readonly environment: EnvironmentPresentation;
776
+ readonly access: AuthMcpClientAccess;
777
+}) {
778
+ const offered = offersLinkedEnvironments(environment.serverConfig);
779
+ const links = useEnvironmentQuery(
780
+ offered
781
+ ? peerLinkEnvironment.list({ environmentId: environment.environmentId, input: {} })
782
+ : null,
783
+ ).data?.links;
784
+ const identities = useEnvironmentIdentities();
785
+ if (!offered || links === undefined || links.length === 0) return null;
786
+ const named = links.map((link) => {
787
+ const name =
788
+ identities.find((identity) => identity.environmentId === link.environmentId)?.label ??
789
+ link.label;
790
+ // A forwarded call keeps the lower of the app's level and the link's own.
791
+ const level = levelRank(link.access) < levelRank(access) ? link.access : access;
792
+ return `${name} · ${link.status === "expired" ? "Expired" : accessConfig[level].label}`;
793
+ });
794
+ return <p className="text-xs text-muted-foreground">Linked: {named.join(", ")}</p>;
795
+}
796
+
797
+/** Opens Sharing & access on this environment, where its clients and T3 Connect tunnels live. */
798
+function ManageAccessButton({
799
+ environment,
800
+ label = "Manage access",
801
+}: {
802
+ readonly environment: EnvironmentPresentation;
803
+ readonly label?: string;
804
+}) {
805
+ const navigate = useNavigate();
806
+ return (
807
+ <Button
808
+ variant="ghost"
809
+ onClick={() => {
810
+ close();
811
+ void navigate({ to: "/settings/access", search: { machine: environment.environmentId } });
812
+ }}
813
+ >
814
+ {label}
815
+ </Button>
816
+ );
817
+}
apps/web/src/components/mcp/logos/chatgpt.png
Binary files /dev/null and b/apps/web/src/components/mcp/logos/chatgpt.png differ
apps/web/src/components/mcp/logos/claude.png
Binary files /dev/null and b/apps/web/src/components/mcp/logos/claude.png differ
apps/web/src/components/mcp/logos/gemini.png
Binary files /dev/null and b/apps/web/src/components/mcp/logos/gemini.png differ
apps/web/src/components/mcp/logos/grokbot.png
Binary files /dev/null and b/apps/web/src/components/mcp/logos/grokbot.png differ
apps/web/src/components/mcp/logos/hermes.png
Binary files /dev/null and b/apps/web/src/components/mcp/logos/hermes.png differ
apps/web/src/components/mcp/logos/instinct.png
Binary files /dev/null and b/apps/web/src/components/mcp/logos/instinct.png differ
apps/web/src/components/mcp/logos/muse.png
Binary files /dev/null and b/apps/web/src/components/mcp/logos/muse.png differ
apps/web/src/components/mcp/logos/openclaw.png
Binary files /dev/null and b/apps/web/src/components/mcp/logos/openclaw.png differ
apps/web/src/components/mcp/logos/poke.png
Binary files /dev/null and b/apps/web/src/components/mcp/logos/poke.png differ
apps/web/src/components/mcp/mcpApps.test.ts
new
+28
@@ -0,0 +1,28 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { MCP_APPS, mcpHandoffAction } from "./mcpApps";
4
+
5
+const MCP_URL = "https://prod-a1.t3coderelay.com/mcp?x=1&y=two words";
6
+
7
+describe("MCP app links", () => {
8
+ it("fill in T3 Code and the encoded URL", () => {
9
+ const opened = (id: string) => {
10
+ const app = MCP_APPS.find((candidate) => candidate.id === id)!;
11
+ return new URL(mcpHandoffAction(app, MCP_URL)!.link);
12
+ };
13
+ const poke = opened("poke");
14
+ expect(poke.searchParams.get("name")).toBe("T3 Code");
15
+ expect(poke.searchParams.get("url")).toBe(MCP_URL);
16
+ const claude = opened("claude");
17
+ expect(claude.searchParams.get("connectorName")).toBe("T3 Code");
18
+ expect(claude.searchParams.get("connectorUrl")).toBe(MCP_URL);
19
+ });
20
+
21
+ // The desktop app opens only http and https links.
22
+ it.each(MCP_APPS.map((app) => [app.name, app] as const))("%s opens only https", (_, app) => {
23
+ const link = mcpHandoffAction(app, MCP_URL)?.link;
24
+ for (const url of [link, app.docs].filter((value) => value != null)) {
25
+ expect(new URL(url).protocol).toBe("https:");
26
+ }
27
+ });
28
+});
apps/web/src/components/mcp/mcpApps.ts
new
+201
@@ -0,0 +1,201 @@
1
+import chatgptLogo from "./logos/chatgpt.png";
2
+import claudeLogo from "./logos/claude.png";
3
+import geminiLogo from "./logos/gemini.png";
4
+import grokBotLogo from "./logos/grokbot.png";
5
+import hermesLogo from "./logos/hermes.png";
6
+import instinctLogo from "./logos/instinct.png";
7
+import museLogo from "./logos/muse.png";
8
+import openClawLogo from "./logos/openclaw.png";
9
+import pokeLogo from "./logos/poke.png";
10
+
11
+/** How the Connect step hands T3 Code's MCP URL to an app. Every link is https. */
12
+export type McpAppHandoff =
13
+ /** Opens the app's add form with T3 Code filled in. */
14
+ | { readonly kind: "open"; readonly link: (mcpUrl: string) => string }
15
+ /** Copies the URL, then opens the page it goes on. */
16
+ | { readonly kind: "copy-url"; readonly link: string }
17
+ /** Copies a message for the app's chat, then opens the app. */
18
+ | {
19
+ readonly kind: "copy-message";
20
+ readonly link: string;
21
+ readonly message: (mcpUrl: string) => string;
22
+ }
23
+ /** Commands to run where the app runs. */
24
+ | { readonly kind: "commands"; readonly commands: (mcpUrl: string) => readonly string[] };
25
+
26
+export interface McpApp {
27
+ readonly id: string;
28
+ readonly name: string;
29
+ readonly logo: string;
30
+ readonly handoff: McpAppHandoff;
31
+ /** "Set up another way", next to the URL. */
32
+ readonly steps: readonly string[];
33
+ /** One line under the primary action. */
34
+ readonly note?: string;
35
+ readonly docs?: string;
36
+ /** Kept out of the grid until its sign-in works. */
37
+ readonly hidden?: boolean;
38
+}
39
+
40
+const encoded = encodeURIComponent;
41
+
42
+export const MCP_APPS: readonly McpApp[] = [
43
+ {
44
+ id: "poke",
45
+ name: "Poke",
46
+ logo: pokeLogo,
47
+ handoff: {
48
+ kind: "open",
49
+ link: (url) => `https://poke.com/integrations/new?name=T3%20Code&url=${encoded(url)}`,
50
+ },
51
+ steps: ["Open poke.com/integrations/new.", "Paste the URL and add the integration."],
52
+ docs: "https://poke.com/docs/mcp-servers",
53
+ },
54
+ {
55
+ id: "claude",
56
+ name: "Claude",
57
+ logo: claudeLogo,
58
+ handoff: {
59
+ kind: "open",
60
+ link: (url) =>
61
+ `https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=T3%20Code&connectorUrl=${encoded(url)}`,
62
+ },
63
+ steps: [
64
+ "In Claude, open Customize, then Connectors.",
65
+ "Choose Add custom connector and paste the URL.",
66
+ "The Free plan allows one custom connector.",
67
+ ],
68
+ docs: "https://claude.com/docs/connectors/building/directory-vs-custom",
69
+ },
70
+ {
71
+ id: "chatgpt",
72
+ name: "ChatGPT",
73
+ logo: chatgptLogo,
74
+ handoff: { kind: "copy-url", link: "https://chatgpt.com/plugins" },
75
+ steps: [
76
+ "Open chatgpt.com/plugins on the web, then + and Add custom MCP server.",
77
+ "Paste the URL. Choose OAuth.",
78
+ "Create it as a plugin, then install it.",
79
+ ],
80
+ docs: "https://developers.openai.com/api/docs/guides/custom-mcp-server",
81
+ },
82
+ {
83
+ id: "grok-bot",
84
+ name: "Grok Bot",
85
+ logo: grokBotLogo,
86
+ // The app has no web chat, and its prompt links need a Bot id.
87
+ handoff: {
88
+ kind: "copy-message",
89
+ link: "https://x.ai/bot",
90
+ message: (url) => `Add the MCP server ${url} and connect it.`,
91
+ },
92
+ steps: ["Send this message to any of your Grok Bots."],
93
+ note: "Shared with all your Grok Bots.",
94
+ docs: "https://docs.x.ai/grok-bot/computer-and-apps",
95
+ },
96
+ {
97
+ id: "gemini",
98
+ name: "Gemini",
99
+ logo: geminiLogo,
100
+ handoff: { kind: "copy-url", link: "https://gemini.google.com/apps" },
101
+ steps: [
102
+ "In Gemini, open Settings, then Connected apps.",
103
+ "Choose Custom apps, then Add, and paste the URL.",
104
+ ],
105
+ docs: "https://support.google.com/gemini/answer/17209137",
106
+ // Gemini's sign-in and its tool schema checks do not work with T3 Code yet.
107
+ hidden: true,
108
+ },
109
+ {
110
+ id: "muse",
111
+ name: "Muse",
112
+ logo: museLogo,
113
+ handoff: {
114
+ kind: "copy-message",
115
+ link: "https://muse.ai",
116
+ message: (url) => `Create a custom connector for the MCP server ${url}.`,
117
+ },
118
+ steps: ["Send this message to Muse."],
119
+ docs: "https://www.meta.com/help/artificial-intelligence/1687253048996149/",
120
+ },
121
+ {
122
+ id: "instinct",
123
+ name: "Instinct",
124
+ logo: instinctLogo,
125
+ handoff: {
126
+ kind: "copy-message",
127
+ link: "https://app.instinct.com",
128
+ message: (url) => `Connect the MCP server ${url}.`,
129
+ },
130
+ steps: ["In Instinct, open Settings, then MCP connections, if your account has it."],
131
+ },
132
+ {
133
+ id: "openclaw",
134
+ name: "OpenClaw",
135
+ logo: openClawLogo,
136
+ handoff: {
137
+ kind: "commands",
138
+ commands: (url) => [
139
+ // Its MCP commands refuse to write while the Gateway runs.
140
+ "openclaw gateway stop",
141
+ `openclaw mcp add t3code --url ${url} --transport streamable-http --auth oauth`,
142
+ "openclaw mcp login t3code",
143
+ "openclaw gateway start",
144
+ ],
145
+ },
146
+ steps: [
147
+ "Open the Control UI, then + and Plugins, and choose Add MCP server.",
148
+ "Paste the URL, and choose Streamable HTTP and OAuth.",
149
+ "Select Sign in for it under Settings → MCP.",
150
+ ],
151
+ docs: "https://docs.openclaw.ai/tools/mcp",
152
+ },
153
+ {
154
+ id: "hermes-agent",
155
+ name: "Hermes Agent",
156
+ logo: hermesLogo,
157
+ handoff: {
158
+ kind: "commands",
159
+ commands: (url) => [
160
+ // `add` signs in on its first connection (30 s by default, too short to get a code);
161
+ // `login` would clear that sign-in and need a second code.
162
+ `hermes mcp add t3code --url ${url} --auth oauth --connect-timeout 315`,
163
+ ],
164
+ },
165
+ steps: [
166
+ "Add t3code under mcp_servers in ~/.hermes/config.yaml, with the URL and auth: oauth.",
167
+ "Run hermes mcp login t3code.",
168
+ ],
169
+ note: "On a remote host, paste the final URL back when asked.",
170
+ docs: "https://hermes-agent.nousresearch.com/docs/user-guide/features/mcp",
171
+ },
172
+];
173
+
174
+/** The "Something else…" choice: the URL and general steps only. */
175
+export const OTHER_MCP_APP_STEPS = ["Add a remote MCP server with OAuth."] as const;
176
+
177
+/**
178
+ * The primary button for `app`: its label, the https page it opens, and what it copies first.
179
+ * Null for apps set up with commands. It never copies the approval code.
180
+ */
181
+export function mcpHandoffAction(app: McpApp, mcpUrl: string) {
182
+ const { handoff } = app;
183
+ switch (handoff.kind) {
184
+ case "open":
185
+ return { label: `Open in ${app.name}`, link: handoff.link(mcpUrl), copy: null };
186
+ case "copy-url":
187
+ return {
188
+ label: `Copy URL and open ${app.name}`,
189
+ link: handoff.link,
190
+ copy: { text: mcpUrl, title: "URL copied" },
191
+ };
192
+ case "copy-message":
193
+ return {
194
+ label: `Copy message and open ${app.name}`,
195
+ link: handoff.link,
196
+ copy: { text: handoff.message(mcpUrl), title: "Message copied" },
197
+ };
198
+ case "commands":
199
+ return null;
200
+ }
201
+}
apps/web/src/components/mcp/mcpGate.test.ts
new
+203
@@ -0,0 +1,203 @@
1
+import type { EnvironmentCloudLinkStateResult } from "@t3tools/contracts";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import { afterFailedCheck, resolveMcpGate } from "./mcpGate";
5
+
6
+const reachable = {
7
+ status: "reachable",
8
+ checkedAt: "2026-11-08T00:00:00.000Z",
9
+ readyConnections: 4,
10
+ protocol: "quic",
11
+} as const;
12
+
13
+const tunnel: EnvironmentCloudLinkStateResult = {
14
+ linked: true,
15
+ cloudUserId: "user_1",
16
+ relayUrl: "https://relay.example.test",
17
+ relayIssuer: "https://relay.example.test",
18
+ managedTunnelActive: true,
19
+ publishAgentActivity: true,
20
+ tunnelHostname: "prod-a1.t3coderelay.com",
21
+};
22
+
23
+const savedTunnel = {
24
+ httpBaseUrl: "https://prod-b2.t3coderelay.com",
25
+ wsBaseUrl: "wss://prod-b2.t3coderelay.com",
26
+ providerKind: "cloudflare_tunnel",
27
+} as const;
28
+
29
+const open = {
30
+ signedIn: true,
31
+ connected: true,
32
+ approvalCodes: true,
33
+ canReadRelay: true,
34
+ linkState: tunnel,
35
+ linkStateError: null,
36
+ thisMachine: true,
37
+ relay: { status: "listed", endpoint: undefined },
38
+ reachability: reachable,
39
+} satisfies Parameters<typeof resolveMcpGate>[0];
40
+
41
+const saved = {
42
+ ...open,
43
+ thisMachine: false,
44
+ relay: { status: "listed", endpoint: savedTunnel },
45
+} satisfies Parameters<typeof resolveMcpGate>[0];
46
+
47
+describe("resolveMcpGate", () => {
48
+ it("opens on a fresh reachable check, at the tunnel's MCP URL", () => {
49
+ expect(resolveMcpGate(open)).toEqual({
50
+ kind: "open",
51
+ mcpUrl: "https://prod-a1.t3coderelay.com/mcp",
52
+ });
53
+ // A saved machine's address comes from T3 Connect, not from what it reports itself.
54
+ expect(resolveMcpGate(saved)).toEqual({
55
+ kind: "open",
56
+ mcpUrl: "https://prod-b2.t3coderelay.com/mcp",
57
+ });
58
+ // A disconnected saved machine follows T3 Connect's list. Offline or an unreadable list keeps
59
+ // a retry; only a list showing nothing wrong asks to reconnect.
60
+ const away = { ...saved, connected: false };
61
+ const listed = (
62
+ availability: "checking" | "online" | "offline" | "error",
63
+ providerKind: "cloudflare_tunnel" | "manual" = "cloudflare_tunnel",
64
+ ) => ({
65
+ ...away,
66
+ relay: {
67
+ status: "listed",
68
+ endpoint: { ...savedTunnel, providerKind },
69
+ availability,
70
+ } as const,
71
+ });
72
+ expect(resolveMcpGate(listed("checking")).kind).toBe("checking");
73
+ expect(resolveMcpGate(listed("offline"))).toEqual({ kind: "disconnected", relay: "offline" });
74
+ expect(resolveMcpGate(listed("error"))).toEqual({ kind: "disconnected", relay: "failed" });
75
+ // T3 Connect refuses to check a publish-only link, so that failure says nothing.
76
+ expect(resolveMcpGate(listed("error", "manual"))).toEqual({
77
+ kind: "disconnected",
78
+ relay: null,
79
+ });
80
+ expect(resolveMcpGate({ ...away, relay: { status: "failed" } })).toEqual({
81
+ kind: "disconnected",
82
+ relay: "failed",
83
+ });
84
+ expect(resolveMcpGate(listed("online"))).toEqual({ kind: "disconnected", relay: null });
85
+ // This machine's probe outranks a stale publish-only record in that list.
86
+ expect(
87
+ resolveMcpGate({
88
+ ...open,
89
+ relay: { status: "listed", endpoint: { ...savedTunnel, providerKind: "manual" } },
90
+ }).kind,
91
+ ).toBe("open");
92
+ });
93
+
94
+ it.each([
95
+ ["no T3 Connect sign-in", { ...open, signedIn: false }, "sign-in"],
96
+ ["no permission to read T3 Connect", { ...open, canReadRelay: false }, "no-relay-read"],
97
+ ["a server without approval codes", { ...open, approvalCodes: false }, "update"],
98
+ ["no tunnel", { ...open, linkState: { ...tunnel, managedTunnelActive: false } }, "turn-on"],
99
+ ["a removed link", { ...open, linkState: { ...tunnel, linkRevoked: true } }, "turn-on"],
100
+ [
101
+ "a publish-only link's local address",
102
+ {
103
+ ...saved,
104
+ relay: {
105
+ status: "listed",
106
+ endpoint: {
107
+ ...savedTunnel,
108
+ httpBaseUrl: "http://127.0.0.1:3773",
109
+ providerKind: "manual",
110
+ },
111
+ },
112
+ },
113
+ "turn-on",
114
+ ],
115
+ [
116
+ "a saved machine T3 Connect does not list",
117
+ { ...saved, relay: { status: "listed", endpoint: undefined } },
118
+ "turn-on",
119
+ ],
120
+ ["T3 Connect's list still loading", { ...saved, relay: { status: "loading" } }, "checking"],
121
+ [
122
+ "a disconnected saved machine while T3 Connect's list refreshes",
123
+ { ...saved, connected: false, relay: { status: "loading" } },
124
+ "checking",
125
+ ],
126
+ [
127
+ "no tunnel, before T3 Connect's list loads",
128
+ {
129
+ ...saved,
130
+ linkState: { ...tunnel, managedTunnelActive: false },
131
+ relay: { status: "loading" },
132
+ },
133
+ "turn-on",
134
+ ],
135
+ ["the check still running", { ...open, reachability: "checking" }, "checking"],
136
+ [
137
+ "an offline tunnel",
138
+ {
139
+ ...open,
140
+ reachability: {
141
+ status: "unreachable",
142
+ checkedAt: "2026-11-08T00:00:00.000Z",
143
+ cause: "no_connector",
144
+ reason: "Cloudflare has no live connection from this machine for the tunnel.",
145
+ hint: null,
146
+ fix: "Restart T3 Code.",
147
+ },
148
+ },
149
+ "offline",
150
+ ],
151
+ ["a failed check", { ...open, reachability: null }, "offline"],
152
+ [
153
+ "no tunnel address yet",
154
+ { ...open, linkState: { ...tunnel, tunnelHostname: undefined } },
155
+ "offline",
156
+ ],
157
+ [
158
+ "a hostname that is not a plain DNS name",
159
+ { ...open, linkState: { ...tunnel, tunnelHostname: "a.com;touch$IFS/tmp/x" } },
160
+ "offline",
161
+ ],
162
+ ] as const)("stays closed with %s", (_, input, kind) => {
163
+ expect(resolveMcpGate(input).kind).toBe(kind);
164
+ });
165
+});
166
+
167
+describe("afterFailedCheck", () => {
168
+ const at = (checkedAt: string) => ({ ...tunnel, reachability: { ...reachable, checkedAt } });
169
+ const older = at("2026-11-08T00:00:00.000Z");
170
+ const newer = at("2026-11-08T00:01:00.000Z");
171
+
172
+ it.each([
173
+ [
174
+ "a check the server finished anyway",
175
+ older,
176
+ newer,
177
+ { result: newer.reachability, since: newer.reachability.checkedAt },
178
+ ],
179
+ ["no newer check", newer, newer, { result: null, since: newer.reachability.checkedAt }],
180
+ [
181
+ "nothing known before, so the read is only a baseline",
182
+ null,
183
+ newer,
184
+ { result: null, since: newer.reachability.checkedAt },
185
+ ],
186
+ [
187
+ "no read after, so the old result is the baseline",
188
+ older,
189
+ null,
190
+ { result: null, since: older.reachability.checkedAt },
191
+ ],
192
+ ["nothing read at all, so only a retry counts", null, null, { result: null, since: null }],
193
+ [
194
+ "a first server check",
195
+ tunnel,
196
+ newer,
197
+ { result: newer.reachability, since: newer.reachability.checkedAt },
198
+ ],
199
+ ["no server check yet, so any later one counts", tunnel, null, { result: null, since: "" }],
200
+ ] as const)("with %s", (_, prior, latest, expected) => {
201
+ expect(afterFailedCheck(prior, latest)).toEqual(expected);
202
+ });
203
+});
apps/web/src/components/mcp/mcpGate.ts
new
+121
@@ -0,0 +1,121 @@
1
+import type {
2
+ EnvironmentCloudLinkStateResult,
3
+ EnvironmentConnectReachability,
4
+} from "@t3tools/contracts";
5
+import type { Discovery } from "@t3tools/client-runtime/relay";
6
+import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";
7
+
8
+import { isManagedTunnelActive, t3ConnectMcpUrl } from "~/cloud/t3ConnectState";
9
+
10
+type Unreachable = Extract<EnvironmentConnectReachability, { readonly status: "unreachable" }>;
11
+
12
+/**
13
+ * What stands between the user and the wizard's steps. Only `open` lets them go on: cloud apps
14
+ * need a public address, so the environment must answer on its T3 Connect tunnel.
15
+ */
16
+export type McpGate =
17
+ | { readonly kind: "checking" }
18
+ | { readonly kind: "sign-in" }
19
+ /**
20
+ * `relay`: T3 Connect reports the saved machine offline, or its list could not be read; both
21
+ * keep a retry. Null when that list shows nothing wrong, so the user should reconnect.
22
+ */
23
+ | { readonly kind: "disconnected"; readonly relay: "offline" | "failed" | null }
24
+ | { readonly kind: "update" }
25
+ | { readonly kind: "no-relay-read" }
26
+ | { readonly kind: "error"; readonly message: string }
27
+ | { readonly kind: "turn-on" }
28
+ | { readonly kind: "offline"; readonly reachability: Unreachable | null }
29
+ | { readonly kind: "open"; readonly mcpUrl: string };
30
+
31
+export function resolveMcpGate(input: {
32
+ /** Undefined until T3 Connect sign-in has loaded. */
33
+ readonly signedIn: boolean | undefined;
34
+ readonly connected: boolean;
35
+ /** The environment's `mcpApprovalCodes` capability; undefined until its config loads. */
36
+ readonly approvalCodes: boolean | undefined;
37
+ readonly canReadRelay: boolean;
38
+ readonly linkState: EnvironmentCloudLinkStateResult | null;
39
+ readonly linkStateError: string | null;
40
+ /** A backend this device runs; its link state names its own tunnel. */
41
+ readonly thisMachine: boolean;
42
+ /** The account's machines on T3 Connect, where a saved machine's address and health come from. */
43
+ readonly relay:
44
+ | { readonly status: "loading" | "failed" }
45
+ | {
46
+ readonly status: "listed";
47
+ readonly endpoint: RelayManagedEndpoint | undefined;
48
+ readonly availability?: Discovery.RelayEnvironmentAvailability | undefined;
49
+ };
50
+ /** A check run for this gate: its answer, "checking" until it has one, or null if it failed. */
51
+ readonly reachability: EnvironmentConnectReachability | "checking" | null;
52
+}): McpGate {
53
+ if (input.signedIn === undefined) return { kind: "checking" };
54
+ if (!input.signedIn) return { kind: "sign-in" };
55
+ const { relay } = input;
56
+ if (!input.connected) {
57
+ if (input.thisMachine) return { kind: "disconnected", relay: null };
58
+ // T3 Connect checks only its own tunnels; a publish-only link's check always fails.
59
+ const availability =
60
+ relay.status === "listed" && relay.endpoint?.providerKind === "cloudflare_tunnel"
61
+ ? relay.availability
62
+ : undefined;
63
+ // A refresh empties the list first, so wait for it instead of flashing "Connect first".
64
+ if (relay.status === "loading" || availability === "checking") return { kind: "checking" };
65
+ if (relay.status === "failed" || availability === "error") {
66
+ return { kind: "disconnected", relay: "failed" };
67
+ }
68
+ return { kind: "disconnected", relay: availability === "offline" ? "offline" : null };
69
+ }
70
+ if (input.approvalCodes === undefined) return { kind: "checking" };
71
+ if (!input.approvalCodes) return { kind: "update" };
72
+ if (!input.canReadRelay) return { kind: "no-relay-read" };
73
+ if (input.linkStateError !== null) return { kind: "error", message: input.linkStateError };
74
+ const { linkState } = input;
75
+ if (linkState === null) return { kind: "checking" };
76
+ // This machine reports its own tunnel and the probe proves it; the list speaks for saved ones.
77
+ const endpoint = !input.thisMachine && relay.status === "listed" ? relay.endpoint : undefined;
78
+ if (!isManagedTunnelActive(linkState, endpoint?.providerKind)) return { kind: "turn-on" };
79
+ if (!input.thisMachine) {
80
+ if (relay.status === "loading") return { kind: "checking" };
81
+ if (relay.status === "failed") return { kind: "error", message: "Could not reach T3 Connect." };
82
+ if (endpoint === undefined) return { kind: "turn-on" };
83
+ }
84
+ const { reachability } = input;
85
+ if (reachability === "checking") return { kind: "checking" };
86
+ const mcpUrl = t3ConnectMcpUrl({
87
+ thisMachine: input.thisMachine,
88
+ tunnelHostname: linkState.tunnelHostname,
89
+ relayEndpoint: endpoint,
90
+ });
91
+ if (reachability?.status === "reachable" && mcpUrl !== null) return { kind: "open", mcpUrl };
92
+ return {
93
+ kind: "offline",
94
+ reachability: reachability?.status === "unreachable" ? reachability : null,
95
+ };
96
+}
97
+
98
+/**
99
+ * What a failed check request leaves: `prior` is the link state from before it, `latest` a read
100
+ * after it (null when unread). The server may still have checked, so a result newer than `prior`
101
+ * counts. Otherwise only a later server check does; with nothing read at all, only a retry does.
102
+ */
103
+export function afterFailedCheck(
104
+ prior: EnvironmentCloudLinkStateResult | null,
105
+ latest: EnvironmentCloudLinkStateResult | null,
106
+): { readonly result: EnvironmentConnectReachability | null; readonly since: string | null } {
107
+ const fresh = latest?.reachability;
108
+ const known = prior?.reachability;
109
+ if (
110
+ fresh !== undefined &&
111
+ prior !== null &&
112
+ (known === undefined || fresh.checkedAt > known.checkedAt)
113
+ ) {
114
+ return { result: fresh, since: fresh.checkedAt };
115
+ }
116
+ const baseline = latest ?? prior;
117
+ return {
118
+ result: null,
119
+ since: baseline === null ? null : (baseline.reachability?.checkedAt ?? ""),
120
+ };
121
+}
apps/web/src/components/settings/AuthorizedClientsSettings.tsx
+7
-2
@@ -1,5 +1,5 @@
1
import { AUTH_SCOPE_OPTIONS as PAIRING_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions";
2
-import { PlusIcon, QrCodeIcon } from "lucide-react";
2
+import { PlugIcon, PlusIcon, QrCodeIcon } from "lucide-react";
3
import { type ReactNode, memo, useId, useState } from "react";
4
import {
5
AuthAccessWriteScope,
@@ -59,6 +59,7 @@ import { readEnvironmentScope } from "~/state/session";
59
import { useManagedPolicy, usePrimaryManagedPolicy } from "~/state/managedPolicy";
60
import { useAtomCommand } from "~/state/use-atom-command";
61
import { ManagedControl } from "../ManagedPolicy";
62
+import { openUseInAnotherApp } from "../mcp/UseInAnotherAppDialog";
63
import { ConnectionStatusDot } from "../ConnectionStatusDot";
64
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
65
import {
@@ -640,7 +641,11 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHead
641
};
642
643
return (
643
- <div className="flex items-center gap-2">
644
+ <div className="flex flex-wrap items-center justify-end gap-2">
645
+ <Button size="xs" variant="outline" onClick={() => openUseInAnotherApp(environmentId)}>
646
+ <PlugIcon className="size-3" />
647
+ Use in another app (MCP)
648
+ </Button>
649
<Button
650
size="xs"
651
variant="destructive-outline"
apps/web/src/components/settings/ConnectionsSettings.tsx
+13
-18
@@ -1,4 +1,5 @@
1
import { SessionPermissions } from "./SessionPermissions";
2
+import { useSearch } from "@tanstack/react-router";
3
import { ChevronRightIcon, EllipsisIcon } from "lucide-react";
4
import { useAtomValue } from "@effect/atom-react";
5
import { type ReactNode, useState } from "react";
@@ -14,7 +15,7 @@ import {
15
type AdvertisedEndpoint,
16
type DesktopServerExposureState,
17
type DesktopWslState,
17
- type EnvironmentId,
18
+ EnvironmentId,
19
managedCapabilityDenial,
20
resolveEnvironmentMachineKind,
21
} from "@t3tools/contracts";
@@ -30,11 +31,11 @@ import {
31
applyWslEnableSelection,
32
isWslSettingsRowVisible,
33
missingTailscaleEndpointDescription,
33
- resolveAccessEnvironmentId,
34
resolveLocalVersionStatusLabel,
35
resolveTailscaleServeBaseUrl,
36
} from "./ConnectionsSettings.logic";
37
import { settingsScopeEnvironmentLabel } from "./settingsScopeAxis";
38
+import { useAccessEnvironment } from "./useAccessEnvironment";
39
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
40
import { ManagedByOrganization } from "../ManagedPolicy";
41
import { LocalEnvironmentSetting } from "./LocalEnvironmentSetting";
@@ -103,7 +104,6 @@ import {
104
useEnvironment,
105
useEnvironments,
106
usePrimaryEnvironment,
106
- usePrimaryEnvironmentId,
107
} from "~/state/environments";
108
import { requestConfirmDialog } from "~/confirmDialog";
109
import { useAtomCommand } from "../../state/use-atom-command";
@@ -166,22 +166,17 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
166
}
167
168
function AccessSettings() {
169
- const { environments } = useEnvironments();
170
- const primaryEnvironmentId = usePrimaryEnvironmentId();
171
- const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
172
- const candidates = environments.filter(
173
- (environment) =>
174
- environment.environmentId === primaryEnvironmentId ||
175
- (environment.entry.enabled && !isDesktopLocalConnectionTarget(environment.entry.target)),
176
- );
177
- const accessEnvironmentId = resolveAccessEnvironmentId({
178
- primaryEnvironmentId,
179
- environments: candidates.map((environment) => ({
180
- environmentId: environment.environmentId,
181
- connected: environment.connection.phase === "connected",
182
- })),
183
- selected: selectedEnvironmentId,
169
+ // A link that names an environment, such as the MCP wizard's, opens the page on it. The
170
+ // settings layout remounts this page when the link changes.
171
+ const linkedEnvironmentId = useSearch({
172
+ strict: false,
173
+ select: (search) =>
174
+ typeof search.machine === "string" ? EnvironmentId.make(search.machine) : null,
175
});
176
+ const [selectedEnvironmentId, setSelectedEnvironmentId] = useState(linkedEnvironmentId);
177
+ const { candidates, environment: accessEnvironment } =
178
+ useAccessEnvironment(selectedEnvironmentId);
179
+ const accessEnvironmentId = accessEnvironment?.environmentId ?? null;
180
const picker =
181
candidates.length > 1 && accessEnvironmentId !== null ? (
182
<div className="flex min-w-0 items-center gap-1.5 px-3 text-sm text-muted-foreground sm:px-4">
apps/web/src/components/settings/FoldedSettingsSection.tsx
+6
-3
@@ -69,8 +69,9 @@ export function FoldedSettingsSection({
69
return (
70
<section id={id} ref={targetRef} tabIndex={-1} className="outline-none">
71
<Collapsible open={open} onOpenChange={setOpen} render={<SettingsGroup divided={false} />}>
72
- <div className="flex items-center gap-4 px-3 sm:px-4">
73
- <CollapsibleTrigger className="flex min-h-11 min-w-0 flex-1 items-center gap-2 py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring rounded-md">
72
+ {/* On a narrow screen the controls drop below the title instead of covering it. */}
73
+ <div className="flex flex-wrap items-center gap-x-4 px-3 sm:px-4">
74
+ <CollapsibleTrigger className="flex min-h-11 min-w-0 flex-1 basis-40 items-center gap-2 py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring rounded-md">
75
<ChevronRightIcon
76
aria-hidden
77
className={cn(
@@ -83,7 +84,9 @@ export function FoldedSettingsSection({
84
<span className="min-w-0 truncate text-xs text-muted-foreground">{summary}</span>
85
) : null}
86
</CollapsibleTrigger>
86
- {control ? <div className="flex shrink-0 items-center">{control}</div> : null}
87
+ {control ? (
88
+ <div className="ms-auto flex max-w-full items-center py-1.5">{control}</div>
89
+ ) : null}
90
</div>
91
{!open && collapsedContent ? (
92
<div className="border-t border-border/50 empty:hidden">{collapsedContent}</div>
apps/web/src/components/settings/SavedEnvironmentRows.tsx
+17
-4
@@ -49,6 +49,7 @@ import {
49
} from "~/versionSkew";
50
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
51
import { isElectron } from "~/env";
52
+import { useT3ConnectTurnOn } from "~/cloud/useT3ConnectTurnOn";
53
import { useCloudLinkController } from "~/cloud/useCloudLinkController";
54
import { useManagedTunnelUsage } from "~/cloud/managedRelayState";
55
import { useT3ConnectAccountPage } from "../clerk/T3ConnectAccountPages";
@@ -487,9 +488,13 @@ function T3ConnectTunnelUsage({ tunnelLimit }: { readonly tunnelLimit: number |
488
used={usage.used}
489
limit={usage.limit}
490
action={
490
- // At the cap the alert below carries the same action.
491
- usage.upgrade && openAccountPage && !showLimitAlert ? (
491
+ // At the cap the alert below carries the same actions.
492
+ !openAccountPage || showLimitAlert ? null : usage.upgrade ? (
493
<InlineButton onClick={() => openAccountPage("t3-chat")}>Get more tunnels</InlineButton>
494
+ ) : usage.used >= usage.limit ? (
495
+ <InlineButton onClick={() => openAccountPage("t3-connect")}>
496
+ Manage tunnels
497
+ </InlineButton>
498
) : null
499
}
500
/>
@@ -536,6 +541,9 @@ function ConfiguredCloudLinkRow({
541
const { openAuthPrompt } = useT3ConnectAuthPrompt();
542
// The server unlinks and refuses relay changes under such a policy; unlinking stays possible.
543
const connectDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "connect");
544
+ const turnOn = useT3ConnectTurnOn(environmentId);
545
+ // Turning on links from this desktop's own backend only; turning off works from anywhere.
546
+ const showSwitch = isElectron && (turnOn.kind !== "on-host" || managedTunnelActive);
547
const [isUpdating, setIsUpdating] = useState(false);
548
const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
549
@@ -645,7 +653,7 @@ function ConfiguredCloudLinkRow({
653
654
return (
655
<>
648
- {isElectron ? (
656
+ {showSwitch ? (
657
<SettingsRow
658
title={searchableSetting("t3-connect").title}
659
description={
@@ -689,8 +697,13 @@ function ConfiguredCloudLinkRow({
697
title={searchableSetting("t3-connect").title}
698
description="This environment was removed from T3 Connect. Run `t3 connect link` on the host to link it again."
699
/>
700
+ ) : isElectron ? (
701
+ <SettingsRow
702
+ title={searchableSetting("t3-connect").title}
703
+ description="Run `t3 connect link` on the host, then restart T3 Code there."
704
+ />
705
) : null}
693
- {signedOut && isElectron ? null : (
706
+ {signedOut && showSwitch ? null : (
707
<SettingsRow
708
title={searchableSetting("publish-agent-activity").title}
709
description={
apps/web/src/components/settings/useAccessEnvironment.ts
new
+37
@@ -0,0 +1,37 @@
1
+import type { EnvironmentId } from "@t3tools/contracts";
2
+
3
+import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal";
4
+import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments";
5
+import { resolveAccessEnvironmentId } from "./ConnectionsSettings.logic";
6
+import { settingsScopeEnvironmentLabel } from "./settingsScopeAxis";
7
+
8
+/**
9
+ * The environments Sharing & access manages, the one `requested` resolves to, and its name.
10
+ * The MCP wizard uses the same, so both name an environment alike. A requested environment
11
+ * always counts, so a thread on a second WSL backend opens on that backend.
12
+ */
13
+export function useAccessEnvironment(requested: EnvironmentId | null) {
14
+ const { environments } = useEnvironments();
15
+ const primaryEnvironmentId = usePrimaryEnvironmentId();
16
+ const candidates = environments.filter(
17
+ (environment) =>
18
+ environment.environmentId === primaryEnvironmentId ||
19
+ environment.environmentId === requested ||
20
+ (environment.entry.enabled && !isDesktopLocalConnectionTarget(environment.entry.target)),
21
+ );
22
+ const environmentId = resolveAccessEnvironmentId({
23
+ primaryEnvironmentId,
24
+ environments: candidates.map((environment) => ({
25
+ environmentId: environment.environmentId,
26
+ connected: environment.connection.phase === "connected",
27
+ })),
28
+ selected: requested,
29
+ });
30
+ const environment =
31
+ candidates.find((candidate) => candidate.environmentId === environmentId) ?? null;
32
+ return {
33
+ candidates,
34
+ environment,
35
+ label: environment ? settingsScopeEnvironmentLabel(environment, candidates) : null,
36
+ };
37
+}
apps/web/src/routes/__root.tsx
+4
@@ -18,6 +18,7 @@ import { AppSidebarLayout } from "../components/AppSidebarLayout";
18
import { CommandPalette } from "../components/CommandPalette";
19
import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";
20
import { GuestShareDialogHost } from "../components/chat/GuestShareControls";
21
+import { UseInAnotherAppDialogHost } from "../components/mcp/UseInAnotherAppDialog";
22
import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog";
23
import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
24
import { DevReplayHost } from "../components/DevReplayHost";
@@ -169,6 +170,8 @@ function RootRouteBranch() {
170
<>
171
<CustomSnoozeDialogHost />
172
<GuestShareDialogHost />
173
+ <UseInAnotherAppDialogHost />
174
+ <RelayClientInstallDialog />
175
<CommandPalette>
176
<AppSidebarLayout>
177
<Outlet />
@@ -212,6 +215,7 @@ function RootRouteBranch() {
215
<GuestShareDialogHost />
216
<ProjectCloneToastCoordinator />
217
<AddProjectToMachineDialogHost />
218
+ <UseInAnotherAppDialogHost />
219
{import.meta.env.DEV && primaryEnvironmentAuthenticated ? <DevReplayHost /> : null}
220
{primaryEnvironmentAuthenticated ? (
221
<EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
apps/web/src/state/peerPairingCode.ts
+21
-2
@@ -1,12 +1,20 @@
1
-import { createPeerPairingCodeCommand } from "@t3tools/client-runtime/state/peerPairingCode";
1
+import {
2
+ createMcpApprovalCodeCommand,
3
+ createPeerPairingCodeCommand,
4
+} from "@t3tools/client-runtime/state/peerPairingCode";
5
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3
-import type { AuthMcpClientAccess, EnvironmentId } from "@t3tools/contracts";
6
+import type {
7
+ AuthMcpClientAccess,
8
+ AuthPairingCredentialResult,
9
+ EnvironmentId,
10
+} from "@t3tools/contracts";
11
import * as Result from "effect/Result";
12
13
import { connectionAtomRuntime } from "../connection/runtime";
14
import { appAtomRegistry } from "../rpc/atomRegistry";
15
16
const mintPairingCode = createPeerPairingCodeCommand(connectionAtomRuntime);
17
+const mintMcpApprovalCode = createMcpApprovalCodeCommand(connectionAtomRuntime);
18
19
/**
20
* A fresh pairing code minted on `environmentId` with this client's session
@@ -22,3 +30,14 @@ export async function mintPairingCodeOn(
30
? Result.succeed(result.value)
31
: Result.fail(squashAtomCommandFailure(result));
32
}
33
+
34
+/** A fresh code on `environmentId` that approves one app's sign-in at `access`. */
35
+export async function mintMcpApprovalCodeOn(
36
+ environmentId: EnvironmentId,
37
+ access: AuthMcpClientAccess,
38
+): Promise<Result.Result<AuthPairingCredentialResult, unknown>> {
39
+ const result = await mintMcpApprovalCode.run(appAtomRegistry, { environmentId, input: access });
40
+ return result._tag === "Success"
41
+ ? Result.succeed(result.value)
42
+ : Result.fail(squashAtomCommandFailure(result));
43
+}
docs/user/outside-agents.md
+26
-6
@@ -6,6 +6,24 @@ check which providers and models are available. This covers Claude Code or
6
Codex in your own terminal, ChatGPT, and bots that support MCP. Each agent signs
7
in once, and you choose what it may do.
8
9
+## Add T3 Code to an assistant app
10
+
11
+Open the command palette (`Cmd/Ctrl+K`) and choose **Use T3 Code in another
12
+app (MCP)**, or use the button in **Settings → Sharing & access**. Pick the
13
+app, choose what it may do, and follow the step for that app. Assistants like
14
+Poke and Claude run in the cloud, so the wizard first asks you to sign in to T3
15
+Connect and turn it on for the environment. To reach your other machines through
16
+the same connection, turn on **Linked environments** in Labs and
17
+[link them](./remote-access.md#link-another-environment).
18
+
19
+When the app opens the sign-in page, choose **Get code** in the wizard and paste
20
+the code there. A code works once, for 5 minutes, and approves only the level
21
+you chose.
22
+
23
+For an app that is not listed, choose **Something else…**, add a remote MCP
24
+server with OAuth in that app, and paste the URL. Apps that require their own
25
+client ID cannot connect.
26
+
27
## Get the MCP URL
28
29
In **Settings → Environments**, open a saved environment's menu and choose
@@ -41,13 +59,15 @@ The page names the agent and where its access goes:
59
- For a hosted agent, approval goes to that service, such as `chatgpt.com`.
60
Anyone who runs that service gets the access.
61
44
-Only approve a sign-in you just started. To approve, enter a pairing code from
45
-**Settings → Sharing & access** or from `t3 auth pairing create` on the host. A
46
-browser already signed in to the environment with permission to manage access
47
-can approve without a code.
62
+Only approve a sign-in you just started. To approve, enter a code from
63
+**Use T3 Code in another app (MCP)**, **Settings → Sharing & access**, or
64
+`t3 auth pairing create` on the host. A browser already signed in to the
65
+environment with permission to manage access can approve without a code.
66
49
-Then choose what the agent may do. **Auto** is selected by default, or the
50
-closest lower mode allowed by your organization’s policy:
67
+A code from **Use T3 Code in another app (MCP)** already carries the level you
68
+picked there. With another code, choose what the agent may do here: **Auto** is
69
+selected by default, or the closest lower mode allowed by your organization’s
70
+policy. Approving without a code starts at **Read only**:
71
72
- **Read only** lets the agent read projects and threads and see
73
the available providers and models. It cannot change anything.
packages/client-runtime/src/state/peerPairingCode.ts
+47
-24
@@ -1,9 +1,15 @@
1
/**
2
- * A one-use pairing code for linking, minted on the environment being linked to with the
3
- * user's own session there, so a link card can be answered without fetching a code by hand.
4
- * It carries exactly what an agent sign-in with the chosen access needs.
2
+ * One-use pairing codes minted on an environment with the user's own session there: a code
3
+ * for linking, so a link card can be answered without fetching a code by hand, and a code
4
+ * that approves one app's sign-in at a set level. Each carries exactly what an agent
5
+ * sign-in with the chosen access needs.
6
*/
6
-import { type AuthMcpClientAccess, mcpClientScopes } from "@t3tools/contracts";
7
+import {
8
+ type AuthCreatePairingCredentialInput,
9
+ type AuthMcpClientAccess,
10
+ type AuthPairingCredentialResult,
11
+ mcpClientScopes,
12
+} from "@t3tools/contracts";
13
import * as Schema from "effect/Schema";
14
import * as Effect from "effect/Effect";
15
import type * as HttpClient from "effect/http/HttpClient";
@@ -21,6 +27,7 @@ import { createEnvironmentCommand } from "./runtime.ts";
27
28
const MINT_TIMEOUT_MS = 8_000;
29
const PEER_PAIRING_CODE_LABEL = "T3 Code link";
30
+const MCP_APPROVAL_CODE_LABEL = "App sign-in";
31
32
/** Minting failed; the user can still paste a code from the other environment. */
33
export class PeerPairingCodeError extends Schema.TaggedError<PeerPairingCodeError>()(
@@ -37,10 +44,10 @@ export class PeerPairingCodeError extends Schema.TaggedError<PeerPairingCodeErro
44
}
45
}
46
40
-const mintPeerPairingCode = Effect.fn("clientRuntime.state.mintPeerPairingCode")(function* (
47
+const mintPairingCredential = Effect.fn("clientRuntime.state.mintPairingCredential")(function* (
48
prepared: PreparedConnection,
42
- access: AuthMcpClientAccess,
43
-): Effect.fn.Return<string, PeerPairingCodeError, HttpClient.HttpClient> {
49
+ payload: AuthCreatePairingCredentialInput,
50
+): Effect.fn.Return<AuthPairingCredentialResult, PeerPairingCodeError, HttpClient.HttpClient> {
51
const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
52
const remoteAuthorization = yield* Effect.serviceOption(
53
RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
@@ -53,11 +60,7 @@ const mintPeerPairingCode = Effect.fn("clientRuntime.state.mintPeerPairingCode")
60
method: "POST",
61
url: (urls) => urls.pairingCredential(),
62
timeoutMs: MINT_TIMEOUT_MS,
56
- request: ({ client, headers }) =>
57
- client.pairingCredential({
58
- headers,
59
- payload: { label: PEER_PAIRING_CODE_LABEL, scopes: mcpClientScopes(access) },
60
- }),
63
+ request: ({ client, headers }) => client.pairingCredential({ headers, payload }),
64
}).pipe(
65
Effect.mapError(
66
(cause) =>
@@ -71,7 +74,20 @@ const mintPeerPairingCode = Effect.fn("clientRuntime.state.mintPeerPairingCode")
74
}),
75
),
76
);
74
- return minted.credential;
77
+ return minted;
78
+});
79
+
80
+// Untraced: mintPairingCredential owns the span.
81
+const mintOnEnvironment = Effect.fnUntraced(function* (payload: AuthCreatePairingCredentialInput) {
82
+ const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
83
+ const prepared = yield* SubscriptionRef.get(supervisor.prepared);
84
+ if (Option.isNone(prepared)) {
85
+ return yield* new PeerPairingCodeError({
86
+ reason: "unavailable",
87
+ cause: "The environment is not connected.",
88
+ });
89
+ }
90
+ return yield* mintPairingCredential(prepared.value, payload);
91
});
92
93
/**
@@ -83,16 +99,23 @@ export function createPeerPairingCodeCommand<R, E>(
99
) {
100
return createEnvironmentCommand(runtime, {
101
label: "environment-data:peer-pairing-code:mint",
86
- execute: Effect.fn(function* (access: AuthMcpClientAccess) {
87
- const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
88
- const prepared = yield* SubscriptionRef.get(supervisor.prepared);
89
- if (Option.isNone(prepared)) {
90
- return yield* new PeerPairingCodeError({
91
- reason: "unavailable",
92
- cause: "The environment is not connected.",
93
- });
94
- }
95
- return yield* mintPeerPairingCode(prepared.value, access);
96
- }),
102
+ execute: (access: AuthMcpClientAccess) =>
103
+ mintOnEnvironment({ label: PEER_PAIRING_CODE_LABEL, scopes: mcpClientScopes(access) }).pipe(
104
+ Effect.map((minted) => minted.credential),
105
+ ),
106
+ });
107
+}
108
+
109
+/**
110
+ * Mints a hidden code that approves one app's sign-in at `access`, and only that. Servers
111
+ * without `mcpApprovalCodes` ignore the level, so check the capability first.
112
+ */
113
+export function createMcpApprovalCodeCommand<R, E>(
114
+ runtime: Atom.AtomRuntime<EnvironmentRegistry | HttpClient.HttpClient | R, E>,
115
+) {
116
+ return createEnvironmentCommand(runtime, {
117
+ label: "environment-data:mcp-approval-code:mint",
118
+ execute: (access: AuthMcpClientAccess) =>
119
+ mintOnEnvironment({ label: MCP_APPROVAL_CODE_LABEL, access }),
120
});
121
}
packages/contracts/src/auth.ts
+60
-22
@@ -255,11 +255,69 @@ export type AuthWebSocketTicketUse = typeof AuthWebSocketTicketUse.Type;
255
256
export const AuthWebSocketTicketParams = Schema.Struct({ use: AuthWebSocketTicketUse });
257
258
+export const AuthMcpClientAccess = Schema.Literals([
259
+ "read-only",
260
+ "approval-required",
261
+ "auto-accept-edits",
262
+ "auto",
263
+ "full-access",
264
+]);
265
+export type AuthMcpClientAccess = typeof AuthMcpClientAccess.Type;
266
+
267
+/** The scopes an agent session gets for an access level, and a pairing code must carry. */
268
+export const mcpClientScopes = (access: AuthMcpClientAccess): ReadonlyArray<AuthGrantScope> =>
269
+ access === "read-only"
270
+ ? [AuthOrchestrationReadScope]
271
+ : access === "full-access"
272
+ ? [
273
+ AuthOrchestrationReadScope,
274
+ AuthOrchestrationOperateScope,
275
+ AuthSettingsWriteScope,
276
+ AuthSourceControlWriteScope,
277
+ ]
278
+ : [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
279
+
280
+/** The random part of a one-time pairing code: this many characters from this alphabet. */
281
+export const PAIRING_CODE_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
282
+export const PAIRING_CODE_LENGTH = 12;
283
+
284
+const MCP_APPROVAL_CODE_PREFIXES = {
285
+ "read-only": "READ",
286
+ "approval-required": "SUPERVISED",
287
+ "auto-accept-edits": "EDITS",
288
+ auto: "AUTO",
289
+ "full-access": "FULL",
290
+} as const satisfies Record<AuthMcpClientAccess, string>;
291
+
292
+const MCP_APPROVAL_CODE_PATTERN = new RegExp(
293
+ `^(${Object.values(MCP_APPROVAL_CODE_PREFIXES).join("|")})-([${PAIRING_CODE_ALPHABET}]{${PAIRING_CODE_LENGTH}})$`,
294
+ "i",
295
+);
296
+
297
+/** A pairing code that approves one agent sign-in at `access`, such as `AUTO-Q8RZ3NWD5KTC`. */
298
+export const mcpApprovalCode = (access: AuthMcpClientAccess, token: string): string =>
299
+ `${MCP_APPROVAL_CODE_PREFIXES[access]}-${token}`;
300
+
301
+/** The level a code approves and the code as issued, or undefined for any other code. */
302
+export function parseMcpApprovalCode(
303
+ code: string,
304
+): { readonly access: AuthMcpClientAccess; readonly code: string } | undefined {
305
+ const match = MCP_APPROVAL_CODE_PATTERN.exec(code.trim());
306
+ if (match === null) return undefined;
307
+ const prefix = match[1]!.toUpperCase();
308
+ const access = AuthMcpClientAccess.literals.find(
309
+ (level) => MCP_APPROVAL_CODE_PREFIXES[level] === prefix,
310
+ );
311
+ return access && { access, code: mcpApprovalCode(access, match[2]!.toUpperCase()) };
312
+}
313
+
314
export const AuthPairingCredentialResult = Schema.Struct({
315
id: TrimmedNonEmptyString,
316
credential: TrimmedNonEmptyString,
317
label: Schema.optionalKey(TrimmedNonEmptyString),
318
expiresAt: Schema.DateTimeUtc,
319
+ /** Set when the code approves one agent sign-in at this level. Older servers omit it. */
320
+ access: Schema.optionalKey(AuthMcpClientAccess),
321
});
322
export type AuthPairingCredentialResult = typeof AuthPairingCredentialResult.Type;
323
@@ -387,6 +445,8 @@ export type AuthRevokeClientSessionInput = typeof AuthRevokeClientSessionInput.T
445
export const AuthCreatePairingCredentialInput = Schema.Struct({
446
label: Schema.optionalKey(TrimmedNonEmptyString),
447
scopes: Schema.optionalKey(AuthGrantScopes),
448
+ /** Binds the code to one agent sign-in at this level. The server derives the scopes from it. */
449
+ access: Schema.optionalKey(AuthMcpClientAccess),
450
});
451
export type AuthCreatePairingCredentialInput = typeof AuthCreatePairingCredentialInput.Type;
452
@@ -400,28 +460,6 @@ export const AuthSessionState = Schema.Struct({
460
});
461
export type AuthSessionState = typeof AuthSessionState.Type;
462
403
-export const AuthMcpClientAccess = Schema.Literals([
404
- "read-only",
405
- "approval-required",
406
- "auto-accept-edits",
407
- "auto",
408
- "full-access",
409
-]);
410
-export type AuthMcpClientAccess = typeof AuthMcpClientAccess.Type;
411
-
412
-/** The scopes an agent session gets for an access level, and a pairing code must carry. */
413
-export const mcpClientScopes = (access: AuthMcpClientAccess): ReadonlyArray<AuthGrantScope> =>
414
- access === "read-only"
415
- ? [AuthOrchestrationReadScope]
416
- : access === "full-access"
417
- ? [
418
- AuthOrchestrationReadScope,
419
- AuthOrchestrationOperateScope,
420
- AuthSettingsWriteScope,
421
- AuthSourceControlWriteScope,
422
- ]
423
- : [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
424
-
463
export const AuthMcpProtectedResourceMetadata = Schema.Struct({
464
resource: Schema.String,
465
authorization_servers: Schema.Array(Schema.String),
packages/contracts/src/environment.ts
+2
@@ -167,6 +167,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
167
(`linkOrigin`). Another environment links to this one only when it is
168
set, since without it that work could change the user's own threads. */
169
linkFence: Schema.optionalKey(Schema.Boolean),
170
+ /** Mints pairing codes that approve one agent sign-in at a set level (`AUTO-…`). */
171
+ mcpApprovalCodes: Schema.optionalKey(Schema.Boolean),
172
/** Server answers server.prepareTriage. */
173
triage: Schema.optionalKey(Schema.Boolean),
174
/** Server accepts `{ type: "once" }` scheduled tasks; older servers reject them on save. */
packages/contracts/src/environmentHttp.ts
+4
@@ -523,6 +523,10 @@ export const EnvironmentCloudLinkStateResult = Schema.Struct({
523
linkRevoked: Schema.optional(Schema.Boolean),
524
/** The latest check the server ran on its own, absent until one finishes. */
525
reachability: Schema.optional(EnvironmentConnectReachability),
526
+ /** The tunnel's public hostname, once cloudflared has connected. Older servers omit it. */
527
+ tunnelHostname: Schema.optional(Schema.String),
528
+ /** Whether this is the desktop app's own session, which may link from where it is. */
529
+ linkableHere: Schema.optional(Schema.Boolean),
530
});
531
export type EnvironmentCloudLinkStateResult = typeof EnvironmentCloudLinkStateResult.Type;
532