import { useReducer, useCallback, useEffect, useRef, useState } from "react"; import { useAtomSet } from "@effect-atom/atom-react"; import { useScope } from "@executor/react"; import { Button } from "@executor/ui/components/button"; import { Input } from "@executor/ui/components/input"; import { Label } from "@executor/ui/components/label"; import { Badge } from "@executor/ui/components/badge"; import { Spinner } from "@executor/ui/components/spinner"; 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 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 }; function openOAuthPopup( url: string, onResult: (data: OAuthPopupResult) => void, onClosed?: () => void, ): void { const w = 600, h = 700; const left = window.screenX + (window.outerWidth - w) / 2; const top = window.screenY + (window.outerHeight - h) / 2; const popup = window.open(url, "mcp-oauth", `width=${w},height=${h},left=${left},top=${top},popup=1`); let settled = false; const settle = () => { settled = true; window.removeEventListener("message", onMsg); }; const onMsg = (e: MessageEvent) => { if (e.origin === window.location.origin && e.data?.type === "executor:oauth-result" && !settled) { settle(); onResult(e.data as OAuthPopupResult); } }; window.addEventListener("message", onMsg); if (popup) { const iv = setInterval(() => { if (popup.closed) { clearInterval(iv); if (!settled) { settle(); onClosed?.(); } } }, 500); } } // --------------------------------------------------------------------------- // Component // --------------------------------------------------------------------------- export default function AddMcpSource(props: { onComplete: () => void; onCancel: () => void; initialUrl?: string; initialPreset?: string; }) { const preset = findPreset(props.initialPreset); const isStdioPreset = preset?.transport === "stdio"; const [transport, setTransport] = useState<"remote" | "stdio">( isStdioPreset ? "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 [stdioName, setStdioName] = useState( isStdioPreset ? preset.name : "", ); 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 probe = "probe" in state ? state.probe : null; const tokens = "tokens" in state ? state.tokens : null; const isIdle = state.step === "url"; const isProbing = state.step === "probing"; const isAdding = state.step === "adding"; const isOAuthBusy = state.step === "oauth-starting" || state.step === "oauth-waiting"; const needsOAuth = probe?.requiresOAuth === true && !tokens; const canAdd = probe && !needsOAuth && !isAdding && !isOAuthBusy; const error = state.step === "error" ? 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() }, }); 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]); const autoProbed = useRef(false); useEffect(() => { if (transport === "remote" && remoteUrl && !autoProbed.current) { autoProbed.current = true; handleProbe(); } }, []); // eslint-disable-line react-hooks/exhaustive-deps const handleOAuth = useCallback(async () => { dispatch({ type: "oauth-start" }); try { const redirectUrl = `${window.location.origin}/v1/mcp/oauth/callback`; const result = await doStartOAuth({ path: { scopeId }, payload: { endpoint: state.url.trim(), redirectUrl }, }); dispatch({ type: "oauth-waiting", sessionId: result.sessionId }); openOAuthPopup( result.authorizationUrl, (data) => { 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 }); } }, () => dispatch({ type: "oauth-cancelled" }), ); } catch (e) { dispatch({ type: "oauth-fail", error: e instanceof Error ? e.message : "Failed to start OAuth" }); } }, [state.url, doStartOAuth]); const handleAddRemote = useCallback(async () => { if (!probe) return; dispatch({ type: "add-start" }); try { await doAdd({ path: { scopeId }, payload: { transport: "remote" as const, name: probe.serverName ?? probe.name, endpoint: state.url.trim(), auth: tokens ? { kind: "oauth2" as const, accessTokenSecretId: tokens.accessTokenSecretId, refreshTokenSecretId: tokens.refreshTokenSecretId, tokenType: tokens.tokenType, expiresAt: tokens.expiresAt, scope: tokens.scope, } : { kind: "none" as const }, }, }); props.onComplete(); } catch (e) { dispatch({ type: "add-fail", error: e instanceof Error ? e.message : "Failed to add source" }); } }, [probe, tokens, state.url, doAdd, props]); // ---- 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); try { await doAdd({ path: { scopeId }, payload: { transport: "stdio" as const, name: stdioName.trim() || cmd, command: cmd, args: parseStdioArgs(stdioArgs), env: parseStdioEnv(stdioEnv), }, }); props.onComplete(); } catch (e) { setStdioError(e instanceof Error ? e.message : "Failed to add source"); setStdioAdding(false); } }, [stdioCommand, stdioArgs, stdioEnv, stdioName, doAdd, scopeId, props]); // ---- Render ---- return (

Add MCP Source

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

{/* Transport toggle */}
{transport === "remote" ? ( <> {/* URL input */}
dispatch({ type: "set-url", url: (e.target as HTMLInputElement).value })} placeholder="https://mcp.example.com" className="flex-1 font-mono text-sm" onKeyDown={(e) => { if (e.key === "Enter" && state.url.trim() && isIdle) handleProbe(); }} disabled={isProbing} /> {!probe && ( )}

Supports Streamable HTTP and SSE transports.

{/* Server info card */} {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 )}
)} {/* OAuth section */} {probe?.requiresOAuth && !tokens && (
{state.step === "probed" && ( )} {state.step === "oauth-starting" && (
Starting authorization…
)} {state.step === "oauth-waiting" && (
Waiting for authorization in popup…
)}
)} {/* OAuth success */} {tokens && (
Authenticated
)} {/* Error */} {error && (

{error}

)} {/* Actions */} {(probe || isProbing) && (
)} {/* Cancel when nothing probed yet */} {!probe && !isProbing && (
)} ) : ( <> {/* Stdio form */}
setStdioCommand((e.target as HTMLInputElement).value)} placeholder="npx" className="font-mono text-sm" />

The executable to run (e.g. npx, uvx, node).

setStdioArgs((e.target as HTMLInputElement).value)} placeholder="-y chrome-devtools-mcp@latest" className="font-mono text-sm" />

Space-separated arguments passed to the command.

setStdioName((e.target as HTMLInputElement).value)} placeholder="My MCP Server" className="text-sm" />