import { useReducer, useCallback, useEffect, useRef, useState, type ReactNode } from "react"; import { useAtomSet } from "@effect-atom/atom-react"; import { useScope } from "@executor/react/api/scope-context"; import { Button } from "@executor/react/components/button"; import { CardStack, CardStackContent, CardStackEntry, CardStackEntryActions, CardStackEntryContent, CardStackEntryDescription, CardStackEntryField, CardStackEntryMedia, CardStackEntryTitle, } from "@executor/react/components/card-stack"; import { FieldError, FieldLabel } from "@executor/react/components/field"; import { FilterTabs } from "@executor/react/components/filter-tabs"; import { FloatActions } from "@executor/react/components/float-actions"; import { Input } from "@executor/react/components/input"; import { Label } from "@executor/react/components/label"; import { Badge } from "@executor/react/components/badge"; import { Skeleton } from "@executor/react/components/skeleton"; import { SourceFavicon } from "@executor/react/components/source-favicon"; import { IOSSpinner, Spinner } from "@executor/react/components/spinner"; import { Textarea } from "@executor/react/components/textarea"; import { HeadersList } from "@executor/react/plugins/headers-list"; import { type HeaderState } from "@executor/react/plugins/secret-header-auth"; import { displayNameFromUrl, slugifyNamespace, SourceIdentityFields, useSourceIdentity, } from "@executor/react/plugins/source-identity"; import { useSecretPickerSecrets } from "@executor/react/plugins/use-secret-picker-secrets"; type RemoteAuthMode = "none" | "header" | "oauth2"; import { sourceWriteKeys } from "@executor/react/api/reactivity-keys"; import { usePendingSources } from "@executor/react/api/optimistic"; import { probeMcpEndpoint, addMcpSource, startMcpOAuth } from "./atoms"; import { mcpPresets, type McpPreset } from "../sdk/presets"; // --------------------------------------------------------------------------- // Preset lookup // --------------------------------------------------------------------------- function findPreset(id: string | undefined): McpPreset | undefined { if (!id) return undefined; return mcpPresets.find((p) => p.id === id); } // --------------------------------------------------------------------------- // State machine (remote flow) // --------------------------------------------------------------------------- type OAuthTokens = { accessTokenSecretId: string; refreshTokenSecretId: string | null; tokenType: string; expiresAt: number | null; scope: string | null; }; type ProbeResult = { connected: boolean; requiresOAuth: boolean; name: string; namespace: string; toolCount: number | null; serverName: string | null; }; type PlainHeader = { name: string; value: string; }; type State = | { step: "url"; url: string } | { step: "probing"; url: string } | { step: "probed"; url: string; probe: ProbeResult } | { step: "oauth-starting"; url: string; probe: ProbeResult } | { step: "oauth-waiting"; url: string; probe: ProbeResult; sessionId: string; } | { step: "oauth-done"; url: string; probe: ProbeResult; tokens: OAuthTokens } | { step: "adding"; url: string; probe: ProbeResult; tokens: OAuthTokens | null; } | { step: "error"; url: string; probe: ProbeResult | null; tokens: OAuthTokens | null; error: string; }; type Action = | { type: "set-url"; url: string } | { type: "probe-start" } | { type: "probe-ok"; probe: ProbeResult } | { type: "probe-fail"; error: string } | { type: "oauth-start" } | { type: "oauth-waiting"; sessionId: string } | { type: "oauth-ok"; tokens: OAuthTokens } | { type: "oauth-fail"; error: string } | { type: "oauth-cancelled" } | { type: "add-start" } | { type: "add-fail"; error: string } | { type: "retry" }; const init: State = { step: "url", url: "" }; function reducer(state: State, action: Action): State { switch (action.type) { case "set-url": return { step: "url", url: action.url }; case "probe-start": return { step: "probing", url: state.url }; case "probe-ok": return { step: "probed", url: state.url, probe: action.probe }; case "probe-fail": return { step: "error", url: state.url, probe: null, tokens: null, error: action.error, }; case "oauth-start": if (state.step !== "probed" && state.step !== "error") return state; return { step: "oauth-starting", url: state.url, probe: state.step === "probed" ? state.probe : state.probe!, }; case "oauth-waiting": if (state.step !== "oauth-starting") return state; return { step: "oauth-waiting", url: state.url, probe: state.probe, sessionId: action.sessionId, }; case "oauth-ok": if (state.step !== "oauth-waiting") return state; return { step: "oauth-done", url: state.url, probe: state.probe, tokens: action.tokens, }; case "oauth-fail": if (state.step !== "oauth-starting" && state.step !== "oauth-waiting") return state; return { step: "error", url: state.url, probe: state.probe, tokens: null, error: action.error, }; case "oauth-cancelled": if (state.step !== "oauth-waiting") return state; return { step: "probed", url: state.url, probe: state.probe }; case "add-start": { const tokens = state.step === "oauth-done" ? state.tokens : state.step === "probed" ? null : null; const probe = "probe" in state ? state.probe : null; if (!probe) return state; return { step: "adding", url: state.url, probe, tokens }; } case "add-fail": if (state.step !== "adding") return state; return { step: "error", url: state.url, probe: state.probe, tokens: state.tokens, error: action.error, }; case "retry": { if (state.step !== "error") return state; return state.probe ? state.tokens ? { step: "oauth-done", url: state.url, probe: state.probe, tokens: state.tokens, } : { step: "probed", url: state.url, probe: state.probe } : { step: "url", url: state.url }; } default: return state; } } // --------------------------------------------------------------------------- // OAuth popup // --------------------------------------------------------------------------- type OAuthPopupResult = | ({ type: "executor:oauth-result"; ok: true; sessionId: string; } & OAuthTokens) | { type: "executor:oauth-result"; ok: false; sessionId: null; error: string; }; const OAUTH_RESULT_CHANNEL = "executor:mcp-oauth-result"; const isOAuthPopupResult = (value: unknown): value is OAuthPopupResult => typeof value === "object" && value !== null && (value as { type?: unknown }).type === "executor:oauth-result"; function openOAuthPopup( url: string, onResult: (data: OAuthPopupResult) => void, onOpenFailed?: () => void, ): () => void { const w = 600, h = 700; const left = window.screenX + (window.outerWidth - w) / 2; const top = window.screenY + (window.outerHeight - h) / 2; let settled = false; const channel = typeof BroadcastChannel !== "undefined" ? new BroadcastChannel(OAUTH_RESULT_CHANNEL) : null; const settle = () => { if (settled) return; settled = true; window.removeEventListener("message", onMsg); channel?.close(); }; const handleResult = (data: unknown) => { if (!isOAuthPopupResult(data) || settled) return; settle(); onResult(data); }; const onMsg = (e: MessageEvent) => { if (e.origin === window.location.origin) handleResult(e.data); }; window.addEventListener("message", onMsg); if (channel) channel.onmessage = (e) => handleResult(e.data); const popup = window.open( url, "mcp-oauth", `width=${w},height=${h},left=${left},top=${top},popup=1`, ); if (!popup && !settled) { settle(); queueMicrotask(() => onOpenFailed?.()); } return settle; } // --------------------------------------------------------------------------- // Component // --------------------------------------------------------------------------- export default function AddMcpSource(props: { onComplete: () => void; onCancel: () => void; initialUrl?: string; initialPreset?: string; /** Whether the stdio transport is enabled on the server. */ allowStdio?: boolean; }) { const allowStdio = props.allowStdio ?? false; const rawPreset = findPreset(props.initialPreset); // Drop stdio presets when stdio is disabled — the caller should have // already filtered these out, but defence-in-depth. const preset = rawPreset?.transport === "stdio" && !allowStdio ? undefined : rawPreset; const isStdioPreset = preset?.transport === "stdio"; const [transport, setTransport] = useState<"remote" | "stdio">( isStdioPreset && allowStdio ? "stdio" : "remote", ); // --- Stdio state --- const [stdioCommand, setStdioCommand] = useState(isStdioPreset ? preset.command : ""); const [stdioArgs, setStdioArgs] = useState( isStdioPreset && preset.args ? preset.args.join(" ") : "", ); const [stdioEnv, setStdioEnv] = useState(""); const stdioIdentity = useSourceIdentity({ fallbackName: isStdioPreset ? preset.name : stdioCommand, }); const [stdioAdding, setStdioAdding] = useState(false); const [stdioError, setStdioError] = useState(null); // --- Remote state --- const remoteUrl = !isStdioPreset && preset?.transport === undefined && preset?.url ? preset.url : (props.initialUrl ?? ""); const [state, dispatch] = useReducer( reducer, remoteUrl ? { step: "url" as const, url: remoteUrl } : init, ); const scopeId = useScope(); const doProbe = useAtomSet(probeMcpEndpoint, { mode: "promise" }); const doAdd = useAtomSet(addMcpSource, { mode: "promise" }); const doStartOAuth = useAtomSet(startMcpOAuth, { mode: "promise" }); const { beginAdd } = usePendingSources(); const secretList = useSecretPickerSecrets(); const [remoteAuthMode, setRemoteAuthMode] = useState("none"); const [remoteAuthHeaders, setRemoteAuthHeaders] = useState([ { name: "Authorization", prefix: "Bearer ", presetKey: "bearer", secretId: null, }, ]); const [remoteHeaders, setRemoteHeaders] = useState([]); const probe = "probe" in state ? state.probe : null; const tokens = "tokens" in state ? state.tokens : null; const remoteIdentity = useSourceIdentity({ fallbackName: probe?.serverName ?? probe?.name ?? displayNameFromUrl(state.url) ?? "", }); const isProbing = state.step === "probing"; const isAdding = state.step === "adding"; const isOAuthBusy = state.step === "oauth-starting" || state.step === "oauth-waiting"; const canUseNone = probe?.requiresOAuth !== true; const remoteAuthHeader = remoteAuthHeaders[0]; const headerAuthComplete = Boolean(remoteAuthHeader?.name.trim() && remoteAuthHeader?.secretId); const remoteHeadersComplete = remoteHeaders.every( (header) => header.name.trim() && header.value.trim(), ); const authReady = remoteAuthMode === "none" ? canUseNone : remoteAuthMode === "header" ? headerAuthComplete : tokens !== null; const canAdd = Boolean(probe) && authReady && remoteHeadersComplete && !isAdding && !isOAuthBusy; // Probe failures are shown inline on the URL field; other failures // (OAuth start, add source) render in the bottom error block. const probeError = state.step === "error" && state.probe === null ? state.error : null; const otherError = state.step === "error" && state.probe !== null ? state.error : null; // ---- Remote actions ---- const handleProbe = useCallback(async () => { dispatch({ type: "probe-start" }); try { const result = await doProbe({ path: { scopeId }, payload: { endpoint: state.url.trim() }, }); setRemoteAuthMode(result.requiresOAuth ? "oauth2" : "none"); dispatch({ type: "probe-ok", probe: result }); } catch (e) { dispatch({ type: "probe-fail", error: e instanceof Error ? e.message : "Failed to connect", }); } }, [state.url, scopeId, doProbe]); // Keep the latest handleProbe in a ref so the debounced effect can call it // without depending on its identity (which changes every render). const handleProbeRef = useRef(handleProbe); handleProbeRef.current = handleProbe; // Auto-probe whenever the URL changes (debounced) while we're on the // remote transport and not already probing/probed. useEffect(() => { if (transport !== "remote") return; if (state.step !== "url") return; const trimmed = state.url.trim(); if (!trimmed) return; const handle = setTimeout(() => { handleProbeRef.current(); }, 400); return () => clearTimeout(handle); }, [transport, state.step, state.url]); const oauthCleanup = useRef<(() => void) | null>(null); const handleOAuth = useCallback(async () => { oauthCleanup.current?.(); oauthCleanup.current = null; dispatch({ type: "oauth-start" }); try { const redirectUrl = `${window.location.origin}/api/mcp/oauth/callback`; const result = await doStartOAuth({ path: { scopeId }, payload: { endpoint: state.url.trim(), redirectUrl }, }); dispatch({ type: "oauth-waiting", sessionId: result.sessionId }); oauthCleanup.current = openOAuthPopup( result.authorizationUrl, (data) => { oauthCleanup.current = null; if (data.ok) { dispatch({ type: "oauth-ok", tokens: { accessTokenSecretId: data.accessTokenSecretId, refreshTokenSecretId: data.refreshTokenSecretId, tokenType: data.tokenType, expiresAt: data.expiresAt, scope: data.scope, }, }); } else { dispatch({ type: "oauth-fail", error: data.error }); } }, () => { oauthCleanup.current = null; dispatch({ type: "oauth-fail", error: "OAuth popup was blocked" }); }, ); } catch (e) { dispatch({ type: "oauth-fail", error: e instanceof Error ? e.message : "Failed to start OAuth", }); } }, [state.url, scopeId, doStartOAuth]); const handleCancelOAuth = useCallback(() => { oauthCleanup.current?.(); oauthCleanup.current = null; dispatch({ type: "oauth-cancelled" }); }, []); const handleAddRemote = useCallback(async () => { if (!probe) return; dispatch({ type: "add-start" }); const headerAuth = remoteAuthHeaders[0]; const auth = remoteAuthMode === "header" && headerAuth?.secretId ? { kind: "header" as const, headerName: headerAuth.name.trim(), secretId: headerAuth.secretId, ...(headerAuth.prefix ? { prefix: headerAuth.prefix } : {}), } : remoteAuthMode === "oauth2" && tokens ? { kind: "oauth2" as const, accessTokenSecretId: tokens.accessTokenSecretId, refreshTokenSecretId: tokens.refreshTokenSecretId, tokenType: tokens.tokenType, expiresAt: tokens.expiresAt, scope: tokens.scope, } : { kind: "none" as const }; const headers = Object.fromEntries( remoteHeaders .map((header) => [header.name.trim(), header.value.trim()] as const) .filter(([name, value]) => name && value), ); const displayName = remoteIdentity.name.trim() || probe.serverName || probe.name; const slugNamespace = slugifyNamespace(remoteIdentity.namespace); const placeholderId = slugNamespace || `pending:${crypto.randomUUID()}`; const placeholder = beginAdd({ id: placeholderId, name: displayName, kind: "mcp", url: state.url.trim(), }); try { await doAdd({ path: { scopeId }, payload: { transport: "remote" as const, name: displayName, namespace: slugNamespace || undefined, endpoint: state.url.trim(), auth, ...(Object.keys(headers).length > 0 ? { headers } : {}), }, reactivityKeys: sourceWriteKeys, }); props.onComplete(); } catch (e) { dispatch({ type: "add-fail", error: e instanceof Error ? e.message : "Failed to add source", }); } finally { placeholder.done(); } }, [ probe, remoteAuthMode, remoteAuthHeaders, remoteHeaders, remoteIdentity, tokens, state.url, doAdd, props, scopeId, beginAdd, ]); // ---- Stdio actions ---- const parseStdioArgs = (raw: string): string[] => { if (!raw.trim()) return []; const args: string[] = []; const regex = /[^\s"]+|"([^"]*)"/g; let match; while ((match = regex.exec(raw)) !== null) { args.push(match[1] ?? match[0]); } return args; }; const parseStdioEnv = (raw: string): Record | undefined => { if (!raw.trim()) return undefined; const env: Record = {}; for (const line of raw.split("\n")) { const eq = line.indexOf("="); if (eq > 0) { env[line.slice(0, eq).trim()] = line.slice(eq + 1).trim(); } } return Object.keys(env).length > 0 ? env : undefined; }; const handleAddStdio = useCallback(async () => { const cmd = stdioCommand.trim(); if (!cmd) return; setStdioAdding(true); setStdioError(null); const displayName = stdioIdentity.name.trim() || cmd; const slugNamespace = slugifyNamespace(stdioIdentity.namespace); const placeholderId = slugNamespace || `pending:${crypto.randomUUID()}`; const placeholder = beginAdd({ id: placeholderId, name: displayName, kind: "mcp", }); try { await doAdd({ path: { scopeId }, payload: { transport: "stdio" as const, name: displayName, namespace: slugNamespace || undefined, command: cmd, args: parseStdioArgs(stdioArgs), env: parseStdioEnv(stdioEnv), }, reactivityKeys: sourceWriteKeys, }); props.onComplete(); } catch (e) { setStdioError(e instanceof Error ? e.message : "Failed to add source"); setStdioAdding(false); } finally { placeholder.done(); } }, [stdioCommand, stdioArgs, stdioEnv, stdioIdentity, doAdd, scopeId, props, beginAdd]); // ---- Render ---- return (

