@devries-cameron20 / t3code Mirror · read-only / commits / 669d8941e2
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

feat: sign in to an agent's MCP server from its warning (#39921)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 20, 2026 at 16:40 UTC 669d8941e270e6a26f5d51de6b6e8c7f48e88f70
49 files changed +1593 -51
apps/mobile/src/features/threads/McpSignInSheet.tsx new
+175
@@ -0,0 +1,175 @@
1 +import type { EnvironmentId, ProviderThreadId, ThreadId } from "@t3tools/contracts";
2 +import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3 +import {
4 + type AtomCommandResult,
5 + isAtomCommandInterrupted,
6 + squashAtomCommandFailure,
7 +} from "@t3tools/client-runtime/state/runtime";
8 +import * as Haptics from "expo-haptics";
9 +import { msg, T, useGT, useMessages } from "gt-react-native";
10 +import { useRef, useState } from "react";
11 +import { ScrollView } from "react-native";
12 +import { useSafeAreaInsets } from "react-native-safe-area-context";
13 +
14 +import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
15 +import { Button } from "../../components/ui/Button";
16 +import { Sheet } from "../../components/ui/Sheet";
17 +import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
18 +import { threadEnvironment } from "../../state/threads";
19 +import { useAtomCommand } from "../../state/use-atom-command";
20 +
21 +export interface McpSignInTarget {
22 + readonly threadId: ThreadId;
23 + readonly providerThreadId: ProviderThreadId;
24 + readonly server: string;
25 +}
26 +
27 +/**
28 + * Signs an agent's MCP server in from the notice that says it needs one. The
29 + * agent keeps the credential; the user approves in a browser, then pastes back
30 + * the address it lands on, which is often a localhost page on another machine.
31 + */
32 +export function McpSignInSheet(props: {
33 + readonly environmentId: EnvironmentId;
34 + readonly target: McpSignInTarget;
35 + readonly onClose: () => void;
36 +}) {
37 + const gt = useGT();
38 + const m = useMessages();
39 + const insets = useSafeAreaInsets();
40 + const { server } = props.target;
41 + const start = useAtomCommand(threadEnvironment.mcpSignInStart, {
42 + label: "start MCP sign-in",
43 + reportFailure: false,
44 + reportDefect: false,
45 + });
46 + const complete = useAtomCommand(threadEnvironment.mcpSignInComplete, {
47 + label: "finish MCP sign-in",
48 + reportFailure: false,
49 + reportDefect: false,
50 + });
51 + const [url, setUrl] = useState<string | null>(null);
52 + const [callbackUrl, setCallbackUrl] = useState("");
53 + const [busy, setBusy] = useState(false);
54 + const [error, setError] = useState<string | null>(null);
55 + // A result that lands after the sheet closed must not open a browser or report anything.
56 + const closed = useRef(false);
57 + const close = () => {
58 + closed.current = true;
59 + props.onClose();
60 + };
61 +
62 + const failed = (result: AtomCommandResult<unknown, unknown> & { readonly _tag: "Failure" }) => {
63 + if (isAtomCommandInterrupted(result)) return;
64 + setError(
65 + errorDisplayMessage(squashAtomCommandFailure(result), m) ??
66 + m(msg("The sign-in couldn't continue. Try again.")),
67 + );
68 + };
69 + // The command marks the server signed in for the thread, which every notice about it shows.
70 + const signedIn = () => {
71 + void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
72 + close();
73 + };
74 + const openSignInPage = async () => {
75 + setBusy(true);
76 + setError(null);
77 + let page = url;
78 + if (page === null) {
79 + const result = await start({ environmentId: props.environmentId, input: props.target });
80 + if (closed.current) return;
81 + if (result._tag === "Failure") {
82 + setBusy(false);
83 + failed(result);
84 + return;
85 + }
86 + if (result.value.authorizationUrl === null) {
87 + setBusy(false);
88 + signedIn();
89 + return;
90 + }
91 + page = result.value.authorizationUrl;
92 + setUrl(page);
93 + }
94 + setBusy(false);
95 + if (!(await tryOpenExternalUrl(page, "provider-auth"))) {
96 + setError(gt("Could not open the sign-in page."));
97 + }
98 + };
99 + const finish = async () => {
100 + const pasted = callbackUrl.trim();
101 + if (pasted.length === 0) return;
102 + setBusy(true);
103 + setError(null);
104 + const result = await complete({
105 + environmentId: props.environmentId,
106 + input: { ...props.target, callbackUrl: pasted },
107 + });
108 + if (closed.current) return;
109 + setBusy(false);
110 + if (result._tag === "Success") signedIn();
111 + else failed(result);
112 + };
113 +
114 + return (
115 + <Sheet title={gt("Sign in to {server}", { server })} onClose={close}>
116 + <ScrollView
117 + className="flex-1 bg-sheet-solid"
118 + contentInsetAdjustmentBehavior="automatic"
119 + contentContainerClassName="gap-5 p-5"
120 + contentContainerStyle={{ paddingBottom: insets.bottom + 20 }}
121 + keyboardShouldPersistTaps="handled"
122 + >
123 + <Text className="font-sans text-sm leading-5 text-foreground-muted">
124 + <T>
125 + Approve access in your browser. It then opens a page that may not load: copy that page's
126 + address and paste it here.
127 + </T>
128 + </Text>
129 + <Button
130 + label={gt("Open sign-in page")}
131 + icon="globe"
132 + tone="secondary"
133 + disabled={busy}
134 + onPress={() => void openSignInPage()}
135 + fullWidth
136 + />
137 + {url !== null ? (
138 + <TextInput
139 + accessibilityLabel={gt("Address of the page your browser opened")}
140 + placeholder="http://127.0.0.1:…/callback?code=…"
141 + value={callbackUrl}
142 + onChangeText={setCallbackUrl}
143 + editable={!busy}
144 + autoCorrect={false}
145 + autoCapitalize="none"
146 + keyboardType="url"
147 + spellCheck={false}
148 + returnKeyType="done"
149 + onSubmitEditing={() => void finish()}
150 + />
151 + ) : null}
152 + {error !== null ? (
153 + <Text
154 + accessibilityRole="alert"
155 + accessibilityLiveRegion="polite"
156 + className="font-sans text-sm text-danger-foreground"
157 + >
158 + {error}
159 + </Text>
160 + ) : null}
161 + {url !== null ? (
162 + <Button
163 + label={gt("Finish sign-in")}
164 + tone="primary"
165 + loading={busy}
166 + disabled={busy || callbackUrl.trim().length === 0}
167 + onPress={() => void finish()}
168 + fullWidth
169 + />
170 + ) : null}
171 + <Button label={gt("Cancel")} tone="secondary" onPress={close} fullWidth />
172 + </ScrollView>
173 + </Sheet>
174 + );
175 +}
apps/mobile/src/features/threads/thread-work-log.tsx
+72 -8
@@ -9,6 +9,7 @@ import {
9 WorkLogPressable,
10 } from "./work-log-layout";
11 import { QuestionAnswerHistory } from "./QuestionAnswerHistory";
12 +import { McpSignInSheet, type McpSignInTarget } from "./McpSignInSheet";
13 import { ThreadCommandOutput, useCommandOutputStreaming } from "./thread-command-output";
14 import {
15 getQuestionAnswerPreview,
@@ -51,6 +52,8 @@ import {
52 type ToolActivityIcon,
53 } from "@t3tools/contracts";
54 import { useAtomValue } from "@effect/atom-react";
55 +import { Atom } from "effect/reactivity";
56 +import * as DateTime from "effect/DateTime";
57 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
58 import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
59 import { useAtomCommand } from "../../state/use-atom-command";
@@ -866,6 +869,9 @@ function HighlightedCodeText({
869 );
870 }
871
872 +// Rows that aren't sign-in notices read this, so every row reads an atom.
873 +const NOT_SIGNED_IN = Atom.make(false);
874 +
875 const ThreadWorkLogRow = function ThreadWorkLogRow(
876 props: Omit<
877 ThreadWorkLogProps,
@@ -886,6 +892,20 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
892 const gt = useGT();
893 const messages = useMessages();
894 const openLinkedThread = useOpenLinkedThread();
895 + const canSignInToMcp = useAtomValue(
896 + threadEnvironment.mcpSignInStart.permissionAtom(props.environmentId),
897 + );
898 + const [mcpSignInOpen, setMcpSignInOpen] = useState(false);
899 + const signInNotice = row.projectedItem.item;
900 + const mcpSignedIn = useAtomValue(
901 + signInNotice.type === "system_notice" && signInNotice.mcpSignIn !== undefined
902 + ? threadEnvironment.mcpSignedInAtom(props.environmentId, {
903 + threadId: signInNotice.threadId,
904 + server: signInNotice.mcpSignIn.server,
905 + noticeAt: DateTime.toEpochMillis(signInNotice.updatedAt),
906 + })
907 + : NOT_SIGNED_IN,
908 + );
909 const streamsOutput =
910 useCommandOutputStreaming(props.environmentId) &&
911 row.projectedItem.item.type === "command_execution";
@@ -982,7 +1002,22 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
1002 row.projectedItem.item.type === "notification"
1003 ? notificationChildThreadId(row.projectedItem.item.source)
1004 : undefined;
985 - const canExpand = row.canExpand && notifiedSubagentThreadId === undefined;
1005 + const notice = row.projectedItem.item;
1006 + const mcpSignInTarget: McpSignInTarget | null =
1007 + canSignInToMcp &&
1008 + notice.type === "system_notice" &&
1009 + notice.mcpSignIn !== undefined &&
1010 + notice.providerThreadId !== null
1011 + ? {
1012 + threadId: notice.threadId,
1013 + providerThreadId: notice.providerThreadId,
1014 + server: notice.mcpSignIn.server,
1015 + }
1016 + : null;
1017 + // Signed in, the notice is an ordinary row again.
1018 + const opensMcpSignIn = mcpSignInTarget !== null && !mcpSignedIn;
1019 + // A sign-in notice opens its sheet instead; a nested button would be out of VoiceOver's reach.
1020 + const canExpand = row.canExpand && notifiedSubagentThreadId === undefined && !opensMcpSignIn;
1021 const reasoning = row.projectedItem.item.type === "reasoning" ? row.projectedItem.item : null;
1022 const fetchedItem = fetchedDetail.data?.item ?? null;
1023 const isRead = toolGroupAction(row.workEntry) === "read";
@@ -1057,21 +1092,29 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
1092 >
1093 <WorkLogPressable
1094 accessibilityRole={
1060 - notifiedSubagentThreadId !== undefined ? "link" : canExpand ? "button" : undefined
1095 + notifiedSubagentThreadId !== undefined
1096 + ? "link"
1097 + : canExpand || opensMcpSignIn
1098 + ? "button"
1099 + : undefined
1100 }
1101 accessibilityLabel={
1102 failed
1103 ? gt("{preview}, tool call failed", { preview: accessiblePreview })
1065 - : accessiblePreview
1104 + : mcpSignInTarget !== null && mcpSignedIn
1105 + ? gt("{preview}, signed in", { preview: accessiblePreview })
1106 + : accessiblePreview
1107 }
1108 accessibilityHint={
1109 notifiedSubagentThreadId !== undefined
1110 ? gt("Opens this agent's thread. Long press to copy.")
1070 - : canExpand
1071 - ? expanded
1072 - ? gt("Double tap to hide full details. Long press to copy.")
1073 - : gt("Double tap to show full details. Long press to copy.")
1074 - : gt("Long press to copy.")
1111 + : opensMcpSignIn
1112 + ? gt("Opens the sign-in. Long press to copy.")
1113 + : canExpand
1114 + ? expanded
1115 + ? gt("Double tap to hide full details. Long press to copy.")
1116 + : gt("Double tap to show full details. Long press to copy.")
1117 + : gt("Long press to copy.")
1118 }
1119 accessibilityState={canExpand ? { expanded } : undefined}
1120 onPress={() => {
@@ -1082,6 +1125,11 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
1125 });
1126 return;
1127 }
1128 + if (opensMcpSignIn) {
1129 + void Haptics.selectionAsync();
1130 + setMcpSignInOpen(true);
1131 + return;
1132 + }
1133 if (canExpand) {
1134 void Haptics.selectionAsync();
1135 props.onToggleRow(row.id, props.anchorKey, row.groupStandIn?.groupId);
@@ -1150,6 +1198,15 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
1198 <Text className="pr-1 font-t3-medium text-3xs text-adaptive-emerald-600-400">
1199 <T>Copied</T>
1200 </Text>
1201 + ) : mcpSignInTarget !== null ? (
1202 + <Text
1203 + className={cn(
1204 + "pr-1 font-t3-medium text-sm",
1205 + mcpSignedIn ? "text-adaptive-emerald-600-400" : "text-primary",
1206 + )}
1207 + >
1208 + {mcpSignedIn ? <T>Signed in</T> : <T>Sign in</T>}
1209 + </Text>
1210 ) : null}
1211 {failed && toolIcon !== undefined ? (
1212 <View
@@ -1177,6 +1234,13 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
1234 </View>
1235 </View>
1236 </WorkLogPressable>
1237 + {mcpSignInOpen && mcpSignInTarget !== null ? (
1238 + <McpSignInSheet
1239 + environmentId={props.environmentId}
1240 + target={mcpSignInTarget}
1241 + onClose={() => setMcpSignInOpen(false)}
1242 + />
1243 + ) : null}
1244
1245 {expanded &&
1246 (reasoning ||
apps/mobile/src/i18n/translations/de.json
+9
@@ -4223,6 +4223,14 @@
4223 },
4224 " kann nicht geladen werden"
4225 ],
4226 + "15f32e12fd49533f": "Die Anmeldung konnte nicht fortgesetzt werden. Versuche es erneut.",
4227 + "54789628a737f557": "Bei {server} anmelden",
4228 + "f8fde2e549c61546": "Adresse der Seite, die dein Browser geöffnet hat",
4229 + "d9f6244b252d11f6": "Anmeldung abschließen",
4230 + "8aecbd38f1facf71": "Erlaube den Zugriff in deinem Browser. Danach öffnet er eine Seite, die vielleicht nicht lädt: Kopiere die Adresse dieser Seite und füge sie hier ein.",
4231 + "6e5bcc452add4f9b": "Öffnet die Anmeldung. Lange drücken zum Kopieren.",
4232 + "83be7aade7ff6360": "Angemeldet",
4233 + "ec21b232e0eacd4a": "Anmelden",
4234 "12ba9fa1445f92a2": "Arbeit der Subagenten",
4235 "eaa6c91a05d95ce7": "Aktualisieren",
4236 "4740c38b2edd194d": "Nur lesen. Diese Subagenten können keine Nachrichten annehmen.",
@@ -4825,6 +4833,7 @@
4833 "bff5692f10fc10b0": "Lange drücken zum Kopieren.",
4834 "7f0f9b1ee42892db": "Die Ausgabe ist nicht mehr verfügbar.",
4835 "a1984c617f973156": "{preview}, Tool-Aufruf fehlgeschlagen",
4836 + "38574c0d1e49b278": "{preview}, angemeldet",
4837 "fd0d04d5a6627f70": "Öffnet den Thread dieses Agenten. Lange drücken zum Kopieren.",
4838 "7ba47e54094ba298": "Doppeltippen, um alle Details auszublenden. Lange drücken zum Kopieren.",
4839 "1862ffb47bf6736c": "Doppeltippen, um alle Details anzuzeigen. Lange drücken zum Kopieren.",
apps/mobile/src/i18n/translations/en.json
+9
@@ -4224,6 +4224,14 @@
4224 },
4225 " app"
4226 ],
4227 + "15f32e12fd49533f": "The sign-in couldn't continue. Try again.",
4228 + "54789628a737f557": "Sign in to {server}",
4229 + "f8fde2e549c61546": "Address of the page your browser opened",
4230 + "d9f6244b252d11f6": "Finish sign-in",
4231 + "8aecbd38f1facf71": "Approve access in your browser. It then opens a page that may not load: copy that page's address and paste it here.",
4232 + "6e5bcc452add4f9b": "Opens the sign-in. Long press to copy.",
4233 + "83be7aade7ff6360": "Signed in",
4234 + "ec21b232e0eacd4a": "Sign in",
4235 "12ba9fa1445f92a2": "Subagent work",
4236 "eaa6c91a05d95ce7": "Refresh",
4237 "4740c38b2edd194d": "Read only. These subagents cannot take messages.",
@@ -4826,6 +4834,7 @@
4834 "bff5692f10fc10b0": "Long press to copy.",
4835 "7f0f9b1ee42892db": "Output is no longer available.",
4836 "a1984c617f973156": "{preview}, tool call failed",
4837 + "38574c0d1e49b278": "{preview}, signed in",
4838 "fd0d04d5a6627f70": "Opens this agent's thread. Long press to copy.",
4839 "7ba47e54094ba298": "Double tap to hide full details. Long press to copy.",
4840 "1862ffb47bf6736c": "Double tap to show full details. Long press to copy.",
apps/mobile/src/i18n/translations/es.json
+9
@@ -4216,6 +4216,14 @@
4216 "v": "v"
4217 }
4218 ],
4219 + "15f32e12fd49533f": "No se pudo continuar con el inicio de sesión. Vuelve a intentarlo.",
4220 + "54789628a737f557": "Iniciar sesión en {server}",
4221 + "f8fde2e549c61546": "Dirección de la página que abrió tu navegador",
4222 + "d9f6244b252d11f6": "Terminar de iniciar sesión",
4223 + "8aecbd38f1facf71": "Aprueba el acceso en tu navegador. Después abrirá una página que puede no cargar: copia la dirección de esa página y pégala aquí.",
4224 + "6e5bcc452add4f9b": "Abre el inicio de sesión. Mantén pulsado para copiar.",
4225 + "83be7aade7ff6360": "Sesión iniciada",
4226 + "ec21b232e0eacd4a": "Iniciar sesión",
4227 "12ba9fa1445f92a2": "Trabajo del subagente",
4228 "eaa6c91a05d95ce7": "Actualizar",
4229 "4740c38b2edd194d": "Solo lectura. Estos subagentes no pueden recibir mensajes.",
@@ -4818,6 +4826,7 @@
4826 "bff5692f10fc10b0": "Mantén pulsado para copiar.",
4827 "7f0f9b1ee42892db": "La salida ya no está disponible.",
4828 "a1984c617f973156": "{preview}, falló la llamada a la herramienta",
4829 + "38574c0d1e49b278": "{preview}, sesión iniciada",
4830 "fd0d04d5a6627f70": "Abre el hilo de este agente. Mantén pulsado para copiar.",
4831 "7ba47e54094ba298": "Toca dos veces para ocultar los detalles completos. Mantén pulsado para copiar.",
4832 "1862ffb47bf6736c": "Toca dos veces para mostrar los detalles completos. Mantén pulsado para copiar.",
apps/mobile/src/i18n/translations/fr.json
+9
@@ -4217,6 +4217,14 @@
4217 "v": "v"
4218 }
4219 ],
4220 + "15f32e12fd49533f": "Impossible de poursuivre la connexion. Réessayez.",
4221 + "54789628a737f557": "Se connecter à {server}",
4222 + "f8fde2e549c61546": "Adresse de la page ouverte par votre navigateur",
4223 + "d9f6244b252d11f6": "Terminer la connexion",
4224 + "8aecbd38f1facf71": "Autorisez l’accès dans votre navigateur. Il ouvre ensuite une page qui peut ne pas se charger : copiez l’adresse de cette page et collez-la ici.",
4225 + "6e5bcc452add4f9b": "Ouvre la connexion. Appuyez longuement pour copier.",
4226 + "83be7aade7ff6360": "Connecté",
4227 + "ec21b232e0eacd4a": "Se connecter",
4228 "12ba9fa1445f92a2": "Travail des sous-agents",
4229 "eaa6c91a05d95ce7": "Actualiser",
4230 "4740c38b2edd194d": "Lecture seule. Ces sous-agents ne peuvent pas recevoir de messages.",
@@ -4819,6 +4827,7 @@
4827 "bff5692f10fc10b0": "Appuyez longuement pour copier.",
4828 "7f0f9b1ee42892db": "La sortie n’est plus disponible.",
4829 "a1984c617f973156": "{preview}, échec de l’appel d’outil",
4830 + "38574c0d1e49b278": "{preview}, connecté",
4831 "fd0d04d5a6627f70": "Ouvre le fil de cet agent. Appuyez longuement pour copier.",
4832 "7ba47e54094ba298": "Touchez deux fois pour masquer tous les détails. Appuyez longuement pour copier.",
4833 "1862ffb47bf6736c": "Touchez deux fois pour afficher tous les détails. Appuyez longuement pour copier.",
apps/mobile/src/i18n/translations/ja.json
+9
@@ -4210,6 +4210,14 @@
4210 },
4211 " アプリを読み込めません"
4212 ],
4213 + "15f32e12fd49533f": "サインインを続行できませんでした。もう一度お試しください。",
4214 + "54789628a737f557": "{server} にサインイン",
4215 + "f8fde2e549c61546": "ブラウザーが開いたページのアドレス",
4216 + "d9f6244b252d11f6": "サインインを完了",
4217 + "8aecbd38f1facf71": "ブラウザーでアクセスを許可してください。その後、読み込まれない場合があるページが開きます。そのページのアドレスをコピーして、ここに貼り付けてください。",
4218 + "6e5bcc452add4f9b": "サインインを開きます。長押しでコピーします。",
4219 + "83be7aade7ff6360": "サインイン済み",
4220 + "ec21b232e0eacd4a": "サインイン",
4221 "12ba9fa1445f92a2": "サブエージェントの作業",
4222 "eaa6c91a05d95ce7": "更新",
4223 "4740c38b2edd194d": "読み取り専用です。これらのサブエージェントはメッセージを受け付けません。",
@@ -4800,6 +4808,7 @@
4808 "bff5692f10fc10b0": "長押しでコピーします。",
4809 "7f0f9b1ee42892db": "出力は利用できなくなりました。",
4810 "a1984c617f973156": "{preview}、ツール呼び出しに失敗",
4811 + "38574c0d1e49b278": "{preview}、サインイン済み",
4812 "fd0d04d5a6627f70": "このエージェントのスレッドを開きます。長押しでコピーします。",
4813 "7ba47e54094ba298": "ダブルタップで詳細を非表示にします。長押しでコピーします。",
4814 "1862ffb47bf6736c": "ダブルタップで詳細を表示します。長押しでコピーします。",
apps/mobile/src/i18n/translations/ko.json
+9
@@ -4214,6 +4214,14 @@
4214 },
4215 " 앱을 불러올 수 없습니다"
4216 ],
4217 + "15f32e12fd49533f": "로그인을 계속할 수 없습니다. 다시 시도하세요.",
4218 + "54789628a737f557": "{server}에 로그인",
4219 + "f8fde2e549c61546": "브라우저가 연 페이지의 주소",
4220 + "d9f6244b252d11f6": "로그인 완료",
4221 + "8aecbd38f1facf71": "브라우저에서 액세스를 승인하세요. 그러면 로드되지 않을 수 있는 페이지가 열립니다. 그 페이지의 주소를 복사해 여기에 붙여넣으세요.",
4222 + "6e5bcc452add4f9b": "로그인을 엽니다. 길게 눌러 복사합니다.",
4223 + "83be7aade7ff6360": "로그인됨",
4224 + "ec21b232e0eacd4a": "로그인",
4225 "12ba9fa1445f92a2": "서브에이전트 작업",
4226 "eaa6c91a05d95ce7": "새로 고침",
4227 "4740c38b2edd194d": "읽기 전용입니다. 이 서브에이전트는 메시지를 받을 수 없습니다.",
@@ -4805,6 +4813,7 @@
4813 "bff5692f10fc10b0": "길게 눌러 복사합니다.",
4814 "7f0f9b1ee42892db": "출력을 더 이상 사용할 수 없습니다.",
4815 "a1984c617f973156": "{preview}, 도구 호출 실패",
4816 + "38574c0d1e49b278": "{preview}, 로그인됨",
4817 "fd0d04d5a6627f70": "이 에이전트의 스레드를 엽니다. 길게 눌러 복사합니다.",
4818 "7ba47e54094ba298": "두 번 탭하여 전체 세부 정보를 숨깁니다. 길게 눌러 복사합니다.",
4819 "1862ffb47bf6736c": "두 번 탭하여 전체 세부 정보를 표시합니다. 길게 눌러 복사합니다.",
apps/mobile/src/i18n/translations/pt-BR.json
+9
@@ -4217,6 +4217,14 @@
4217 "v": "v"
4218 }
4219 ],
4220 + "15f32e12fd49533f": "Não foi possível continuar o login. Tente novamente.",
4221 + "54789628a737f557": "Entrar em {server}",
4222 + "f8fde2e549c61546": "Endereço da página que o navegador abriu",
4223 + "d9f6244b252d11f6": "Concluir login",
4224 + "8aecbd38f1facf71": "Aprove o acesso no navegador. Depois ele abre uma página que pode não carregar: copie o endereço dessa página e cole aqui.",
4225 + "6e5bcc452add4f9b": "Abre o login. Mantenha pressionado para copiar.",
4226 + "83be7aade7ff6360": "Conectado",
4227 + "ec21b232e0eacd4a": "Entrar",
4228 "12ba9fa1445f92a2": "Trabalho de subagentes",
4229 "eaa6c91a05d95ce7": "Atualizar",
4230 "4740c38b2edd194d": "Somente leitura. Estes subagentes não aceitam mensagens.",
@@ -4819,6 +4827,7 @@
4827 "bff5692f10fc10b0": "Mantenha pressionado para copiar.",
4828 "7f0f9b1ee42892db": "A saída não está mais disponível.",
4829 "a1984c617f973156": "{preview}, a chamada de ferramenta falhou",
4830 + "38574c0d1e49b278": "{preview}, conectado",
4831 "fd0d04d5a6627f70": "Abre a thread deste agente. Mantenha pressionado para copiar.",
4832 "7ba47e54094ba298": "Toque duas vezes para ocultar os detalhes completos. Mantenha pressionado para copiar.",
4833 "1862ffb47bf6736c": "Toque duas vezes para mostrar os detalhes completos. Mantenha pressionado para copiar.",
apps/mobile/src/i18n/translations/ru.json
+9
@@ -4271,6 +4271,14 @@
4271 "v": "v"
4272 }
4273 ],
4274 + "15f32e12fd49533f": "Не удалось продолжить вход. Попробуйте ещё раз.",
4275 + "54789628a737f557": "Войти в {server}",
4276 + "f8fde2e549c61546": "Адрес страницы, которую открыл браузер",
4277 + "d9f6244b252d11f6": "Завершить вход",
4278 + "8aecbd38f1facf71": "Разрешите доступ в браузере. Затем он откроет страницу, которая может не загрузиться: скопируйте адрес этой страницы и вставьте его сюда.",
4279 + "6e5bcc452add4f9b": "Открывает вход. Нажмите и удерживайте, чтобы скопировать.",
4280 + "83be7aade7ff6360": "Вход выполнен",
4281 + "ec21b232e0eacd4a": "Войти",
4282 "12ba9fa1445f92a2": "Работа субагентов",
4283 "eaa6c91a05d95ce7": "Обновить",
4284 "4740c38b2edd194d": "Только чтение. Этим субагентам нельзя отправлять сообщения.",
@@ -4897,6 +4905,7 @@
4905 "bff5692f10fc10b0": "Нажмите и удерживайте, чтобы скопировать.",
4906 "7f0f9b1ee42892db": "Вывод больше недоступен.",
4907 "a1984c617f973156": "{preview}, вызов инструмента не удался",
4908 + "38574c0d1e49b278": "{preview}, вход выполнен",
4909 "fd0d04d5a6627f70": "Открывает тред этого агента. Нажмите и удерживайте, чтобы скопировать.",
4910 "7ba47e54094ba298": "Дважды нажмите, чтобы скрыть подробности. Нажмите и удерживайте, чтобы скопировать.",
4911 "1862ffb47bf6736c": "Дважды нажмите, чтобы показать подробности. Нажмите и удерживайте, чтобы скопировать.",
apps/mobile/src/i18n/translations/sv.json
+9
@@ -4223,6 +4223,14 @@
4223 "v": "v"
4224 }
4225 ],
4226 + "15f32e12fd49533f": "Inloggningen kunde inte fortsätta. Försök igen.",
4227 + "54789628a737f557": "Logga in på {server}",
4228 + "f8fde2e549c61546": "Adressen till sidan som webbläsaren öppnade",
4229 + "d9f6244b252d11f6": "Slutför inloggningen",
4230 + "8aecbd38f1facf71": "Godkänn åtkomsten i webbläsaren. Den öppnar sedan en sida som kanske inte laddas: kopiera sidans adress och klistra in den här.",
4231 + "6e5bcc452add4f9b": "Öppnar inloggningen. Tryck länge för att kopiera.",
4232 + "83be7aade7ff6360": "Inloggad",
4233 + "ec21b232e0eacd4a": "Logga in",
4234 "12ba9fa1445f92a2": "Subagentarbete",
4235 "eaa6c91a05d95ce7": "Uppdatera",
4236 "4740c38b2edd194d": "Endast läsning. De här subagenterna kan inte ta emot meddelanden.",
@@ -4825,6 +4833,7 @@
4833 "bff5692f10fc10b0": "Tryck länge för att kopiera.",
4834 "7f0f9b1ee42892db": "Utdata är inte längre tillgängliga.",
4835 "a1984c617f973156": "{preview}, verktygsanropet misslyckades",
4836 + "38574c0d1e49b278": "{preview}, inloggad",
4837 "fd0d04d5a6627f70": "Öppnar agentens tråd. Tryck länge för att kopiera.",
4838 "7ba47e54094ba298": "Dubbeltryck för att dölja alla detaljer. Tryck länge för att kopiera.",
4839 "1862ffb47bf6736c": "Dubbeltryck för att visa alla detaljer. Tryck länge för att kopiera.",
apps/mobile/src/i18n/translations/zh.json
+9
@@ -4218,6 +4218,14 @@
4218 },
4219 " 应用"
4220 ],
4221 + "15f32e12fd49533f": "无法继续登录。请重试。",
4222 + "54789628a737f557": "登录 {server}",
4223 + "f8fde2e549c61546": "浏览器打开的页面地址",
4224 + "d9f6244b252d11f6": "完成登录",
4225 + "8aecbd38f1facf71": "请在浏览器中批准访问。之后浏览器会打开一个可能无法加载的页面:复制该页面的地址并粘贴到这里。",
4226 + "6e5bcc452add4f9b": "打开登录。长按以复制。",
4227 + "83be7aade7ff6360": "已登录",
4228 + "ec21b232e0eacd4a": "登录",
4229 "12ba9fa1445f92a2": "子智能体工作",
4230 "eaa6c91a05d95ce7": "刷新",
4231 "4740c38b2edd194d": "只读。这些子智能体无法接收消息。",
@@ -4808,6 +4816,7 @@
4816 "bff5692f10fc10b0": "长按以复制。",
4817 "7f0f9b1ee42892db": "输出已不可用。",
4818 "a1984c617f973156": "{preview},工具调用失败",
4819 + "38574c0d1e49b278": "{preview},已登录",
4820 "fd0d04d5a6627f70": "打开此智能体的会话。长按以复制。",
4821 "7ba47e54094ba298": "轻点两下以隐藏完整详情。长按以复制。",
4822 "1862ffb47bf6736c": "轻点两下以显示完整详情。长按以复制。",
apps/server/src/auth/RpcAuthorization.ts
+2
@@ -75,6 +75,8 @@ export const RPC_REQUIRED_SCOPES = {
75 [WS_METHODS.providerAuthStart]: AuthProvidersManageScope,
76 [WS_METHODS.providerConsumeResetCredit]: AuthProvidersManageScope,
77 [WS_METHODS.providerAuthComplete]: AuthProvidersManageScope,
78 + [WS_METHODS.providerMcpSignInStart]: AuthProvidersManageScope,
79 + [WS_METHODS.providerMcpSignInComplete]: AuthProvidersManageScope,
80 [WS_METHODS.chatGptReconnectProfile]: AuthProvidersManageScope,
81 [WS_METHODS.chatGptImportProfile]: AuthProvidersManageScope,
82 [WS_METHODS.chatGptHandoffSubscribe]: AuthProvidersManageScope,
apps/server/src/mcpApps/McpSignIn.ts new
+112
@@ -0,0 +1,112 @@
1 +import {
2 + ProviderMcpSignInError,
3 + type ProviderMcpSignInCompleteInput,
4 + type ProviderMcpSignInCompleteResult,
5 + type ProviderMcpSignInStartInput,
6 + type ProviderMcpSignInStartResult,
7 +} from "@t3tools/contracts";
8 +import * as Context from "effect/Context";
9 +import * as DateTime from "effect/DateTime";
10 +import * as Effect from "effect/Effect";
11 +import * as Layer from "effect/Layer";
12 +import * as Option from "effect/Option";
13 +import * as Predicate from "effect/Predicate";
14 +import * as Schema from "effect/Schema";
15 +
16 +import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts";
17 +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
18 +
19 +/**
20 + * Signs an agent's MCP server in through the session that reported it needs
21 + * one. Agents keep the credential themselves, so this never starts a session.
22 + */
23 +export class McpSignIn extends Context.Service<
24 + McpSignIn,
25 + {
26 + readonly start: (
27 + input: ProviderMcpSignInStartInput,
28 + ) => Effect.Effect<ProviderMcpSignInStartResult, ProviderMcpSignInError>;
29 + readonly complete: (
30 + input: ProviderMcpSignInCompleteInput,
31 + ) => Effect.Effect<ProviderMcpSignInCompleteResult, ProviderMcpSignInError>;
32 + }
33 +>()("t3/mcpApps/McpSignIn") {}
34 +
35 +const isSignInError = Schema.is(ProviderMcpSignInError);
36 +
37 +const make = Effect.gen(function* () {
38 + const threadManagement = yield* ThreadManagementService.ThreadManagementService;
39 + const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
40 +
41 + const fail = (server: string, detail: string) => new ProviderMcpSignInError({ server, detail });
42 + const stopped = (server: string) =>
43 + fail(server, "The agent session has ended. Send a message, then sign in again.");
44 +
45 + const resolve = Effect.fn("McpSignIn.resolve")(function* (input: ProviderMcpSignInStartInput) {
46 + const projection = yield* threadManagement.getThreadRecords(input.threadId, [
47 + "providerThreads",
48 + ]);
49 + const providerThread = projection.providerThreads.find(
50 + (candidate) => candidate.id === input.providerThreadId,
51 + );
52 + if (providerThread?.providerSessionId == null) return yield* stopped(input.server);
53 + const runtime = Option.getOrUndefined(
54 + yield* providerSessions.get(providerThread.providerSessionId),
55 + );
56 + if (runtime === undefined) return yield* stopped(input.server);
57 + if (runtime.mcpSignIn === undefined) {
58 + return yield* fail(input.server, "This agent can't sign MCP servers in from T3 Code.");
59 + }
60 + return { providerThread, mcpSignIn: runtime.mcpSignIn };
61 + });
62 +
63 + /** Adapter and lookup failures can echo URLs or tokens, so callers see only a generic line. */
64 + const toSignInError = (input: ProviderMcpSignInStartInput, detail: string) => (cause: unknown) =>
65 + isSignInError(cause)
66 + ? Effect.fail(cause)
67 + : Predicate.isTagged(cause, "ProviderAdapterSessionStoppedError")
68 + ? Effect.fail(stopped(input.server))
69 + : Effect.logWarning("mcp-sign-in.failed", {
70 + threadId: input.threadId,
71 + server: input.server,
72 + cause: Predicate.hasProperty(cause, "_tag") ? cause._tag : "unknown",
73 + }).pipe(Effect.andThen(Effect.fail(fail(input.server, detail))));
74 +
75 + const start = Effect.fn("McpSignIn.start")(
76 + function* (input: ProviderMcpSignInStartInput) {
77 + const { providerThread, mcpSignIn } = yield* resolve(input);
78 + const { authorizationUrl } = yield* mcpSignIn.start({
79 + providerThread,
80 + server: input.server,
81 + });
82 + return {
83 + authorizationUrl,
84 + signedInAt: authorizationUrl === null ? DateTime.formatIso(yield* DateTime.now) : null,
85 + };
86 + },
87 + (effect, input) =>
88 + effect.pipe(
89 + Effect.catch(toSignInError(input, `Couldn't start the sign-in to ${input.server}.`)),
90 + ),
91 + );
92 +
93 + const complete = Effect.fn("McpSignIn.complete")(
94 + function* (input: ProviderMcpSignInCompleteInput) {
95 + const { providerThread, mcpSignIn } = yield* resolve(input);
96 + yield* mcpSignIn.complete({
97 + providerThread,
98 + server: input.server,
99 + callbackUrl: input.callbackUrl,
100 + });
101 + return { signedInAt: DateTime.formatIso(yield* DateTime.now) };
102 + },
103 + (effect, input) =>
104 + effect.pipe(
105 + Effect.catch(toSignInError(input, `Couldn't finish the sign-in to ${input.server}.`)),
106 + ),
107 + );
108 +
109 + return McpSignIn.of({ start, complete });
110 +});
111 +
112 +export const layer = Layer.effect(McpSignIn, make);
apps/server/src/observability/RpcInstrumentation.ts
+2
@@ -44,6 +44,8 @@ const RPC_AGGREGATES = {
44 [WS_METHODS.providerAuthStart]: "provider",
45 [WS_METHODS.providerConsumeResetCredit]: "provider",
46 [WS_METHODS.providerAuthComplete]: "provider",
47 + [WS_METHODS.providerMcpSignInStart]: "provider",
48 + [WS_METHODS.providerMcpSignInComplete]: "provider",
49 [WS_METHODS.chatGptReconnectProfile]: "provider",
50 [WS_METHODS.chatGptImportProfile]: "provider",
51 [WS_METHODS.chatGptHandoffSubscribe]: "provider",
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+123
@@ -1149,6 +1149,9 @@ describe("ClaudeAdapterV2 Auto-accept edits", () => {
1149 mcpServerStatus: Effect.succeed([]),
1150 readMcpResource: () => Effect.die("unexpected MCP resource read"),
1151 callMcpTool: () => Effect.die("unexpected MCP tool call"),
1152 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
1153 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
1154 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
1155 listPermissionRules: Effect.die("unexpected permission rules read"),
1156 stopTask: () => Effect.void,
1157 interrupt: Effect.void,
@@ -1272,6 +1275,9 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
1275 mcpServerStatus: Effect.succeed([]),
1276 readMcpResource: () => Effect.die("unexpected MCP resource read"),
1277 callMcpTool: () => Effect.die("unexpected MCP tool call"),
1278 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
1279 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
1280 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
1281 listPermissionRules: Effect.die("unexpected permission rules read"),
1282 stopTask: () => Effect.void,
1283 interrupt: Effect.void,
@@ -1561,6 +1567,9 @@ describe("ClaudeAdapterV2 provider installation gate", () => {
1567 mcpServerStatus: Effect.succeed([]),
1568 readMcpResource: () => Effect.die("unexpected MCP resource read"),
1569 callMcpTool: () => Effect.die("unexpected MCP tool call"),
1570 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
1571 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
1572 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
1573 listPermissionRules: Effect.die("unexpected permission rules read"),
1574 stopTask: () => Effect.void,
1575 interrupt: Effect.void,
@@ -1749,6 +1758,9 @@ const captureSdkExecutablePaths = Effect.fn("captureSdkExecutablePaths")(functio
1758 mcpServerStatus: Effect.succeed([]),
1759 readMcpResource: () => Effect.die("unexpected MCP resource read"),
1760 callMcpTool: () => Effect.die("unexpected MCP tool call"),
1761 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
1762 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
1763 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
1764 listPermissionRules: Effect.die("unexpected permission rules read"),
1765 stopTask: () => Effect.void,
1766 interrupt: Effect.void,
@@ -1952,6 +1964,9 @@ describe("ClaudeAdapterV2 resume compaction", () => {
1964 mcpServerStatus: Effect.succeed([]),
1965 readMcpResource: () => Effect.die("unexpected MCP resource read"),
1966 callMcpTool: () => Effect.die("unexpected MCP tool call"),
1967 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
1968 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
1969 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
1970 listPermissionRules: Effect.die("unexpected permission rules read"),
1971 stopTask: () => Effect.void,
1972 interrupt: Effect.void,
@@ -2342,6 +2357,9 @@ describe("ClaudeAdapterV2 attachments", () => {
2357 mcpServerStatus: Effect.succeed([]),
2358 readMcpResource: () => Effect.die("unexpected MCP resource read"),
2359 callMcpTool: () => Effect.die("unexpected MCP tool call"),
2360 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
2361 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
2362 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
2363 listPermissionRules: Effect.die("unexpected permission rules read"),
2364 stopTask: () => Effect.void,
2365 interrupt: Effect.void,
@@ -2884,6 +2902,9 @@ describe("ClaudeAdapterV2 native fork", () => {
2902 mcpServerStatus: Effect.succeed([]),
2903 readMcpResource: () => Effect.die("unexpected MCP resource read"),
2904 callMcpTool: () => Effect.die("unexpected MCP tool call"),
2905 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
2906 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
2907 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
2908 listPermissionRules: Effect.die("unexpected permission rules read"),
2909 stopTask: () => Effect.void,
2910 interrupt: Effect.void,
@@ -3233,6 +3254,9 @@ describe("ClaudeAdapterV2 native session identity", () => {
3254 mcpServerStatus: Effect.succeed([]),
3255 readMcpResource: () => Effect.die("unexpected MCP resource read"),
3256 callMcpTool: () => Effect.die("unexpected MCP tool call"),
3257 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
3258 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
3259 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
3260 listPermissionRules: Effect.die("unexpected permission rules read"),
3261 stopTask: () => Effect.void,
3262 interrupt: Effect.void,
@@ -3717,6 +3741,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3741 mcpServerStatus: Effect.succeed([]),
3742 readMcpResource: () => Effect.die("unexpected MCP resource read"),
3743 callMcpTool: () => Effect.die("unexpected MCP tool call"),
3744 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
3745 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
3746 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
3747 listPermissionRules: Effect.die("unexpected permission rules read"),
3748 stopTask: options?.stopTask ?? (() => Effect.void),
3749 interrupt: Effect.void,
@@ -3760,6 +3787,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3787 (() => Effect.die("unexpected MCP resource read")),
3788 callMcpTool:
3789 options?.mcp?.callMcpTool ?? (() => Effect.die("unexpected MCP tool call")),
3790 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
3791 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
3792 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
3793 listPermissionRules: options?.mcp?.listPermissionRules ?? Effect.succeed([]),
3794 stopTask: options?.stopTask ?? (() => Effect.void),
3795 interrupt: options?.interrupt ?? Effect.void,
@@ -7072,6 +7102,69 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7102 ),
7103 );
7104
7105 + it.effect("asks to sign in to a configured MCP server, but not to a claude.ai connector", () =>
7106 + Effect.gen(function* () {
7107 + const harness = yield* makeWakeHarnessWithOptions({
7108 + mcp: {
7109 + mcpServerStatus: Effect.succeed([
7110 + { name: "linear", status: "needs-auth" },
7111 + { name: "claude.ai Gmail", status: "needs-auth", scope: "claudeai" },
7112 + { name: "docs", status: "connected" },
7113 + ]),
7114 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
7115 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
7116 + },
7117 + });
7118 + yield* harness.runtime.startTurn(
7119 + makeClaudeTestTurnInput({
7120 + threadId: harness.threadId,
7121 + providerThread: harness.providerThread,
7122 + now: yield* DateTime.now,
7123 + attemptId: RunAttemptId.make("mcp-sign-in"),
7124 + text: "Plan the sprint",
7125 + attachments: [],
7126 + }),
7127 + );
7128 + // Remote servers are still connecting at init; whether they need a sign-in settles later.
7129 + yield* harness.offerAndWait(
7130 + claudeSdkFrame({
7131 + type: "system",
7132 + subtype: "init",
7133 + uuid: "mcp-sign-in-init",
7134 + session_id: WAKE_NATIVE_SESSION,
7135 + mcp_servers: [
7136 + { name: "linear", status: "pending" },
7137 + { name: "claude.ai Gmail", status: "needs-auth" },
7138 + { name: "docs", status: "connected" },
7139 + ],
7140 + }),
7141 + );
7142 + yield* Queue.offer(
7143 + harness.sdkMessages,
7144 + makeResultFrame({ uuid: "mcp-sign-in-result", result: "Planned" }),
7145 + );
7146 + yield* Queue.take(harness.terminalReceipts);
7147 + const signIns = harness.events.flatMap((event) =>
7148 + event.type === "turn_item.updated" &&
7149 + event.turnItem.type === "system_notice" &&
7150 + event.turnItem.mcpSignIn !== undefined
7151 + ? [event.turnItem.mcpSignIn.server]
7152 + : [],
7153 + );
7154 + assert.deepEqual(signIns, ["linear"]);
7155 + }).pipe(
7156 + Effect.scoped,
7157 + Effect.provide(
7158 + Layer.mergeAll(
7159 + IdAllocator.layer,
7160 + McpProviderSessions.layer,
7161 + NodeServices.layer,
7162 + NodeCrypto.layer,
7163 + ),
7164 + ),
7165 + ),
7166 + );
7167 +
7168 // regression: #38284 an MCP app's update-model-context note must reach Claude's next turn
7169 it.effect("sends MCP app model context with the next Claude turn", () =>
7170 Effect.gen(function* () {
@@ -14460,6 +14553,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14553 mcpServerStatus: Effect.succeed([]),
14554 readMcpResource: () => Effect.die("unexpected MCP resource read"),
14555 callMcpTool: () => Effect.die("unexpected MCP tool call"),
14556 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
14557 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
14558 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
14559 listPermissionRules: Effect.die("unexpected permission rules read"),
14560 stopTask: () => Effect.void,
14561 interrupt: Effect.void,
@@ -14662,6 +14758,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14758 mcpServerStatus: Effect.succeed([]),
14759 readMcpResource: () => Effect.die("unexpected MCP resource read"),
14760 callMcpTool: () => Effect.die("unexpected MCP tool call"),
14761 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
14762 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
14763 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
14764 listPermissionRules: Effect.die("unexpected permission rules read"),
14765 stopTask: () => Effect.void,
14766 interrupt: Effect.void,
@@ -14874,6 +14973,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14973 mcpServerStatus: Effect.succeed([]),
14974 readMcpResource: () => Effect.die("unexpected MCP resource read"),
14975 callMcpTool: () => Effect.die("unexpected MCP tool call"),
14976 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
14977 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
14978 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
14979 listPermissionRules: Effect.die("unexpected permission rules read"),
14980 stopTask: () => Effect.void,
14981 interrupt: Effect.void,
@@ -18267,6 +18369,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
18369 mcpServerStatus: Effect.die("unexpected MCP server status"),
18370 readMcpResource: () => Effect.die("unexpected MCP resource read"),
18371 callMcpTool: () => Effect.die("unexpected MCP tool call"),
18372 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
18373 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
18374 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
18375 listPermissionRules: Effect.die("unexpected permission rules read"),
18376 interrupt: Effect.void,
18377 close:
@@ -21625,6 +21730,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
21730 mcpServerStatus: Effect.succeed([]),
21731 readMcpResource: () => Effect.die("unexpected MCP resource read"),
21732 callMcpTool: () => Effect.die("unexpected MCP tool call"),
21733 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
21734 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
21735 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
21736 listPermissionRules: Effect.die("unexpected permission rules read"),
21737 stopTask: () => Effect.void,
21738 interrupt: Effect.void,
@@ -21803,6 +21911,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
21911 mcpServerStatus: Effect.succeed([]),
21912 readMcpResource: () => Effect.die("unexpected MCP resource read"),
21913 callMcpTool: () => Effect.die("unexpected MCP tool call"),
21914 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
21915 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
21916 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
21917 listPermissionRules: Effect.die("unexpected permission rules read"),
21918 stopTask: () => Effect.void,
21919 interrupt: Effect.void,
@@ -21981,6 +22092,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
22092 mcpServerStatus: Effect.succeed([]),
22093 readMcpResource: () => Effect.die("unexpected MCP resource read"),
22094 callMcpTool: () => Effect.die("unexpected MCP tool call"),
22095 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
22096 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
22097 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
22098 listPermissionRules: Effect.die("unexpected permission rules read"),
22099 stopTask: () => Effect.void,
22100 interrupt: Effect.void,
@@ -22180,6 +22294,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
22294 mcpServerStatus: Effect.succeed([]),
22295 readMcpResource: () => Effect.die("unexpected MCP resource read"),
22296 callMcpTool: () => Effect.die("unexpected MCP tool call"),
22297 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
22298 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
22299 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
22300 listPermissionRules: Effect.die("unexpected permission rules read"),
22301 stopTask: () => Effect.void,
22302 interrupt: Effect.void,
@@ -22327,6 +22444,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
22444 mcpServerStatus: Effect.succeed([]),
22445 readMcpResource: () => Effect.die("unexpected MCP resource read"),
22446 callMcpTool: () => Effect.die("unexpected MCP tool call"),
22447 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
22448 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
22449 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
22450 listPermissionRules: Effect.die("unexpected permission rules read"),
22451 stopTask: () => Effect.void,
22452 interrupt: Effect.void,
@@ -22449,6 +22569,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
22569 mcpServerStatus: Effect.succeed([]),
22570 readMcpResource: () => Effect.die("unexpected MCP resource read"),
22571 callMcpTool: () => Effect.die("unexpected MCP tool call"),
22572 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
22573 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
22574 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
22575 listPermissionRules: Effect.die("unexpected permission rules read"),
22576 stopTask: () => Effect.void,
22577 interrupt: Effect.void,
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts
+5 -1
@@ -848,9 +848,13 @@ function makeReplayQueryRunner(
848 replayEffect(() => {
849 assertNextOutboundFrame({ type: "query.background_tasks", toolUseId });
850 }).pipe(Effect.as(true)),
851 + // A result looks for servers that need a sign-in; the replay reports none.
852 + mcpServerStatus: Effect.succeed([]),
853 // Recorded CLIs predate MCP Apps capabilities, so replays never reach these.
852 - mcpServerStatus: Effect.die("unexpected MCP server status in replay"),
854 readMcpResource: () => Effect.die("unexpected MCP resource read in replay"),
855 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in in replay"),
856 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in in replay"),
857 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect in replay"),
858 callMcpTool: () => Effect.die("unexpected MCP tool call in replay"),
859 listPermissionRules: Effect.die("unexpected permission rules read in replay"),
860 interrupt: replayEffect(() => {
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+205 -1
@@ -26,6 +26,7 @@ import {
26 } from "./claudeWorkflowProgress.ts";
27
28 import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
29 +import { pastedUrl } from "@t3tools/shared/oauthCallback";
30 import {
31 addClaudeLedgerUsage,
32 claudeLedgerDelta,
@@ -124,6 +125,7 @@ import {
125 type OrchestrationV2WebSearchResult,
126 type ProviderApprovalDecision,
127 type ProviderApprovalFullAccessOverride,
128 + ProviderMcpSignInError,
129 type ProviderApprovalOption,
130 ProviderDriverKind,
131 type ProviderInstanceId,
@@ -729,6 +731,18 @@ export interface ClaudeAgentSdkQuerySession {
731 { readonly contents: ReadonlyArray<unknown> },
732 ClaudeAgentSdkQueryRunnerError
733 >;
734 + /** Starts an MCP server's sign-in. The CLI never opens a browser; null means none is needed. */
735 + readonly mcpAuthenticate: (
736 + server: string,
737 + ) => Effect.Effect<string | null, ClaudeAgentSdkQueryRunnerError>;
738 + /** Finishes it with the address the browser was sent to; the CLI checks its state. */
739 + readonly mcpSubmitOAuthCallbackUrl: (input: {
740 + readonly server: string;
741 + readonly callbackUrl: string;
742 + }) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
743 + readonly reconnectMcpServer: (
744 + server: string,
745 + ) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
746 /** Runs an MCP tool without a model turn and returns the server's raw `CallToolResult`. */
747 readonly callMcpTool: (input: {
748 readonly tool: string;
@@ -946,7 +960,12 @@ function closeClaudeQuery(queryRuntime: ClaudeQuery) {
960 async function sendClaudeControlRequest(
961 queryRuntime: ClaudeQuery,
962 request: {
949 - readonly subtype: "mcp_call" | "list_permission_rules" | "rename_session";
963 + readonly subtype:
964 + | "mcp_call"
965 + | "list_permission_rules"
966 + | "rename_session"
967 + | "mcp_authenticate"
968 + | "mcp_oauth_callback_url";
969 readonly [key: string]: unknown;
970 },
971 ): Promise<unknown> {
@@ -958,6 +977,13 @@ async function sendClaudeControlRequest(
977 return Predicate.isObject(reply) ? reply.response : undefined;
978 }
979
980 +const decodeClaudeMcpAuthenticateReply = Schema.decodeUnknownEffect(
981 + Schema.Struct({
982 + authUrl: Schema.optional(Schema.String),
983 + requiresUserAction: Schema.optional(Schema.Boolean),
984 + }),
985 +);
986 +
987 const ClaudePermissionRules = Schema.Struct({
988 state: Schema.Struct({
989 rules: Schema.Array(
@@ -1921,6 +1947,38 @@ export const layerQueryRunner: Layer.Layer<
1947 try: () => queryRuntime.readMcpResource(server, uri),
1948 catch: (cause) => queryRunnerError(cause, "readMcpResource"),
1949 }),
1950 + mcpAuthenticate: (server) =>
1951 + Effect.tryPromise({
1952 + try: () =>
1953 + sendClaudeControlRequest(queryRuntime, {
1954 + subtype: "mcp_authenticate",
1955 + serverName: server,
1956 + }),
1957 + catch: (cause) => queryRunnerError(cause, "mcpAuthenticate"),
1958 + }).pipe(
1959 + Effect.flatMap(decodeClaudeMcpAuthenticateReply),
1960 + Effect.map((reply) =>
1961 + reply.requiresUserAction === true && reply.authUrl !== undefined
1962 + ? reply.authUrl
1963 + : null,
1964 + ),
1965 + Effect.mapError((cause) => queryRunnerError(cause, "mcpAuthenticate")),
1966 + ),
1967 + mcpSubmitOAuthCallbackUrl: ({ server, callbackUrl }) =>
1968 + Effect.tryPromise({
1969 + try: () =>
1970 + sendClaudeControlRequest(queryRuntime, {
1971 + subtype: "mcp_oauth_callback_url",
1972 + serverName: server,
1973 + callbackUrl,
1974 + }),
1975 + catch: (cause) => queryRunnerError(cause, "mcpSubmitOAuthCallbackUrl"),
1976 + }).pipe(Effect.asVoid),
1977 + reconnectMcpServer: (server) =>
1978 + Effect.tryPromise({
1979 + try: () => queryRuntime.reconnectMcpServer(server),
1980 + catch: (cause) => queryRunnerError(cause, "reconnectMcpServer"),
1981 + }),
1982 callMcpTool: (call) =>
1983 Effect.tryPromise({
1984 try: () =>
@@ -5231,6 +5289,8 @@ interface ClaudeLiveQueryContext {
5289 // The CLI may fall back from the requested mode on its first init frame.
5290 openedPermissionMode: PermissionMode;
5291 receivedInit: boolean;
5292 + // Init listed a server still connecting or needing a sign-in; a result checks which it was.
5293 + checkMcpSignIns: boolean;
5294 // From system/init; feature-detects control requests such as MCP Apps.
5295 capabilities: ReadonlySet<string>;
5296 claudeCodeVersion: string | undefined;
@@ -8706,6 +8766,82 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8766 registry: target.toolCalls,
8767 });
8768
8769 + const liveQueryForThread = Effect.fn("ClaudeAdapterV2.liveQueryForThread")(function* (
8770 + providerThread: OrchestrationV2ProviderThread,
8771 + ) {
8772 + const liveQuery = yield* Ref.get(queryContext);
8773 + const nativeId = providerThread.nativeThreadRef?.nativeId;
8774 + // After /clear the thread carries the new session id; the live query keeps the old one.
8775 + if (
8776 + liveQuery === null ||
8777 + liveQuery.stopping ||
8778 + (liveQuery.nativeThreadId !== nativeId &&
8779 + clearedNativeSessions.get(liveQuery.nativeThreadId) !== nativeId)
8780 + ) {
8781 + return yield* new ProviderAdapter.ProviderAdapterSessionStoppedError({
8782 + driver: CLAUDE_PROVIDER,
8783 + });
8784 + }
8785 + return liveQuery;
8786 + });
8787 +
8788 + // Keyed by native thread and server: one notice per server for as long as the session runs.
8789 + const announcedMcpSignIns = new Set<string>();
8790 + /** Claude reports a server that needs a sign-in only in its status, which settles after start. */
8791 + const announceMcpSignIns = Effect.fn("ClaudeAdapterV2.announceMcpSignIns")(function* (
8792 + liveQuery: ClaudeLiveQueryContext,
8793 + context: ActiveClaudeTurnContext,
8794 + ) {
8795 + if (!liveQuery.checkMcpSignIns) return;
8796 + const statuses = yield* liveQuery.query.mcpServerStatus.pipe(
8797 + Effect.timeoutOrElse({
8798 + duration: "2 seconds",
8799 + orElse: () => Effect.succeed<ReadonlyArray<ClaudeMcpServerStatus>>([]),
8800 + }),
8801 + Effect.orElseSucceed((): ReadonlyArray<ClaudeMcpServerStatus> => []),
8802 + );
8803 + liveQuery.checkMcpSignIns = statuses.some((status) => status.status === "pending");
8804 + for (const status of statuses) {
8805 + // Every claude.ai connector the user never connected reports this too.
8806 + if (status.status !== "needs-auth" || status.scope === "claudeai") continue;
8807 + const key = `${liveQuery.nativeThreadId}\u0000${status.name}`;
8808 + if (announcedMcpSignIns.has(key)) continue;
8809 + announcedMcpSignIns.add(key);
8810 + const nativeItemId = `mcp-sign-in:${context.providerTurnId}:${status.name}`;
8811 + const now = yield* DateTime.now;
8812 + yield* emitProviderEvent({
8813 + type: "turn_item.updated",
8814 + driver: CLAUDE_PROVIDER,
8815 + turnItem: {
8816 + id: idAllocator.derive.turnItemFromProviderItem({
8817 + driver: CLAUDE_PROVIDER,
8818 + nativeItemId,
8819 + }),
8820 + threadId: context.input.threadId,
8821 + runId: context.input.runId,
8822 + nodeId: context.input.rootNodeId,
8823 + providerThreadId: context.input.providerThread.id,
8824 + providerTurnId: context.providerTurnId,
8825 + nativeItemRef: {
8826 + driver: CLAUDE_PROVIDER,
8827 + nativeId: nativeItemId,
8828 + strength: "weak",
8829 + },
8830 + parentItemId: null,
8831 + ordinal: yield* resolveItemOrdinal(context, nativeItemId),
8832 + type: "system_notice",
8833 + status: "completed",
8834 + title: `MCP server ${status.name} needs a sign-in`,
8835 + message: `The ${status.name} MCP server needs a sign-in before Claude can use it.`,
8836 + mcpSignIn: { server: status.name },
8837 + startedAt: now,
8838 + completedAt: now,
8839 + updatedAt: now,
8840 + },
8841 + });
8842 + }
8843 + });
8844 +
8845 // App requests never start a CLI; they reuse the live process that ran the tool.
8846 const mcpAppQuery = Effect.fn("ClaudeAdapterV2.mcpAppQuery")(function* (
8847 providerThread: OrchestrationV2ProviderThread,
@@ -12001,6 +12137,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12137 }
12138
12139 if (message.type === "result") {
12140 + if (context === (yield* Ref.get(activeTurn))) {
12141 + yield* announceMcpSignIns(liveQuery, context);
12142 + }
12143 const contextUsage = context.streamUsage?.usage ?? context.compactionTokens;
12144 if (resultsReportingNewContextWindow.has(message) && contextUsage !== undefined) {
12145 yield* emitContextUsage(context, contextUsage);
@@ -13172,6 +13311,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13311 promptEchoMode: "unknown",
13312 openedPermissionMode: queryOptions.permissionMode,
13313 receivedInit: false,
13314 + checkMcpSignIns: false,
13315 capabilities: new Set(),
13316 claudeCodeVersion: undefined,
13317 permissionMode: queryOptions.permissionMode,
@@ -13219,6 +13359,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13359 context.capabilities = new Set(message.capabilities ?? []);
13360 context.claudeCodeVersion = message.claude_code_version;
13361 }
13362 + if (message.type === "system" && message.subtype === "init") {
13363 + // Recorded frames from older CLIs can omit the list.
13364 + context.checkMcpSignIns = (message.mcp_servers ?? []).some(
13365 + (server) =>
13366 + (server.status === "pending" || server.status === "needs-auth") &&
13367 + // claude.ai connectors the user never connected need a sign-in too.
13368 + !server.name.startsWith("claude.ai "),
13369 + );
13370 + }
13371 if (
13372 message.type === "system" &&
13373 message.subtype === "init" &&
@@ -14477,6 +14626,61 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
14626 }
14627 yield* applySessionTitle(live.query, live.nativeThreadId, title);
14628 }),
14629 + mcpSignIn: {
14630 + start: Effect.fn("ClaudeAdapterV2.mcpSignIn.start")(function* ({
14631 + providerThread,
14632 + server,
14633 + }) {
14634 + const liveQuery = yield* liveQueryForThread(providerThread);
14635 + const authorizationUrl = yield* liveQuery.query.mcpAuthenticate(server).pipe(
14636 + Effect.mapError(
14637 + () =>
14638 + new ProviderMcpSignInError({
14639 + server,
14640 + detail: `Claude couldn't start the sign-in to ${server}.`,
14641 + }),
14642 + ),
14643 + );
14644 + return { authorizationUrl };
14645 + }),
14646 + complete: Effect.fn("ClaudeAdapterV2.mcpSignIn.complete")(function* ({
14647 + providerThread,
14648 + server,
14649 + callbackUrl,
14650 + }) {
14651 + const fail = (detail: string) => new ProviderMcpSignInError({ server, detail });
14652 + const liveQuery = yield* liveQueryForThread(providerThread);
14653 + const statuses = yield* liveQuery.query.mcpServerStatus.pipe(
14654 + Effect.mapError(() => fail(`Claude couldn't finish the sign-in to ${server}.`)),
14655 + );
14656 + // A browser on this machine may already have finished it on Claude's own page.
14657 + if (statuses.find((status) => status.name === server)?.status === "connected") return;
14658 + const pasted = yield* Effect.try({
14659 + try: () => pastedUrl(callbackUrl).toString(),
14660 + catch: () =>
14661 + fail("That isn't an address. Paste the whole address from your browser."),
14662 + });
14663 + yield* liveQuery.query
14664 + .mcpSubmitOAuthCallbackUrl({ server, callbackUrl: pasted })
14665 + .pipe(
14666 + Effect.mapError(() =>
14667 + fail(
14668 + "Claude didn't accept that address. Paste the address your browser went to after you approved, or start again.",
14669 + ),
14670 + ),
14671 + );
14672 + // The CLI reconnects after its own callback page, but not after a pasted address.
14673 + yield* liveQuery.query
14674 + .reconnectMcpServer(server)
14675 + .pipe(
14676 + Effect.mapError(() =>
14677 + fail(
14678 + `Signed in, but ${server} didn't reconnect. Restart the agent session to use it.`,
14679 + ),
14680 + ),
14681 + );
14682 + }),
14683 + },
14684 stopTask: Effect.fn("ClaudeAdapterV2.stopTask")(function* ({ providerThread, taskId }) {
14685 const liveQuery = yield* Ref.get(queryContext);
14686 const task = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId);
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+122 -6
@@ -3479,8 +3479,104 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3479 ),
3480 );
3481
3482 + it.effect("signs a Codex MCP server in only while it isn't connected in the thread", () =>
3483 + Effect.gen(function* () {
3484 + const nativeThreadId = "mcp-sign-in-thread";
3485 + const status = (
3486 + id: number,
3487 + runtimeStatus: string,
3488 + ): Array<CodexReplay.CodexAppServerReplayEntry> => [
3489 + {
3490 + type: "expect_outbound",
3491 + label: "mcpServerStatus/list",
3492 + frame: {
3493 + id,
3494 + method: "mcpServerStatus/list",
3495 + params: { serverName: "linear", threadId: nativeThreadId, detail: "toolsAndAuthOnly" },
3496 + },
3497 + },
3498 + {
3499 + type: "emit_inbound",
3500 + label: "mcpServerStatus/list",
3501 + frame: {
3502 + id,
3503 + result: {
3504 + data: [
3505 + {
3506 + name: "linear",
3507 + runtimeStatus,
3508 + authStatus: "oAuth",
3509 + tools: {},
3510 + resources: [],
3511 + resourceTemplates: [],
3512 + },
3513 + ],
3514 + },
3515 + },
3516 + },
3517 + ];
3518 + const authorizationUrl =
3519 + "https://linear.example/authorize?redirect_uri=http%3A%2F%2F127.0.0.1%3A50123%2Fcallback%2Fabc&state=s1";
3520 + const harness = yield* makeCodexReplayHarness(
3521 + makeCodexReplayTranscript({
3522 + scenario: "codex-mcp-sign-in",
3523 + entries: [
3524 + ...codexReplayPreamble({
3525 + nativeThreadId,
3526 + nativeTurnId: "unused",
3527 + prompt: "work",
3528 + }).slice(0, 5),
3529 + ...status(3, "connected"),
3530 + ...status(4, "authenticationRequired"),
3531 + {
3532 + type: "expect_outbound",
3533 + label: "mcpServer/oauth/login",
3534 + frame: {
3535 + id: 5,
3536 + method: "mcpServer/oauth/login",
3537 + params: { name: "linear", threadId: nativeThreadId },
3538 + },
3539 + },
3540 + {
3541 + type: "emit_inbound",
3542 + label: "mcpServer/oauth/login",
3543 + frame: { id: 5, result: { authorizationUrl } },
3544 + },
3545 + // A browser on Codex's machine reached its callback page before anything was pasted.
3546 + {
3547 + type: "emit_inbound",
3548 + label: "mcpServer/oauthLogin/completed",
3549 + frame: {
3550 + method: "mcpServer/oauthLogin/completed",
3551 + params: { name: "linear", threadId: nativeThreadId, success: true },
3552 + },
3553 + },
3554 + ],
3555 + }),
3556 + );
3557 + const mcpSignIn = harness.runtime.mcpSignIn;
3558 + assert.isDefined(mcpSignIn);
3559 + const input = { providerThread: harness.providerThread, server: "linear" };
3560 + assert.deepEqual(yield* mcpSignIn.start(input), { authorizationUrl: null });
3561 + assert.deepEqual(yield* mcpSignIn.start(input), { authorizationUrl });
3562 + yield* mcpSignIn.complete({
3563 + ...input,
3564 + callbackUrl: "127.0.0.1:50123/callback/abc?code=c1&state=s1",
3565 + });
3566 + }).pipe(
3567 + Effect.provide(
3568 + Layer.mergeAll(
3569 + IdAllocator.layer,
3570 + McpProviderSessions.layer,
3571 + NodeServices.layer,
3572 + NodeCrypto.layer,
3573 + ),
3574 + ),
3575 + ),
3576 + );
3577 +
3578 it.effect.each(["before", "during"] as const)(
3483 - "surfaces a user MCP server that fails to start %s the turn",
3579 + "surfaces a user MCP server that fails to start %s the turn, with a sign-in when it needs one",
3580 (timing) =>
3581 Effect.gen(function* () {
3582 const nativeThreadId = "mcp-startup-failed-thread";
@@ -3516,6 +3612,22 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3612 },
3613 },
3614 },
3615 + {
3616 + type: "emit_inbound",
3617 + label: "mcp-not-logged-in",
3618 + frame: {
3619 + method: "mcpServer/startupStatus/updated",
3620 + params: {
3621 + threadId: nativeThreadId,
3622 + name: "login_mcp",
3623 + status: "failed",
3624 + // Verbatim from codex-cli 0.171.0, which sets no failureReason for it.
3625 + error:
3626 + "The login_mcp MCP server is not logged in. Run `codex mcp login login_mcp`.",
3627 + failureReason: null,
3628 + },
3629 + },
3630 + },
3631 ];
3632 const preamble = codexReplayPreamble({
3633 nativeThreadId,
@@ -3555,11 +3667,15 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3667 }),
3668 );
3669 yield* harness.firstTerminal;
3558 - const surfaced = harness.events.filter((event) => {
3559 - const serialized = JSON.stringify(event);
3560 - return serialized.includes("example_mcp") && serialized.includes("failed to start");
3561 - });
3562 - assert.isNotEmpty(surfaced);
3670 + const notices = harness.events.flatMap((event) =>
3671 + event.type === "turn_item.updated" && event.turnItem.type === "system_notice"
3672 + ? [[event.turnItem.title, event.turnItem.mcpSignIn?.server ?? null]]
3673 + : [],
3674 + );
3675 + assert.deepEqual(notices, [
3676 + ["MCP server example_mcp failed to start", null],
3677 + ["MCP server login_mcp failed to start", "login_mcp"],
3678 + ]);
3679 }).pipe(
3680 Effect.provide(
3681 Layer.mergeAll(
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+161 -8
@@ -39,6 +39,7 @@ import {
39 OrchestrationV2ProviderGoal,
40 parseGoalCommand,
41 ProviderDriverKind,
42 + ProviderMcpSignInError,
43 ProviderSetupError,
44 type ServerProviderCompatibilityAdvisory,
45 type ServerProviderModel,
@@ -57,6 +58,7 @@ import { getModelSelectionStringOptionValue, modelSelectionsEqual } from "@t3too
58 import { appendGeneratedImageEmbeds } from "@t3tools/shared/generatedImageMarkdown";
59 import { resolveSpawnCommand } from "@t3tools/shared/shell";
60 import { mcpToolResultOutput } from "@t3tools/shared/toolOutput";
61 +import { oauthCallbackUrl } from "@t3tools/shared/oauthCallback";
62 import type {
63 ChatAttachment,
64 OrchestrationV2AppThread,
@@ -105,6 +107,7 @@ import * as Schema from "effect/Schema";
107 import * as Scope from "effect/Scope";
108 import * as Semaphore from "effect/Semaphore";
109 import * as Stream from "effect/Stream";
110 +import { FetchHttpClient, HttpClient } from "effect/http";
111 import { ChildProcess, ChildProcessSpawner } from "effect/process";
112
113 import { resolveAttachmentPath, resolveAttachmentPathById } from "../../attachmentStore.ts";
@@ -739,6 +742,7 @@ const decodeTurnReasoningEffort = Schema.decodeUnknownEffect(
742
743 type CodexTurnStartParams = typeof CodexClient.V2TurnStartParams.Type;
744 const decodeCodexTurnStartParams = Schema.decodeUnknownEffect(CodexClient.V2TurnStartParams);
745 +const isProviderMcpSignInError = Schema.is(ProviderMcpSignInError);
746 const isProviderAdapterRuntimeRequestResponseError = Schema.is(
747 ProviderAdapter.ProviderAdapterRuntimeRequestResponseError,
748 );
@@ -919,6 +923,28 @@ function providerSession(input: {
923 };
924 }
925
926 +interface CodexMcpStartupFailure {
927 + readonly message: string;
928 + readonly signIn: boolean;
929 +}
930 +
931 +/** Codex names an expired sign-in, but a missing one only in text that says to run `codex mcp login`. */
932 +const codexMcpStartupNeedsSignIn = (payload: {
933 + readonly failureReason?: string | null;
934 + readonly error?: string | null;
935 +}) =>
936 + payload.failureReason === "reauthenticationRequired" ||
937 + (payload.error ?? "").includes("mcp login");
938 +
939 +/** A sign-in Codex started, waiting for its callback page on this machine to be opened. */
940 +interface CodexMcpSignIn {
941 + readonly redirectUri: string;
942 + readonly state: string;
943 + readonly succeeded: Deferred.Deferred<boolean>;
944 +}
945 +
946 +const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
947 +
948 const getNativeThreadId = Effect.fn("CodexAdapterV2.getNativeThreadId")(function* (
949 providerThread: OrchestrationV2ProviderThread,
950 ) {
@@ -2141,7 +2167,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
2167 );
2168 const activeTurns = yield* Ref.make(new Map<string, ActiveCodexTurnContext>());
2169 // Codex reports MCP startup on thread start, usually before the turn context exists.
2144 - const mcpStartupFailures = new Map<string, Map<string, string>>();
2170 + const mcpStartupFailures = new Map<string, Map<string, CodexMcpStartupFailure>>();
2171 + // By server name: the shared app-server signs a server in for every thread at once.
2172 + const mcpSignIns = new Map<string, CodexMcpSignIn>();
2173 const turnTokenUsageByThread = new Map<string, CodexTurnTokenUsageState>();
2174 const usageStateForThread = (nativeThreadId: string) => {
2175 let state = turnTokenUsageByThread.get(nativeThreadId);
@@ -2437,7 +2465,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
2465 const failures = mcpStartupFailures.get(nativeThreadId);
2466 if (failures === undefined) return;
2467 mcpStartupFailures.delete(nativeThreadId);
2440 - for (const [name, message] of failures) {
2468 + for (const [name, failure] of failures) {
2469 const nativeItemId = `mcp-startup-failed:${context.providerTurnId}:${name}`;
2470 const { ordinal, startedAt } = yield* resolveItemPosition(context, nativeItemId);
2471 yield* emitProviderEvent({
@@ -2459,7 +2487,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
2487 type: "system_notice",
2488 status: "completed",
2489 title: `MCP server ${name} failed to start`,
2462 - message,
2490 + message: failure.message,
2491 + ...(failure.signIn ? { mcpSignIn: { server: name } } : {}),
2492 startedAt,
2493 completedAt: startedAt,
2494 updatedAt: startedAt,
@@ -5105,12 +5134,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
5134 yield* client.handleServerNotification("mcpServer/startupStatus/updated", (payload) =>
5135 Effect.gen(function* () {
5136 if (payload.threadId == null) return;
5108 - const failures = mcpStartupFailures.get(payload.threadId) ?? new Map<string, string>();
5137 + const failures =
5138 + mcpStartupFailures.get(payload.threadId) ?? new Map<string, CodexMcpStartupFailure>();
5139 if (payload.status === "failed") {
5110 - failures.set(
5111 - payload.name,
5112 - payload.error?.trim() || `MCP server ${payload.name} failed to start.`,
5113 - );
5140 + failures.set(payload.name, {
5141 + message: payload.error?.trim() || `MCP server ${payload.name} failed to start.`,
5142 + signIn: codexMcpStartupNeedsSignIn(payload),
5143 + });
5144 mcpStartupFailures.set(payload.threadId, failures);
5145 } else {
5146 failures.delete(payload.name);
@@ -5122,6 +5152,15 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
5152 }),
5153 );
5154
5155 + yield* client.handleServerNotification("mcpServer/oauthLogin/completed", (payload) =>
5156 + Effect.suspend(() => {
5157 + const signIn = mcpSignIns.get(payload.name);
5158 + return signIn === undefined
5159 + ? Effect.void
5160 + : Deferred.succeed(signIn.succeeded, payload.success).pipe(Effect.asVoid);
5161 + }),
5162 + );
5163 +
5164 yield* client.handleServerNotification("hook/completed", (payload) =>
5165 Effect.gen(function* () {
5166 if (payload.turnId == null || payload.run.status !== "stopped") return;
@@ -8891,6 +8930,120 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
8930 ),
8931 ),
8932 mcpApps,
8933 + mcpSignIn: {
8934 + start: Effect.fn("CodexAdapterV2.mcpSignIn.start")(
8935 + function* ({ providerThread, server }) {
8936 + const threadId = yield* getNativeThreadId(providerThread);
8937 + // A notice can outlive its problem, as when another client signed the server in.
8938 + const status = yield* ensureInitialized.pipe(
8939 + Effect.andThen(
8940 + withLoadedThread(
8941 + providerThread,
8942 + threadId,
8943 + client.request("mcpServerStatus/list", {
8944 + serverName: server,
8945 + threadId,
8946 + detail: "toolsAndAuthOnly",
8947 + }),
8948 + ),
8949 + ),
8950 + Effect.orElseSucceed(() => ({ data: [] })),
8951 + );
8952 + if (status.data.some((entry) => entry.runtimeStatus === "connected")) {
8953 + return { authorizationUrl: null };
8954 + }
8955 + // With the thread, Codex reconnects the server there once the sign-in succeeds.
8956 + const { authorizationUrl } = yield* ensureInitialized.pipe(
8957 + Effect.andThen(
8958 + withLoadedThread(
8959 + providerThread,
8960 + threadId,
8961 + client.request("mcpServer/oauth/login", { name: server, threadId }),
8962 + ),
8963 + ),
8964 + );
8965 + const params = yield* Effect.try({
8966 + try: () => new URL(authorizationUrl).searchParams,
8967 + catch: () =>
8968 + new ProviderMcpSignInError({
8969 + server,
8970 + detail: `Codex returned a sign-in page for ${server} that T3 Code can't open.`,
8971 + }),
8972 + });
8973 + const redirectUri = params.get("redirect_uri");
8974 + const state = params.get("state");
8975 + if (redirectUri !== null && state !== null) {
8976 + mcpSignIns.set(server, {
8977 + redirectUri,
8978 + state,
8979 + succeeded: yield* Deferred.make<boolean>(),
8980 + });
8981 + }
8982 + return { authorizationUrl };
8983 + },
8984 + Effect.mapError((cause) =>
8985 + isProviderMcpSignInError(cause)
8986 + ? cause
8987 + : new ProviderAdapter.ProviderAdapterProtocolError({
8988 + driver: CODEX_PROVIDER,
8989 + detail: "Failed to start a Codex MCP sign-in.",
8990 + payload: cause,
8991 + }),
8992 + ),
8993 + ),
8994 + complete: Effect.fn("CodexAdapterV2.mcpSignIn.complete")(function* ({
8995 + server,
8996 + callbackUrl,
8997 + }) {
8998 + const fail = (detail: string) => new ProviderMcpSignInError({ server, detail });
8999 + const signIn = mcpSignIns.get(server);
9000 + if (signIn === undefined) return yield* fail(`Start the sign-in to ${server} again.`);
9001 + // A browser on this machine may already have opened Codex's callback page.
9002 + let delivered = true;
9003 + if (!(yield* Deferred.isDone(signIn.succeeded))) {
9004 + const callback = yield* Effect.try({
9005 + try: () => oauthCallbackUrl(callbackUrl, signIn.redirectUri, signIn.state),
9006 + catch: () =>
9007 + fail(
9008 + "That address isn't from this sign-in. Paste the address your browser went to after you approved.",
9009 + ),
9010 + });
9011 + if (!LOOPBACK_HOSTNAMES.has(callback.hostname)) {
9012 + return yield* fail(
9013 + `Codex takes this sign-in at ${callback.host}. Finish it in a browser that can reach that address.`,
9014 + );
9015 + }
9016 + // Codex listens on the machine it runs on, which may not be the browser's. Its
9017 + // listener closes once a browser reached it, so a refused request can still win.
9018 + delivered = yield* HttpClient.get(callback).pipe(
9019 + Effect.provide(FetchHttpClient.layer),
9020 + Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
9021 + Effect.provideService(HttpClient.TracerPropagationEnabled, false),
9022 + Effect.timeout("10 seconds"),
9023 + Effect.as(true),
9024 + Effect.orElseSucceed(() => false),
9025 + );
9026 + }
9027 + const succeeded = yield* Deferred.await(signIn.succeeded).pipe(
9028 + Effect.timeoutOrElse({
9029 + duration: delivered ? "30 seconds" : "2 seconds",
9030 + orElse: () =>
9031 + Effect.fail(
9032 + fail(
9033 + delivered
9034 + ? `Codex didn't finish the sign-in to ${server}. Start again.`
9035 + : `Codex didn't take the sign-in to ${server}. Start again.`,
9036 + ),
9037 + ),
9038 + }),
9039 + );
9040 + // A newer start may have replaced this sign-in while it finished.
9041 + if (mcpSignIns.get(server) === signIn) mcpSignIns.delete(server);
9042 + if (!succeeded) {
9043 + return yield* fail(`${server} didn't accept the sign-in. Start again.`);
9044 + }
9045 + }),
9046 + },
9047 readThreadSnapshot: Effect.fn("CodexAdapterV2.readThreadSnapshot")(
9048 function* (threadInput) {
9049 const threadId = yield* getNativeThreadId(threadInput.providerThread);
apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
+15
@@ -175,6 +175,9 @@ it.effect.each(deliveries)(
175 mcpServerStatus: Effect.succeed([]),
176 readMcpResource: () => Effect.die("unexpected MCP resource read"),
177 callMcpTool: () => Effect.die("unexpected MCP tool call"),
178 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
179 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
180 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
181 listPermissionRules: Effect.die("unexpected permission rules read"),
182 stopTask: () => Effect.void,
183 interrupt: Effect.die("automatic delivery must never interrupt"),
@@ -521,6 +524,9 @@ it.effect("applies an effort change to the running Claude query without waiting
524 mcpServerStatus: Effect.succeed([]),
525 readMcpResource: () => Effect.die("unexpected MCP resource read"),
526 callMcpTool: () => Effect.die("unexpected MCP tool call"),
527 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
528 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
529 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
530 listPermissionRules: Effect.die("unexpected permission rules read"),
531 stopTask: () => Effect.void,
532 interrupt: Effect.die("an effort change must not interrupt the turn"),
@@ -637,6 +643,9 @@ const renamedClaudeSessionTitles = (options: { readonly renameDuringStartup: boo
643 mcpServerStatus: Effect.succeed([]),
644 readMcpResource: () => Effect.die("unexpected MCP resource read"),
645 callMcpTool: () => Effect.die("unexpected MCP tool call"),
646 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
647 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
648 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
649 listPermissionRules: Effect.die("unexpected permission rules read"),
650 stopTask: () => Effect.void,
651 interrupt: Effect.die("a rename must not interrupt the turn"),
@@ -863,6 +872,9 @@ it.effect("offers a continuation for a later wake after a queued continuation is
872 mcpServerStatus: Effect.succeed([]),
873 readMcpResource: () => Effect.die("unexpected MCP resource read"),
874 callMcpTool: () => Effect.die("unexpected MCP tool call"),
875 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
876 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
877 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
878 listPermissionRules: Effect.die("unexpected permission rules read"),
879 stopTask: () => Effect.void,
880 interrupt: Effect.void,
@@ -1067,6 +1079,9 @@ it.effect.each([
1079 mcpServerStatus: Effect.succeed([]),
1080 readMcpResource: () => Effect.die("unexpected MCP resource read"),
1081 callMcpTool: () => Effect.die("unexpected MCP tool call"),
1082 + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
1083 + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
1084 + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
1085 listPermissionRules: Effect.die("unexpected permission rules read"),
1086 stopTask: () => Effect.void,
1087 interrupt: Queue.shutdown(sdkMessages),
apps/server/src/orchestration-v2/runtimeLayer.ts
+6
@@ -9,6 +9,7 @@ import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore
9 import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";
10 import * as PreviewAgentActivity from "../preview/PreviewAgentActivity.ts";
11 import * as McpAppRequests from "../mcpApps/McpAppRequests.ts";
12 +import * as McpSignIn from "../mcpApps/McpSignIn.ts";
13 import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
14 import * as TextGeneration from "../textGeneration/TextGeneration.ts";
15 import * as ProviderAuthService from "../provider/ProviderAuthService.ts";
@@ -382,10 +383,15 @@ const layerMcpAppRequestsProvided = McpAppRequests.layer.pipe(
383 ),
384 );
385
386 +const layerMcpSignInProvided = McpSignIn.layer.pipe(
387 + Layer.provide(Layer.merge(layerThreadManagementProvided, layerProviderSessionManagerProvided)),
388 +);
389 +
390 export const layer = Layer.mergeAll(
391 layerCommandOutputHubProvided,
392 layerOrchestratorProvided,
393 layerMcpAppRequestsProvided,
394 + layerMcpSignInProvided,
395 layerThreadManagementProvided,
396 layerEffectWorkerProvided,
397 layerProviderSessionManagerProvided,
apps/server/src/ws.test.ts
+2
@@ -95,6 +95,7 @@ import * as HostResources from "./resourceTelemetry/HostResources.ts";
95 import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts";
96 import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts";
97 import * as McpAppRequests from "./mcpApps/McpAppRequests.ts";
98 +import * as McpSignIn from "./mcpApps/McpSignIn.ts";
99 import * as ModelManifest from "./provider/ModelManifest.ts";
100 import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
101 import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts";
@@ -843,6 +844,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
844 Layer.mock(GitWorkflowService.GitWorkflowService)({}),
845 Layer.mock(HostResources.HostResources)({}),
846 Layer.mock(McpAppRequests.McpAppRequests)({}),
847 + Layer.mock(McpSignIn.McpSignIn)({}),
848 Layer.mock(ModelManifest.ModelManifest)({}),
849 Layer.mock(OrchestrationEventStore.OrchestrationEventStore)({}),
850 Layer.mock(Orchestrator.OrchestratorV2)({}),
apps/server/src/ws.ts
+4
@@ -124,6 +124,7 @@ import * as ThreadManagementService from "./orchestration-v2/ThreadManagementSer
124 import * as ThreadViewers from "./orchestration-v2/ThreadViewers.ts";
125 import * as CommandOutputHub from "./orchestration-v2/CommandOutputHub.ts";
126 import * as McpAppRequests from "./mcpApps/McpAppRequests.ts";
127 +import * as McpSignIn from "./mcpApps/McpSignIn.ts";
128 import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
129 import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts";
130 import * as ThreadMessageIntake from "./orchestration-v2/ThreadMessageIntake.ts";
@@ -1462,6 +1463,7 @@ export const layerWsRpc = (
1463
1464 const providerSessionsV2 = yield* ProviderSessionManager.ProviderSessionManagerV2;
1465 const mcpAppRequests = yield* McpAppRequests.McpAppRequests;
1466 + const mcpSignIn = yield* McpSignIn.McpSignIn;
1467 const analytics = yield* AnalyticsService.AnalyticsService;
1468 const originProps = clientAnalyticsProps;
1469 const recordClientCommandAnalytics = (command: OrchestrationV2Command) => {
@@ -2584,6 +2586,8 @@ export const layerWsRpc = (
2586 [WS_METHODS.mcpAppsToolInfo]: (input) => mcpAppRequests.toolInfo(input),
2587 [WS_METHODS.mcpAppsUpdateModelContext]: (input) => mcpAppRequests.updateModelContext(input),
2588 [WS_METHODS.mcpAppsReadResource]: (input) => mcpAppRequests.readResource(input),
2589 + [WS_METHODS.providerMcpSignInStart]: (input) => mcpSignIn.start(input),
2590 + [WS_METHODS.providerMcpSignInComplete]: (input) => mcpSignIn.complete(input),
2591 [WS_METHODS.providerUploadFeedback]:
2592 /* Request instrumentation already owns the span; keep this helper in that context. */
2593 Effect.fnUntraced(
apps/web/src/components/chat/McpSignInAction.tsx new
+214
@@ -0,0 +1,214 @@
1 +import type { EnvironmentId, ProviderThreadId, ThreadId } from "@t3tools/contracts";
2 +import { useAtomValue } from "@effect/atom-react";
3 +import { T, useGT } from "gt-react";
4 +import { CheckIcon, CopyIcon, ExternalLinkIcon } from "lucide-react";
5 +import { useId, useRef, useState, type KeyboardEvent } from "react";
6 +
7 +import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
8 +import { ensureLocalApi } from "../../localApi";
9 +import { formatEnvironmentQueryError } from "../../state/query";
10 +import { threadEnvironment } from "../../state/threads";
11 +import { useAtomCommand } from "../../state/use-atom-command";
12 +import { Button, InlineButton } from "../ui/button";
13 +import {
14 + Dialog,
15 + DialogDescription,
16 + DialogFooter,
17 + DialogHeader,
18 + DialogPanel,
19 + DialogPopup,
20 + DialogTitle,
21 +} from "../ui/dialog";
22 +import { Input } from "../ui/input";
23 +import { toastManager } from "../ui/toast";
24 +
25 +type SignIn =
26 + | { readonly phase: "starting" }
27 + | { readonly phase: "ready" | "finishing"; readonly url: string }
28 + | { readonly phase: "failed"; readonly url: string | null; readonly message: string };
29 +
30 +const stopRowToggle = (event: KeyboardEvent<HTMLElement>) => event.stopPropagation();
31 +
32 +/**
33 + * Signs an MCP server in from the notice that says it needs one. The agent
34 + * keeps the credential; the user approves in a browser, then pastes back the
35 + * address it lands on, which is often a localhost page on another machine.
36 + */
37 +export function McpSignInAction({
38 + environmentId,
39 + threadId,
40 + providerThreadId,
41 + server,
42 + noticeAt,
43 +}: {
44 + readonly environmentId: EnvironmentId;
45 + readonly threadId: ThreadId;
46 + readonly providerThreadId: ProviderThreadId;
47 + readonly server: string;
48 + /** When the environment raised the notice, in epoch milliseconds. */
49 + readonly noticeAt: number;
50 +}) {
51 + const gt = useGT();
52 + const formId = useId();
53 + const allowed = useAtomValue(threadEnvironment.mcpSignInStart.permissionAtom(environmentId));
54 + const signedIn = useAtomValue(
55 + threadEnvironment.mcpSignedInAtom(environmentId, { threadId, server, noticeAt }),
56 + );
57 + const start = useAtomCommand(threadEnvironment.mcpSignInStart, { reportFailure: false });
58 + const complete = useAtomCommand(threadEnvironment.mcpSignInComplete, { reportFailure: false });
59 + const { copyToClipboard, isCopied } = useCopyToClipboard();
60 + const [signIn, setSignIn] = useState<SignIn | null>(null);
61 + const [callbackUrl, setCallbackUrl] = useState("");
62 + // Counts attempts, so a result that lands after a close or a restart changes nothing.
63 + const attempt = useRef(0);
64 + if (!allowed) return null;
65 +
66 + const input = { threadId, providerThreadId, server };
67 + const close = () => {
68 + attempt.current += 1;
69 + setSignIn(null);
70 + };
71 + const done = () => {
72 + close();
73 + toastManager.add({ type: "success", title: gt("Signed in to {server}", { server }) });
74 + };
75 + const begin = async () => {
76 + const current = ++attempt.current;
77 + setSignIn({ phase: "starting" });
78 + setCallbackUrl("");
79 + const result = await start({ environmentId, input });
80 + if (current !== attempt.current) return;
81 + if (result._tag === "Failure") {
82 + setSignIn({ phase: "failed", url: null, message: formatEnvironmentQueryError(result.cause) });
83 + } else if (result.value.authorizationUrl === null) {
84 + done();
85 + } else {
86 + setSignIn({ phase: "ready", url: result.value.authorizationUrl });
87 + }
88 + };
89 + const finish = async (url: string) => {
90 + if (callbackUrl.trim().length === 0) return;
91 + const current = attempt.current;
92 + setSignIn({ phase: "finishing", url });
93 + const result = await complete({
94 + environmentId,
95 + input: { ...input, callbackUrl: callbackUrl.trim() },
96 + });
97 + if (current !== attempt.current) return;
98 + if (result._tag === "Failure") {
99 + setSignIn({ phase: "failed", url, message: formatEnvironmentQueryError(result.cause) });
100 + } else {
101 + done();
102 + }
103 + };
104 + const url = signIn !== null && signIn.phase !== "starting" ? signIn.url : null;
105 +
106 + return (
107 + <>
108 + {signedIn ? (
109 + <span className="shrink-0 text-sm text-success-foreground">
110 + <T>Signed in</T>
111 + </span>
112 + ) : (
113 + <InlineButton
114 + aria-label={gt("Sign in to {server}", { server })}
115 + onClick={(event) => {
116 + event.stopPropagation();
117 + void begin();
118 + }}
119 + onKeyDown={stopRowToggle}
120 + >
121 + <T>Sign in</T>
122 + </InlineButton>
123 + )}
124 + <Dialog
125 + open={signIn !== null}
126 + onOpenChange={(open) => {
127 + if (!open) close();
128 + }}
129 + >
130 + <DialogPopup className="max-w-lg">
131 + <DialogHeader>
132 + <DialogTitle>{gt("Sign in to {server}", { server })}</DialogTitle>
133 + <DialogDescription>
134 + <T>
135 + Approve access in your browser. It then opens a page that may not load: copy that
136 + page's address and paste it here.
137 + </T>
138 + </DialogDescription>
139 + </DialogHeader>
140 + <DialogPanel>
141 + {signIn?.phase === "starting" ? (
142 + <p className="text-sm text-muted-foreground">
143 + <T>Starting the sign-in…</T>
144 + </p>
145 + ) : null}
146 + {url !== null ? (
147 + <form
148 + id={formId}
149 + className="grid gap-4"
150 + onSubmit={(event) => {
151 + event.preventDefault();
152 + void finish(url);
153 + }}
154 + >
155 + <div className="flex flex-wrap gap-2">
156 + <Button
157 + variant="outline"
158 + size="sm"
159 + onClick={() => void ensureLocalApi().shell.openExternal(url)}
160 + >
161 + <ExternalLinkIcon aria-hidden />
162 + <T>Open sign-in page</T>
163 + </Button>
164 + <Button variant="ghost" size="sm" onClick={() => copyToClipboard(url)}>
165 + {isCopied ? <CheckIcon aria-hidden /> : <CopyIcon aria-hidden />}
166 + <T>Copy link</T>
167 + </Button>
168 + </div>
169 + <label className="grid gap-1.5 text-sm">
170 + <T>Address of the page your browser opened</T>
171 + <Input
172 + // Browsers can hide `http://`, which the environment adds back.
173 + inputMode="url"
174 + autoComplete="off"
175 + spellCheck={false}
176 + value={callbackUrl}
177 + maxLength={16_384}
178 + disabled={signIn?.phase === "finishing"}
179 + onChange={(event) => setCallbackUrl(event.target.value)}
180 + />
181 + </label>
182 + </form>
183 + ) : null}
184 + {signIn?.phase === "failed" ? (
185 + <p role="alert" className="mt-3 text-sm text-destructive-foreground">
186 + {signIn.message}
187 + </p>
188 + ) : null}
189 + </DialogPanel>
190 + <DialogFooter variant="bare">
191 + <Button variant="outline" onClick={close}>
192 + <T>Cancel</T>
193 + </Button>
194 + {url === null && signIn?.phase === "failed" ? (
195 + <Button onClick={() => void begin()}>
196 + <T>Try again</T>
197 + </Button>
198 + ) : (
199 + <Button
200 + type="submit"
201 + form={formId}
202 + disabled={
203 + url === null || signIn?.phase === "finishing" || callbackUrl.trim().length === 0
204 + }
205 + >
206 + <T>Finish sign-in</T>
207 + </Button>
208 + )}
209 + </DialogFooter>
210 + </DialogPopup>
211 + </Dialog>
212 + </>
213 + );
214 +}
apps/web/src/components/chat/TimelineWorkEntryRow.tsx
+13
@@ -37,6 +37,8 @@ import ChatMarkdown from "../ChatMarkdown";
37 import { ChatMarkdownAssetImage } from "./ChatMarkdownMedia";
38 import type { ExpandedImagePreview } from "./ExpandedImagePreview";
39 import { workGroupImageGallery } from "./markdownImageGallery";
40 +import { McpSignInAction } from "./McpSignInAction";
41 +import * as DateTime from "effect/DateTime";
42 import { ChevronRightIcon, CircleAlertIcon, XIcon, RotateCcwIcon } from "lucide-react";
43 import { Button, InlineButton } from "../ui/button";
44 import { useAssetUrls } from "../../assets/assetUrls";
@@ -607,6 +609,17 @@ function WorkEntryLogRow(props: WorkEntryRowProps) {
609 <T>Open chat</T>
610 </button>
611 ) : null}
612 + {payload?.type === "system_notice" &&
613 + payload.mcpSignIn !== undefined &&
614 + payload.providerThreadId !== null ? (
615 + <McpSignInAction
616 + environmentId={ctx.activeThreadEnvironmentId}
617 + threadId={payload.threadId}
618 + providerThreadId={payload.providerThreadId}
619 + server={payload.mcpSignIn.server}
620 + noticeAt={DateTime.toEpochMillis(payload.updatedAt)}
621 + />
622 + ) : null}
623 {notifiedSubagentThreadId ? (
624 <InlineButton
625 aria-label={gt("Open subagent thread")}
apps/web/src/i18n/translations/de.json
+6
@@ -3714,6 +3714,12 @@
3714 },
3715 " kann nicht geladen werden"
3716 ],
3717 + "0fd6b38d7839f885": "Bei {server} angemeldet",
3718 + "54789628a737f557": "Bei {server} anmelden",
3719 + "8aecbd38f1facf71": "Erlaube den Zugriff in deinem Browser. Danach öffnet er eine Seite, die vielleicht nicht lädt: Kopiere die Adresse dieser Seite und füge sie hier ein.",
3720 + "2281dc87b05d4a4c": "Anmeldung wird gestartet…",
3721 + "880d3e6e7ff86899": "Adresse der Seite, die dein Browser geöffnet hat",
3722 + "e52585cdfcf317cf": "Anmeldung abschließen",
3723 "9cc6288e83305ca3": "Das Diagramm konnte nicht gerendert werden.",
3724 "74d986aed0381cb0": "Der Diagramm-Renderer konnte nicht geladen werden.",
3725 "d694484d6fea351e": "Diagramm vergrößern",
apps/web/src/i18n/translations/en.json
+6
@@ -3713,6 +3713,12 @@
3713 },
3714 " app"
3715 ],
3716 + "0fd6b38d7839f885": "Signed in to {server}",
3717 + "54789628a737f557": "Sign in to {server}",
3718 + "8aecbd38f1facf71": "Approve access in your browser. It then opens a page that may not load: copy that page's address and paste it here.",
3719 + "2281dc87b05d4a4c": "Starting the sign-in…",
3720 + "880d3e6e7ff86899": "Address of the page your browser opened",
3721 + "e52585cdfcf317cf": "Finish sign-in",
3722 "9cc6288e83305ca3": "The diagram could not be rendered.",
3723 "74d986aed0381cb0": "The diagram renderer failed to load.",
3724 "d694484d6fea351e": "Expand diagram",
apps/web/src/i18n/translations/es.json
+6
@@ -3711,6 +3711,12 @@
3711 "v": "v"
3712 }
3713 ],
3714 + "0fd6b38d7839f885": "Sesión iniciada en {server}",
3715 + "54789628a737f557": "Iniciar sesión en {server}",
3716 + "8aecbd38f1facf71": "Aprueba el acceso en tu navegador. Después abrirá una página que puede no cargar: copia la dirección de esa página y pégala aquí.",
3717 + "2281dc87b05d4a4c": "Iniciando sesión…",
3718 + "880d3e6e7ff86899": "Dirección de la página que abrió tu navegador",
3719 + "e52585cdfcf317cf": "Terminar de iniciar sesión",
3720 "9cc6288e83305ca3": "No se pudo renderizar el diagrama.",
3721 "74d986aed0381cb0": "No se pudo cargar el renderizador de diagramas.",
3722 "d694484d6fea351e": "Expandir diagrama",
apps/web/src/i18n/translations/fr.json
+6
@@ -3712,6 +3712,12 @@
3712 "v": "v"
3713 }
3714 ],
3715 + "0fd6b38d7839f885": "Connecté à {server}",
3716 + "54789628a737f557": "Se connecter à {server}",
3717 + "8aecbd38f1facf71": "Autorisez l’accès dans votre navigateur. Il ouvre ensuite une page qui peut ne pas se charger : copiez l’adresse de cette page et collez-la ici.",
3718 + "2281dc87b05d4a4c": "Démarrage de la connexion…",
3719 + "880d3e6e7ff86899": "Adresse de la page ouverte par votre navigateur",
3720 + "e52585cdfcf317cf": "Terminer la connexion",
3721 "9cc6288e83305ca3": "Impossible d’afficher le diagramme.",
3722 "74d986aed0381cb0": "Le moteur de rendu des diagrammes n’a pas pu se charger.",
3723 "d694484d6fea351e": "Agrandir le diagramme",
apps/web/src/i18n/translations/ja.json
+6
@@ -3705,6 +3705,12 @@
3705 },
3706 " アプリを読み込めません"
3707 ],
3708 + "0fd6b38d7839f885": "{server} にサインインしました",
3709 + "54789628a737f557": "{server} にサインイン",
3710 + "8aecbd38f1facf71": "ブラウザーでアクセスを許可してください。その後、読み込まれない場合があるページが開きます。そのページのアドレスをコピーして、ここに貼り付けてください。",
3711 + "2281dc87b05d4a4c": "サインインを開始しています…",
3712 + "880d3e6e7ff86899": "ブラウザーが開いたページのアドレス",
3713 + "e52585cdfcf317cf": "サインインを完了",
3714 "9cc6288e83305ca3": "図をレンダリングできませんでした。",
3715 "74d986aed0381cb0": "図のレンダラーを読み込めませんでした。",
3716 "d694484d6fea351e": "図を拡大",
apps/web/src/i18n/translations/ko.json
+6
@@ -3705,6 +3705,12 @@
3705 },
3706 " 앱을 불러올 수 없습니다"
3707 ],
3708 + "0fd6b38d7839f885": "{server}에 로그인했습니다",
3709 + "54789628a737f557": "{server}에 로그인",
3710 + "8aecbd38f1facf71": "브라우저에서 액세스를 승인하세요. 그러면 로드되지 않을 수 있는 페이지가 열립니다. 그 페이지의 주소를 복사해 여기에 붙여넣으세요.",
3711 + "2281dc87b05d4a4c": "로그인을 시작하는 중…",
3712 + "880d3e6e7ff86899": "브라우저가 연 페이지의 주소",
3713 + "e52585cdfcf317cf": "로그인 완료",
3714 "9cc6288e83305ca3": "다이어그램을 렌더링할 수 없습니다.",
3715 "74d986aed0381cb0": "다이어그램 렌더러를 불러오지 못했습니다.",
3716 "d694484d6fea351e": "다이어그램 펼치기",
apps/web/src/i18n/translations/pt-BR.json
+6
@@ -3712,6 +3712,12 @@
3712 "v": "v"
3713 }
3714 ],
3715 + "0fd6b38d7839f885": "Você entrou em {server}",
3716 + "54789628a737f557": "Entrar em {server}",
3717 + "8aecbd38f1facf71": "Aprove o acesso no navegador. Depois ele abre uma página que pode não carregar: copie o endereço dessa página e cole aqui.",
3718 + "2281dc87b05d4a4c": "Iniciando o login…",
3719 + "880d3e6e7ff86899": "Endereço da página que o navegador abriu",
3720 + "e52585cdfcf317cf": "Concluir login",
3721 "9cc6288e83305ca3": "Não foi possível renderizar o diagrama.",
3722 "74d986aed0381cb0": "Falha ao carregar o renderizador de diagramas.",
3723 "d694484d6fea351e": "Expandir diagrama",
apps/web/src/i18n/translations/ru.json
+6
@@ -3712,6 +3712,12 @@
3712 "v": "v"
3713 }
3714 ],
3715 + "0fd6b38d7839f885": "Вход в {server} выполнен",
3716 + "54789628a737f557": "Войти в {server}",
3717 + "8aecbd38f1facf71": "Разрешите доступ в браузере. Затем он откроет страницу, которая может не загрузиться: скопируйте адрес этой страницы и вставьте его сюда.",
3718 + "2281dc87b05d4a4c": "Начинаем вход…",
3719 + "880d3e6e7ff86899": "Адрес страницы, которую открыл браузер",
3720 + "e52585cdfcf317cf": "Завершить вход",
3721 "9cc6288e83305ca3": "Не удалось отрисовать диаграмму.",
3722 "74d986aed0381cb0": "Не удалось загрузить отрисовщик диаграмм.",
3723 "d694484d6fea351e": "Развернуть диаграмму",
apps/web/src/i18n/translations/sv.json
+6
@@ -3712,6 +3712,12 @@
3712 "v": "v"
3713 }
3714 ],
3715 + "0fd6b38d7839f885": "Inloggad på {server}",
3716 + "54789628a737f557": "Logga in på {server}",
3717 + "8aecbd38f1facf71": "Godkänn åtkomsten i webbläsaren. Den öppnar sedan en sida som kanske inte laddas: kopiera sidans adress och klistra in den här.",
3718 + "2281dc87b05d4a4c": "Startar inloggningen…",
3719 + "880d3e6e7ff86899": "Adressen till sidan som webbläsaren öppnade",
3720 + "e52585cdfcf317cf": "Slutför inloggningen",
3721 "9cc6288e83305ca3": "Diagrammet kunde inte renderas.",
3722 "74d986aed0381cb0": "Diagramrenderaren kunde inte läsas in.",
3723 "d694484d6fea351e": "Expandera diagram",
apps/web/src/i18n/translations/zh.json
+6
@@ -3716,6 +3716,12 @@
3716 },
3717 " 应用"
3718 ],
3719 + "0fd6b38d7839f885": "已登录 {server}",
3720 + "54789628a737f557": "登录 {server}",
3721 + "8aecbd38f1facf71": "请在浏览器中批准访问。之后浏览器会打开一个可能无法加载的页面:复制该页面的地址并粘贴到这里。",
3722 + "2281dc87b05d4a4c": "正在开始登录…",
3723 + "880d3e6e7ff86899": "浏览器打开的页面地址",
3724 + "e52585cdfcf317cf": "完成登录",
3725 "9cc6288e83305ca3": "无法渲染图表。",
3726 "74d986aed0381cb0": "图表渲染器加载失败。",
3727 "d694484d6fea351e": "放大图表",
docs/user/providers-claude.md
+9
@@ -118,6 +118,15 @@ To show Claude task lists in the web and desktop apps, add
118 **Environment** section in **Settings > Providers**. Each update shows as a Tasks
119 row in the thread; open it to see every step.
120
121 +## Sign in to an MCP server
122 +
123 +When an MCP server you added to Claude needs you to sign in, the thread shows a notice with
124 +**Sign in**, once per session; on mobile, tap the notice. Approve access on the page it opens. Your
125 +browser then goes to a page that may not load, especially when Claude runs on another machine:
126 +copy that page's address, paste it into T3 Code, and choose **Finish sign-in**. Claude keeps the
127 +sign-in and reconnects the server. Connectors you added on claude.ai are signed in on claude.ai,
128 +so T3 Code doesn't ask about them. Signing in needs permission to manage providers.
129 +
130 ## Claude in Chrome
131
132 Claude threads can use the Claude in Chrome extension, which works in your own
docs/user/providers-codex.md
+10
@@ -128,6 +128,16 @@ in the thread on web, desktop, or mobile. Some tools offer access for one reques
128 the current session, or permanently. See [Permission modes](./permission-modes.md)
129 for command and file approvals.
130
131 +## Sign in to an MCP server
132 +
133 +When an MCP server you added to Codex needs you to sign in, the thread shows a notice with
134 +**Sign in**; on mobile, tap the notice. Approve access on the page it opens. Your browser then goes
135 +to a page that may not load, especially when Codex runs on another machine: copy that page's
136 +address, paste it into T3 Code, and choose **Finish sign-in**. Codex reconnects the server in that
137 +thread and keeps the sign-in for other threads on the same Codex instance; an instance with its own
138 +home, such as a second account, may need to sign in separately. Signing in needs permission to
139 +manage providers.
140 +
141 ## Use the OpenAI Chrome extension
142
143 Connecting ChatGPT in **Settings → Providers** signs in the Codex provider.
packages/client-runtime/src/state/commandPermissions.test.ts
+2
@@ -155,6 +155,8 @@ describe("command permissions", () => {
155 it.effect.each([
156 { method: WS_METHODS.serverRunStorageCleanup, scope: AuthSettingsWriteScope },
157 { method: WS_METHODS.serverReclaimDatabaseSpace, scope: AuthEnvironmentMaintainScope },
158 + { method: WS_METHODS.providerMcpSignInStart, scope: AuthProvidersManageScope },
159 + { method: WS_METHODS.providerMcpSignInComplete, scope: AuthProvidersManageScope },
160 ])("requires the destination $scope grant for $method", ({ method, scope }) =>
161 Effect.gen(function* () {
162 const registry = yield* setup;
packages/client-runtime/src/state/threadCommands.ts
+49
@@ -154,6 +154,37 @@ export function createThreadEnvironmentAtoms<R, E>(
154 }),
155 });
156
157 + // The environment's time of the last sign-in to a server in a thread, until the app reloads.
158 + const mcpSignedInAtFamily = Atom.family((_key: string) =>
159 + Atom.make<number | null>(null).pipe(Atom.keepAlive),
160 + );
161 + const mcpSignInKey = (
162 + environmentId: EnvironmentId,
163 + input: { readonly threadId: ThreadId; readonly server: string },
164 + ) => JSON.stringify([environmentId, input.threadId, input.server]);
165 + const markMcpSignedIn = (
166 + registry: AtomRegistry.AtomRegistry,
167 + environmentId: EnvironmentId,
168 + input: { readonly threadId: ThreadId; readonly server: string },
169 + signedInAt: string,
170 + ) =>
171 + registry.update(mcpSignedInAtFamily(mcpSignInKey(environmentId, input)), (current) =>
172 + Math.max(current ?? 0, Date.parse(signedInAt)),
173 + );
174 + const mcpNoticeSignedInFamily = Atom.family((key: string) => {
175 + const [signInKey, noticeAt] = JSON.parse(key) as [string, number];
176 + // A notice newer than the sign-in means the server needs one again.
177 + return Atom.make((get) => {
178 + const signedInAt = get(mcpSignedInAtFamily(signInKey));
179 + return signedInAt !== null && noticeAt <= signedInAt;
180 + });
181 + });
182 + /** Whether a sign-in notice, by its environment time, came before the server was signed in. */
183 + const mcpSignedInAtom = (
184 + environmentId: EnvironmentId,
185 + input: { readonly threadId: ThreadId; readonly server: string; readonly noticeAt: number },
186 + ) =>
187 + mcpNoticeSignedInFamily(JSON.stringify([mcpSignInKey(environmentId, input), input.noticeAt]));
188 const sent = {
189 armTitleRegeneration: createEnvironmentCommand(runtime, {
190 label: "environment-data:commands:thread:regenerate-title",
@@ -435,6 +466,23 @@ export function createThreadEnvironmentAtoms<R, E>(
466 scheduler,
467 concurrency,
468 }),
469 + // Outside the thread's queue: finishing can wait on the agent, and messages must not.
470 + mcpSignInStart: createEnvironmentRpcCommand(runtime, {
471 + label: "environment-data:commands:thread:mcp-sign-in-start",
472 + tag: WS_METHODS.providerMcpSignInStart,
473 + onSuccess: ({ environmentId, input }, registry, result) =>
474 + Effect.sync(() => {
475 + if (result.signedInAt !== null) {
476 + markMcpSignedIn(registry, environmentId, input, result.signedInAt);
477 + }
478 + }),
479 + }),
480 + mcpSignInComplete: createEnvironmentRpcCommand(runtime, {
481 + label: "environment-data:commands:thread:mcp-sign-in-complete",
482 + tag: WS_METHODS.providerMcpSignInComplete,
483 + onSuccess: ({ environmentId, input }, registry, result) =>
484 + Effect.sync(() => markMcpSignedIn(registry, environmentId, input, result.signedInAt)),
485 + }),
486 };
487 const commands = {
488 ...sent,
@@ -481,6 +529,7 @@ export function createThreadEnvironmentAtoms<R, E>(
529 ...commands,
530 regenerateTitle,
531 rowActionsAtom,
532 + mcpSignedInAtom,
533 snapshotAtom: optimistic.snapshotAtom,
534 pendingThreadIdsAtom: optimistic.pendingThreadIdsAtom,
535 settle: optimistic.wrap(commands.settle, (thread, _input, now, accepted) =>
packages/contracts/src/clientRpcPermissions.ts
+3
@@ -18,6 +18,9 @@ import { WS_METHODS } from "./rpc.ts";
18 /** Incremental client enforcement; the server still authorizes every request. */
19 export const CLIENT_GUARDED_RPC_SCOPES = {
20 [WS_METHODS.providerAuthRemoveMethod]: AuthProvidersManageScope,
21 + // An MCP sign-in stores a credential for the agent, as an account sign-in does.
22 + [WS_METHODS.providerMcpSignInStart]: AuthProvidersManageScope,
23 + [WS_METHODS.providerMcpSignInComplete]: AuthProvidersManageScope,
24 [WS_METHODS.previewClose]: AuthPreviewOperateScope,
25 // Stopping a server signals its processes, as closing a terminal does.
26 [WS_METHODS.previewStopLocalServer]: AuthTerminalOperateScope,
packages/contracts/src/orchestrationV2.ts
+5
@@ -1659,6 +1659,9 @@ export type OrchestrationV2UserMessageInputIntent =
1659 /** Notices without a level predate it and are warnings. */
1660 const OrchestrationV2SystemNoticeLevel = Schema.Literals(["info", "warning", "error"]);
1661
1662 +/** A notice about an MCP server that a sign-in from the thread would fix. */
1663 +const OrchestrationV2McpSignIn = Schema.Struct({ server: Schema.String });
1664 +
1665 /** A same-harness model or effort change that took effect with this message. */
1666 export const OrchestrationV2ModelSwitch = Schema.Struct({
1667 from: ModelSelection,
@@ -1918,6 +1921,7 @@ export const OrchestrationV2TurnItem = Schema.Union([
1921 type: Schema.Literal("system_notice"),
1922 message: Schema.String,
1923 level: Schema.optional(OrchestrationV2SystemNoticeLevel),
1924 + mcpSignIn: Schema.optional(OrchestrationV2McpSignIn),
1925 }),
1926 Schema.Struct({
1927 ...OrchestrationV2TurnItemBaseFields,
@@ -2807,6 +2811,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
2811 type: Schema.Literal("system_notice"),
2812 message: Schema.String,
2813 level: Schema.optional(OrchestrationV2SystemNoticeLevel),
2814 + mcpSignIn: Schema.optional(OrchestrationV2McpSignIn),
2815 }),
2816 Schema.Struct({
2817 ...OrchestrationV2TurnItemJsonBaseFields,
packages/contracts/src/provider.ts
+46 -1
@@ -1,5 +1,5 @@
1 import * as Schema from "effect/Schema";
2 -import { TrimmedNonEmptyString } from "./baseSchemas.ts";
2 +import { IsoDateTime, ProviderThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
3 import { ThreadId } from "./baseSchemas.ts";
4 import {
5 getProviderAttachmentLimitError,
@@ -8,6 +8,7 @@ import {
8 } from "./chatAttachment.ts";
9 import { ModelSelection } from "./modelSelection.ts";
10 import { ProviderInteractionMode } from "./providerPolicy.ts";
11 +import { SignInUrl } from "./providerSetup.ts";
12
13 export const ProviderSendTurnInput = Schema.Struct({
14 threadId: ThreadId,
@@ -37,6 +38,50 @@ export const ProviderUploadFeedbackResult = Schema.Struct({
38 });
39 export type ProviderUploadFeedbackResult = typeof ProviderUploadFeedbackResult.Type;
40
41 +const McpServerName = TrimmedNonEmptyString.check(Schema.isMaxLength(256));
42 +
43 +/** One of an agent's MCP servers, in the thread whose session asked for a sign-in. */
44 +export const ProviderMcpSignInStartInput = Schema.Struct({
45 + threadId: ThreadId,
46 + providerThreadId: ProviderThreadId,
47 + server: McpServerName,
48 +});
49 +export type ProviderMcpSignInStartInput = typeof ProviderMcpSignInStartInput.Type;
50 +
51 +export const ProviderMcpSignInStartResult = Schema.Struct({
52 + /** The page to approve the sign-in on; null when the server needs none any more. */
53 + authorizationUrl: Schema.NullOr(SignInUrl),
54 + /** The environment's time when it found the server already signed in. */
55 + signedInAt: Schema.NullOr(IsoDateTime),
56 +});
57 +export type ProviderMcpSignInStartResult = typeof ProviderMcpSignInStartResult.Type;
58 +
59 +export const ProviderMcpSignInCompleteInput = Schema.Struct({
60 + ...ProviderMcpSignInStartInput.fields,
61 + /** The address the browser was sent to after approving, usually a localhost page. */
62 + callbackUrl: TrimmedNonEmptyString.check(Schema.isMaxLength(16_384)),
63 +});
64 +export type ProviderMcpSignInCompleteInput = typeof ProviderMcpSignInCompleteInput.Type;
65 +
66 +export const ProviderMcpSignInCompleteResult = Schema.Struct({
67 + /** The environment's time, so a later notice that needs a sign-in again offers one. */
68 + signedInAt: IsoDateTime,
69 +});
70 +export type ProviderMcpSignInCompleteResult = typeof ProviderMcpSignInCompleteResult.Type;
71 +
72 +/** Safe to show: never carries the callback URL, codes or tokens. */
73 +export class ProviderMcpSignInError extends Schema.TaggedError<ProviderMcpSignInError>()(
74 + "ProviderMcpSignInError",
75 + {
76 + server: Schema.String,
77 + detail: Schema.String,
78 + },
79 +) {
80 + override get message(): string {
81 + return this.detail;
82 + }
83 +}
84 +
85 export class ProviderUploadFeedbackError extends Schema.TaggedError<ProviderUploadFeedbackError>()(
86 "ProviderUploadFeedbackError",
87 {
packages/contracts/src/providerSetup.ts
+1 -1
@@ -16,7 +16,7 @@ export type ProviderSetupInput = typeof ProviderSetupInput.Type;
16
17 const SetupOperationId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
18 // Environments supply these and clients open them, so a `javascript:` URL would run as the client.
19 -const SignInUrl = TrimmedNonEmptyString.check(
19 +export const SignInUrl = TrimmedNonEmptyString.check(
20 Schema.isMaxLength(16_384),
21 Schema.isPattern(/^https?:\/\//i),
22 );
packages/contracts/src/rpc.ts
+21
@@ -171,6 +171,11 @@ import {
171 import { KeybindingsConfigError } from "./keybindings.ts";
172 import { OrchestrationSearchThreadsError } from "./threadSearch.ts";
173 import {
174 + ProviderMcpSignInCompleteInput,
175 + ProviderMcpSignInCompleteResult,
176 + ProviderMcpSignInError,
177 + ProviderMcpSignInStartInput,
178 + ProviderMcpSignInStartResult,
179 ProviderUploadFeedbackError,
180 ProviderUploadFeedbackInput,
181 ProviderUploadFeedbackResult,
@@ -477,6 +482,8 @@ export const WS_METHODS = {
482 mcpAppsUpdateModelContext: "mcpApps.updateModelContext",
483
484 providerUploadFeedback: "provider.uploadFeedback",
485 + providerMcpSignInStart: "provider.mcpSignIn.start",
486 + providerMcpSignInComplete: "provider.mcpSignIn.complete",
487 providerAuthStart: "provider.auth.start",
488 providerConsumeResetCredit: "provider.consumeResetCredit",
489 providerAuthComplete: "provider.auth.complete",
@@ -1708,6 +1715,18 @@ const WsProviderUploadFeedbackRpc = Rpc.make(WS_METHODS.providerUploadFeedback,
1715 error: Schema.Union([ProviderUploadFeedbackError, EnvironmentAuthorizationError]),
1716 });
1717
1718 +const WsProviderMcpSignInStartRpc = Rpc.make(WS_METHODS.providerMcpSignInStart, {
1719 + payload: ProviderMcpSignInStartInput,
1720 + success: ProviderMcpSignInStartResult,
1721 + error: Schema.Union([ProviderMcpSignInError, EnvironmentAuthorizationError]),
1722 +});
1723 +
1724 +const WsProviderMcpSignInCompleteRpc = Rpc.make(WS_METHODS.providerMcpSignInComplete, {
1725 + payload: ProviderMcpSignInCompleteInput,
1726 + success: ProviderMcpSignInCompleteResult,
1727 + error: Schema.Union([ProviderMcpSignInError, EnvironmentAuthorizationError]),
1728 +});
1729 +
1730 const WsSubscribeVcsBranchRpc = Rpc.make(WS_METHODS.subscribeVcsBranch, {
1731 payload: VcsStatusInput,
1732 success: VcsBranchStatus,
@@ -2465,6 +2484,8 @@ export const WsRpcGroup = RpcGroup.make(
2484 WsMcpAppsReadResourceRpc,
2485 WsMcpAppsUpdateModelContextRpc,
2486 WsProviderUploadFeedbackRpc,
2487 + WsProviderMcpSignInStartRpc,
2488 + WsProviderMcpSignInCompleteRpc,
2489 WsSubscribeVcsStatusRpc,
2490 WsSubscribeVcsBranchRpc,
2491 WsVcsRefreshBranchRpc,
packages/provider-core/src/server/ProviderAdapter.ts
+23
@@ -22,6 +22,7 @@ import {
22 ProviderInteractionMode,
23 ProviderDriverKind,
24 ProviderInstanceId,
25 + ProviderMcpSignInError,
26 PositiveInt,
27 ProviderUserInputAnswers,
28 ProviderSessionId,
@@ -691,6 +692,26 @@ export interface ProviderAdapterV2McpApps {
692 }) => Effect.Effect<{ readonly contents: ReadonlyArray<unknown> }, ProviderAdapterV2Error>;
693 }
694
695 +/**
696 + * Signs one of the session's MCP servers in. `start` returns the page to approve
697 + * on; `complete` takes the address the browser was sent back to afterwards,
698 + * usually a localhost page that may sit on another machine, and finishes here.
699 + */
700 +export interface ProviderAdapterV2McpSignIn {
701 + readonly start: (input: {
702 + readonly providerThread: OrchestrationV2ProviderThread;
703 + readonly server: string;
704 + }) => Effect.Effect<
705 + { readonly authorizationUrl: string | null },
706 + ProviderMcpSignInError | ProviderAdapterV2Error
707 + >;
708 + readonly complete: (input: {
709 + readonly providerThread: OrchestrationV2ProviderThread;
710 + readonly server: string;
711 + readonly callbackUrl: string;
712 + }) => Effect.Effect<void, ProviderMcpSignInError | ProviderAdapterV2Error>;
713 +}
714 +
715 export type ProviderAdapterV2SubagentOutcome = {
716 readonly status: "completed" | "failed" | "cancelled";
717 readonly completedAt: NonNullable<OrchestrationV2Subagent["completedAt"]>;
@@ -804,6 +825,8 @@ export interface ProviderAdapterV2SessionRuntime {
825 }) => Effect.Effect<{ readonly feedbackId: string }, ProviderAdapterV2Error>;
826 /** Absent means non-interactive apps with plain tool rows. */
827 readonly mcpApps?: ProviderAdapterV2McpApps;
828 + /** Absent when the agent has no way to sign an MCP server in. */
829 + readonly mcpSignIn?: ProviderAdapterV2McpSignIn;
830 readonly rollbackThread: (
831 input: ProviderAdapterV2RollbackThreadInput,
832 ) => Effect.Effect<ProviderAdapterV2ThreadSnapshot, ProviderAdapterV2Error>;
packages/shared/package.json
+4
@@ -495,6 +495,10 @@
495 "types": "./src/codexAuthHandoff.ts",
496 "import": "./src/codexAuthHandoff.ts"
497 },
498 + "./oauthCallback": {
499 + "types": "./src/oauthCallback.ts",
500 + "import": "./src/oauthCallback.ts"
501 + },
502 "./codexArtifactTemplates": {
503 "types": "./src/codexArtifactTemplates.ts",
504 "import": "./src/codexArtifactTemplates.ts"
packages/shared/src/codexAuthHandoff.ts
+3 -25
@@ -1,5 +1,6 @@
1 import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
2 import * as Schema from "effect/Schema";
3 +import { oauthCallbackUrl } from "./oauthCallback.ts";
4 import { providerAuthReturnUrl } from "./providerAuthReturnUrl.ts";
5
6 export const CodexAuthHandoff = Schema.Struct({
@@ -56,32 +57,9 @@ export function codexAuthorizationRequest(value: string) {
57 }
58
59 export function codexCallbackUrl(value: string, redirectUri: string, state: string) {
59 - const expected = new URL(redirectUri);
60 - const pasted = value.trimStart();
61 - // Browsers can hide `http://` in the address bar, so a pasted callback may lack it.
62 - const callback = new URL(
63 - /^[a-z][a-z\d+.-]*:\/\//iu.test(pasted) ? pasted : `${expected.protocol}//${pasted}`,
64 - );
65 - const states = callback.searchParams.getAll("state");
66 - const codes = callback.searchParams.getAll("code");
67 - const errors = callback.searchParams.getAll("error");
60 + const callback = oauthCallbackUrl(value, redirectUri, state);
61 const clients = callback.searchParams.getAll("client_id");
69 - if (
70 - value.length > 16_384 ||
71 - callback.origin !== expected.origin ||
72 - callback.pathname !== expected.pathname ||
73 - callback.username ||
74 - callback.password ||
75 - callback.hash ||
76 - states.length !== 1 ||
77 - states[0] !== state ||
78 - clients.length > 1 ||
79 - (clients.length === 1 && !/^oaiapp_[\w-]+$/u.test(clients[0]!)) ||
80 - !(
81 - (codes.length === 1 && Boolean(codes[0]) && errors.length === 0) ||
82 - (errors.length === 1 && Boolean(errors[0]) && codes.length === 0)
83 - )
84 - )
62 + if (clients.length > 1 || (clients.length === 1 && !/^oaiapp_[\w-]+$/u.test(clients[0]!)))
63 throw new Error("This redirect URL does not belong to the current sign-in.");
64 return callback;
65 }
packages/shared/src/oauthCallback.ts new
+34
@@ -0,0 +1,34 @@
1 +/**
2 + * The address an OAuth sign-in sent the browser back to, as the user pasted it,
3 + * if it answers this sign-in: the redirect's own address, its one state, and
4 + * one code or one error. Throws otherwise.
5 + */
6 +export function oauthCallbackUrl(value: string, redirectUri: string, state: string) {
7 + const expected = new URL(redirectUri);
8 + const callback = pastedUrl(value, expected.protocol);
9 + const states = callback.searchParams.getAll("state");
10 + const codes = callback.searchParams.getAll("code");
11 + const errors = callback.searchParams.getAll("error");
12 + if (
13 + value.length > 16_384 ||
14 + callback.origin !== expected.origin ||
15 + callback.pathname !== expected.pathname ||
16 + callback.username ||
17 + callback.password ||
18 + callback.hash ||
19 + states.length !== 1 ||
20 + states[0] !== state ||
21 + !(
22 + (codes.length === 1 && Boolean(codes[0]) && errors.length === 0) ||
23 + (errors.length === 1 && Boolean(errors[0]) && codes.length === 0)
24 + )
25 + )
26 + throw new Error("This redirect URL does not belong to the current sign-in.");
27 + return callback;
28 +}
29 +
30 +/** A URL copied from an address bar, which can hide its `http://`. Throws if it isn't one. */
31 +export function pastedUrl(value: string, protocol = "http:") {
32 + const pasted = value.trim();
33 + return new URL(/^[a-z][a-z\d+.-]*:\/\//iu.test(pasted) ? pasted : `${protocol}//${pasted}`);
34 +}