Add MCP Source

Connect to an MCP server to discover and use its tools.

{/* Transport toggle — only shown when stdio is enabled server-side */} {allowStdio && (
)} {transport === "remote" ? ( <> {/* Server info card (shown above URL input after probing) */} {probe ? ( {probe.serverName ?? probe.name} {probe.connected ? `${probe.toolCount} tool${probe.toolCount !== 1 ? "s" : ""} available` : "OAuth required to discover tools"} {probe.connected ? ( Connected ) : ( OAuth required )} ) : isProbing ? ( ) : null} {/* URL input */}
dispatch({ type: "set-url", url: (e.target as HTMLInputElement).value, }) } placeholder="https://mcp.example.com" className="w-full pr-9 font-mono text-sm" aria-invalid={probeError ? true : undefined} /> {isProbing && (
)}
{probeError && {probeError}}
{probe && ( )} {/* Authentication */} {probe && (
Authentication tabs={ probe.requiresOAuth ? [ { value: "header", label: "Header" }, { value: "oauth2", label: "OAuth" }, ] : [ { value: "none", label: "None" }, { value: "header", label: "Header" }, ] } value={remoteAuthMode} onChange={setRemoteAuthMode} />
{remoteAuthMode === "header" && ( )} {remoteAuthMode === "oauth2" && ( <> {!tokens && state.step === "probed" && ( )} {!tokens && state.step === "oauth-starting" && (
Starting authorization…
)} {!tokens && state.step === "oauth-waiting" && (
Waiting for authorization in popup…
)} {tokens && (
Authenticated
)} )}
)} {/* Additional headers */} {probe && (

Plaintext headers sent with every request. Use authentication for secret-backed auth headers.

{remoteHeaders.length === 0 ? ( No headers} onClick={() => setRemoteHeaders((headers) => [...headers, { name: "", value: "" }]) } /> ) : ( <> {remoteHeaders.map((header, index) => (
setRemoteHeaders((headers) => headers.map((current, headerIndex) => headerIndex === index ? { ...current, name: (event.target as HTMLInputElement).value, } : current, ), ) } placeholder="X-Organization-Id" className="h-8 text-xs font-mono" />
setRemoteHeaders((headers) => headers.map((current, headerIndex) => headerIndex === index ? { ...current, value: (event.target as HTMLInputElement).value, } : current, ), ) } placeholder="workspace-id" className="h-8 text-xs font-mono" />
))} setRemoteHeaders((headers) => [...headers, { name: "", value: "" }]) } /> )}
)} {/* Error (OAuth / add source). Probe errors show inline on the field. */} {otherError && (

{otherError}

)} {(probe || isProbing) && ( )} ) : ( <> {/* Stdio form */} setStdioCommand((e.target as HTMLInputElement).value)} placeholder="npx" className="font-mono text-sm" /> setStdioArgs((e.target as HTMLInputElement).value)} placeholder="-y chrome-devtools-mcp@latest" className="font-mono text-sm" />