The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Chore: enhance MCP authentication flow with automatic resume and connection status updates (#701)
harshil-2096a122ba144f4c
diff --git a/.changeset/mcp-auth-verify-connector.md b/.changeset/mcp-auth-verify-connector.mdnew file mode 100644index 000000000..49733eea9--- /dev/null+++ b/.changeset/mcp-auth-verify-connector.md@@ -0,0 +1,5 @@+---+'@truefoundry/trueforge-ui': patch+---++Show successful MCP authentication in chat, automatically continue after every required server connects, and indicate while the turn is starting. Confirm OAuth against the chat MCP connector read (`getMcpConnector`) so non-admins are not blocked by settings-only catalog GETs, and ignore authorize callbacks after the prompt unmounts.diff --git a/packages/trueforge-ui/src/atoms/adapters/McpAuthPromptAdapter.tsx b/packages/trueforge-ui/src/atoms/adapters/McpAuthPromptAdapter.tsxindex 4aa17192e..6b4e799a1 100644--- a/packages/trueforge-ui/src/atoms/adapters/McpAuthPromptAdapter.tsx+++ b/packages/trueforge-ui/src/atoms/adapters/McpAuthPromptAdapter.tsx@@ -9,6 +9,8 @@ export type McpServer = {export type McpAuthPromptProps = {servers: McpServer[];+ connectedServerIds?: ReadonlySet<string>;+ continueLoading?: boolean;onConnect: (serverId: string) => void;onContinue?: () => void;readOnly?: boolean;@@ -21,6 +23,8 @@ const DEFAULT_TITLE = 'MCP Authentication Required';export function McpAuthPrompt({servers,+ connectedServerIds,+ continueLoading = false,onConnect,onContinue,readOnly = false,@@ -46,15 +50,28 @@ export function McpAuthPrompt({<span className="shrink-0 text-xs font-semibold text-text-secondary">:</span><span className="truncate font-sans font-medium text-text-primary">{server.name}</span></div>- <Button.Primary size="small" disabled={readOnly} onClick={() => onConnect(server.id)} className="shrink-0">- Connect- <Icon name="external-link" size="0.75em" className="ml-1" />- </Button.Primary>+ {connectedServerIds?.has(server.id) ? (+ <span className="inline-flex shrink-0 items-center gap-1 text-xs text-success-bg">+ <Icon name="check" size="0.875rem" />+ Connected+ </span>+ ) : (+ <Button.Primary+ size="small"+ disabled={readOnly}+ onClick={() => onConnect(server.id)}+ className="shrink-0"+ >+ Connect+ <Icon name="external-link" size="0.75em" className="ml-1" />+ </Button.Primary>+ )}</div>))}{onContinue && (<div className="flex justify-end border-t border-border pt-2">- <Button.Primary size="small" disabled={readOnly} onClick={onContinue}>+ <Button.Primary size="small" disabled={readOnly || continueLoading} onClick={onContinue}>+ {continueLoading ? <Icon name="loader" className="animate-spin" /> : null}Continue</Button.Primary></div>diff --git a/packages/trueforge-ui/src/containers/McpAuthContainer.tsx b/packages/trueforge-ui/src/containers/McpAuthContainer.tsxindex 0ea6bc7c6..f741f9f9f 100644--- a/packages/trueforge-ui/src/containers/McpAuthContainer.tsx+++ b/packages/trueforge-ui/src/containers/McpAuthContainer.tsx@@ -2,6 +2,7 @@import { useThreadIsRunning } from '@assistant-ui/core/react';import { useTrueFoundryMcpAuth } from '@truefoundry/assistant-ui-runtime';+import { useEffect, useRef, useState } from 'react';import { useDraftCatalog } from '@/atoms/draft/DraftCatalogProvider.js';import { useMCPAuth } from '@/hooks/useMcpAuth.js';@@ -10,7 +11,7 @@ import { useSlot } from '../theme/SlotsProvider.js';type McpAuthPromptProps = {servers: NonNullable<ReturnType<typeof useTrueFoundryMcpAuth>['pending']>['mcpServers'];- onContinue: () => void;+ onContinue: () => Promise<void>;readOnly: boolean;};@@ -18,16 +19,51 @@ function CatalogMcpAuthPrompt({ servers, onContinue, readOnly }: McpAuthPromptPrconst McpAuthPrompt = useSlot('McpAuthPrompt');const { handleAuthorize } = useMCPAuth();const { refreshConnectors } = useDraftCatalog();+ const [connectedServerIds, setConnectedServerIds] = useState<ReadonlySet<string>>(() => new Set());+ const connectedServerIdsRef = useRef(connectedServerIds);+ const [isResuming, setIsResuming] = useState(false);+ const resumedRef = useRef(false);+ const promptGenerationRef = useRef(0);++ useEffect(+ () => () => {+ promptGenerationRef.current += 1;+ },+ [],+ );++ const startResume = () => {+ if (readOnly || resumedRef.current) return;+ resumedRef.current = true;+ setIsResuming(true);+ void onContinue().catch(() => {+ resumedRef.current = false;+ setIsResuming(false);+ });+ };const handleConnect = (serverId: string) => {+ const generation = promptGenerationRef.current;void handleAuthorize(serverId, isSuccess => {- if (isSuccess) {- void refreshConnectors();- }+ if (generation !== promptGenerationRef.current || !isSuccess) return;+ const nextConnectedServerIds = new Set([...connectedServerIdsRef.current, serverId]);+ connectedServerIdsRef.current = nextConnectedServerIds;+ setConnectedServerIds(nextConnectedServerIds);+ void refreshConnectors();+ if (servers.every(server => nextConnectedServerIds.has(server.id))) startResume();});};- return <McpAuthPrompt servers={servers} onConnect={handleConnect} onContinue={onContinue} readOnly={readOnly} />;+ return (+ <McpAuthPrompt+ servers={servers}+ connectedServerIds={connectedServerIds}+ continueLoading={isResuming}+ onConnect={handleConnect}+ onContinue={startResume}+ readOnly={readOnly}+ />+ );}export function McpAuthContainer({ disabled = false }: { disabled?: boolean }) {@@ -39,12 +75,12 @@ export function McpAuthContainer({ disabled = false }: { disabled?: boolean }) {if (!pending) return null;if (catalog) {+ const pendingServerKey = JSON.stringify(pending.mcpServers.map(server => server.id));return (<CatalogMcpAuthPrompt+ key={pendingServerKey}servers={pending.mcpServers}- onContinue={() => {- if (!disabled) void resume();- }}+ onContinue={resume}readOnly={isRunning || disabled}/>);diff --git a/packages/trueforge-ui/src/hooks/useMcpAuth.ts b/packages/trueforge-ui/src/hooks/useMcpAuth.tsindex 41315940a..a7d52c735 100644--- a/packages/trueforge-ui/src/hooks/useMcpAuth.ts+++ b/packages/trueforge-ui/src/hooks/useMcpAuth.ts@@ -1,7 +1,7 @@-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';import { useToasterOptional } from '../containers/ToasterContainer.js';-import { useCatalogServer } from '../server/ServerContext.js';+import { useCatalogServer, useOptionalServer } from '../server/ServerContext.js';export const MCP_AUTH_POPUP_CHANNEL = 'truefoundry-mcp-auth-popup';@@ -24,58 +24,127 @@ const isPopupMessage = (value: unknown): value is McpAuthPopupMessage => {return typeof message.popupUid === 'string' && typeof message.isSuccess === 'boolean';};+/**+ * Browser side of the MCP OAuth handshake:+ * 1. `authenticateConnector` either reports the connector already authenticated or returns an authorization URL.+ * 2. That URL opens in a popup; the callback page broadcasts its result on `MCP_AUTH_POPUP_CHANNEL`, matched by `popupUid`.+ * 3. Success is re-read from the connector before `callback(true)` — the popup only proves the redirect ran, not that+ * tokens were stored.+ *+ * Each attempt has its own popup ID and listener, so multiple servers can be authorized independently.+ */export const useMCPAuth = ({ callbackPath }: UseMCPAuthOptions = {}) => {const { connectorCatalog } = useCatalogServer();+ const server = useOptionalServer();const toaster = useToasterOptional();- const [isOAuthLoading, setIsOAuthLoading] = useState(false);- const popupUid = useMemo(() => generatePopupUid(), []);- const listenerCleanupRef = useRef<(() => void) | null>(null);-- const clearPopupListener = useCallback(() => {- listenerCleanupRef.current?.();- listenerCleanupRef.current = null;+ const [loadingCount, setLoadingCount] = useState(0);+ const activeAttemptsRef = useRef(new Set<object>());+ const popupCleanupRef = useRef(new Set<() => void>());++ useEffect(() => {+ const activeAttempts = activeAttemptsRef.current;+ const popupCleanups = popupCleanupRef.current;+ return () => {+ activeAttempts.clear();+ for (const cleanup of popupCleanups) cleanup();+ popupCleanups.clear();+ };}, []);- useEffect(() => clearPopupListener, [clearPopupListener]);+ // Check the user's MCP authentication status with `getMcpConnector`; `getConnector` is only available to admins.+ const loadConnector = useCallback(+ async (integrationId: string) => {+ if (server?.getMcpConnector !== undefined) {+ return server.getMcpConnector({ connectorId: integrationId });+ }+ return connectorCatalog.getConnector({ id: integrationId });+ },+ [connectorCatalog, server],+ );- const openAuthPopup = useCallback(- (authorizationEndpoint: string, callback: McpAuthCallback) => {- clearPopupListener();+ const reportVerifiedSuccess = useCallback(+ async ({+ integrationId,+ callback,+ attempt,+ }: {+ integrationId: string;+ callback: McpAuthCallback;+ attempt: object;+ }) => {+ try {+ const connector = await loadConnector(integrationId);+ if (!activeAttemptsRef.current.has(attempt)) return;+ if (!connector.authenticated) {+ throw new Error('The MCP server is not authenticated yet. Please try again.');+ }+ callback(true);+ } catch (error: unknown) {+ if (!activeAttemptsRef.current.has(attempt)) return;+ toaster?.showError(error);+ callback(false);+ }+ },+ [loadConnector, toaster],+ );+ const openAuthPopup = useCallback(+ ({+ authorizationEndpoint,+ integrationId,+ callback,+ attempt,+ popupUid,+ }: {+ authorizationEndpoint: string;+ integrationId: string;+ callback: McpAuthCallback;+ attempt: object;+ popupUid: string;+ }) => {const channel = new BroadcastChannel(MCP_AUTH_POPUP_CHANNEL);let popup: Window | null = null;const cleanup = () => {channel.close();popup?.close();+ popupCleanupRef.current.delete(cleanup);};channel.onmessage = (event: MessageEvent<unknown>) => {if (!isPopupMessage(event.data) || event.data.popupUid !== popupUid) return;- try {- callback(event.data.isSuccess);- } finally {- clearPopupListener();+ const { isSuccess } = event.data;+ cleanup();+ if (!isSuccess) {+ if (activeAttemptsRef.current.delete(attempt)) callback(false);+ return;}+ void reportVerifiedSuccess({ integrationId, callback, attempt }).finally(() => {+ activeAttemptsRef.current.delete(attempt);+ });};- listenerCleanupRef.current = cleanup;+ popupCleanupRef.current.add(cleanup);popup = window.open(authorizationEndpoint, '_blank', 'popup=true');if (!popup) {- clearPopupListener();+ cleanup();throw new Error('Popup blocked. Please allow pop-ups to authorize the MCP server.');}popup.focus();},- [clearPopupListener, popupUid],+ [reportVerifiedSuccess],);const handleAuthorize = useCallback(async (integrationId: string, callback: McpAuthCallback) => {if (!integrationId) return;+ const attempt = {};+ const popupUid = generatePopupUid();+ activeAttemptsRef.current.add(attempt);+ setLoadingCount(count => count + 1);+ let popupOpened = false;try {- setIsOAuthLoading(true);const callbackUrl = callbackPath? new URL(callbackPath, window.location.origin): new URL(window.location.href);@@ -87,12 +156,13 @@ export const useMCPAuth = ({ callbackPath }: UseMCPAuthOptions = {}) => {id: integrationId,returnTo: `${callbackUrl.pathname}${callbackUrl.search}`,});+ if (!activeAttemptsRef.current.has(attempt)) return;if (('status' in result && result.status?.toUpperCase() === 'AUTHENTICATED') ||('authenticated' in result && result.authenticated)) {- callback(true);+ await reportVerifiedSuccess({ integrationId, callback, attempt });return;}@@ -101,19 +171,22 @@ export const useMCPAuth = ({ callbackPath }: UseMCPAuthOptions = {}) => {throw new Error('The MCP server did not return an authorization URL.');}- openAuthPopup(authorizationEndpoint, callback);+ openAuthPopup({ authorizationEndpoint, integrationId, callback, attempt, popupUid });+ popupOpened = true;} catch (error: unknown) {+ if (!activeAttemptsRef.current.has(attempt)) return;toaster?.showError(error);callback(false);} finally {- setIsOAuthLoading(false);+ if (activeAttemptsRef.current.has(attempt)) setLoadingCount(count => count - 1);+ if (!popupOpened) activeAttemptsRef.current.delete(attempt);}},- [callbackPath, connectorCatalog, openAuthPopup, popupUid, toaster],+ [callbackPath, connectorCatalog, openAuthPopup, reportVerifiedSuccess, toaster],);return {handleAuthorize,- isOAuthLoading,+ isOAuthLoading: loadingCount > 0,};};diff --git a/packages/trueforge-ui/test/containers/McpAuthContainer.test.tsx b/packages/trueforge-ui/test/containers/McpAuthContainer.test.tsxindex 5a1cf5ec1..84df0dac5 100644--- a/packages/trueforge-ui/test/containers/McpAuthContainer.test.tsx+++ b/packages/trueforge-ui/test/containers/McpAuthContainer.test.tsx@@ -1,25 +1,30 @@// @vitest-environment jsdomimport { AssistantRuntimeProvider, useExternalStoreRuntime, type ThreadMessageLike } from '@assistant-ui/react';-import { fireEvent, render, screen } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { trueFoundryExtras, type TrueFoundryRuntimeExtras } from '@truefoundry/assistant-ui-runtime';import { describe, expect, it, vi } from 'vitest';+import { DraftCatalogProvider } from '@/atoms/draft/DraftCatalogProvider.js';import { McpAuthContainer } from '@/containers/McpAuthContainer.js';+import { ServerProvider } from '@/server/ServerContext.js';+import type { AgentUIServer } from '@/server/types.js';+import { createMockAgentUIServer, createMockCatalog } from '../server/mockServer.js';-const SERVERS = [- { id: 'srv-1', name: 'github', authUrl: 'https://example.com/auth/github' },- { id: 'srv-2', name: 'slack', authUrl: 'https://example.com/auth/slack' },-];+const GITHUB_SERVER = { id: 'srv-1', name: 'github', authUrl: 'https://example.com/auth/github' };+const SLACK_SERVER = { id: 'srv-2', name: 'slack', authUrl: 'https://example.com/auth/slack' };+const SERVERS = [GITHUB_SERVER, SLACK_SERVER];const PENDING = { mcpServers: SERVERS };function McpAuthHarness({pendingMcpAuth,resumeMcpAuth,isRunning = false,+ server,}: {pendingMcpAuth: TrueFoundryRuntimeExtras['pendingMcpAuth'];resumeMcpAuth: TrueFoundryRuntimeExtras['resumeMcpAuth'];isRunning?: boolean;+ server?: AgentUIServer;}) {const messages: ThreadMessageLike[] = [];const runtime = useExternalStoreRuntime({@@ -47,11 +52,19 @@ function McpAuthHarness({}),});- return (+ const content = (<AssistantRuntimeProvider runtime={runtime}><McpAuthContainer /></AssistantRuntimeProvider>);++ return server ? (+ <ServerProvider server={server}>+ <DraftCatalogProvider>{content}</DraftCatalogProvider>+ </ServerProvider>+ ) : (+ content+ );}describe('McpAuthContainer', () => {@@ -93,4 +106,205 @@ describe('McpAuthContainer', () => {render(<McpAuthHarness pendingMcpAuth={PENDING} resumeMcpAuth={vi.fn()} isRunning={true} />);expect(screen.getByRole('button', { name: /continue/i })).toBeDisabled();});++ it('shows each successful catalog connection and resumes once all servers are connected', async () => {+ const resumeMcpAuth = vi.fn().mockResolvedValue(undefined);+ const authenticateConnector = vi.fn().mockResolvedValue({ status: 'AUTHENTICATED' });+ const getConnector = vi.fn(async ({ id }: { id: string }) => ({+ id,+ name: id,+ description: '',+ url: 'https://example.test/mcp',+ auth: { type: 'dcr' as const },+ requiresAuth: false,+ authenticated: true,+ }));+ const catalog = createMockCatalog({+ connectorCatalog: {+ ...createMockCatalog().connectorCatalog,+ authenticateConnector,+ getConnector,+ },+ });+ const server = createMockAgentUIServer({ catalog });++ render(<McpAuthHarness pendingMcpAuth={PENDING} resumeMcpAuth={resumeMcpAuth} server={server} />);++ const firstConnect = screen.getAllByRole('button', { name: 'Connect' })[0];+ if (!firstConnect) throw new Error('Expected the first MCP Connect button');+ fireEvent.click(firstConnect);++ await waitFor(() => expect(screen.getByText('Connected')).toBeInTheDocument());+ expect(getConnector).toHaveBeenCalled();+ expect(resumeMcpAuth).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));++ await waitFor(() => expect(screen.getAllByText('Connected')).toHaveLength(2));+ await waitFor(() => expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled());+ expect(resumeMcpAuth).toHaveBeenCalledTimes(1);+ });++ it('keeps a failed catalog connection available without resuming', async () => {+ const resumeMcpAuth = vi.fn().mockResolvedValue(undefined);+ const authenticateConnector = vi.fn().mockRejectedValue(new Error('Authorization failed'));+ const catalog = createMockCatalog({+ connectorCatalog: {+ ...createMockCatalog().connectorCatalog,+ authenticateConnector,+ },+ });+ const server = createMockAgentUIServer({ catalog });++ render(<McpAuthHarness pendingMcpAuth={PENDING} resumeMcpAuth={resumeMcpAuth} server={server} />);++ const firstConnect = screen.getAllByRole('button', { name: 'Connect' })[0];+ if (!firstConnect) throw new Error('Expected the first MCP Connect button');+ fireEvent.click(firstConnect);++ await waitFor(() => expect(authenticateConnector).toHaveBeenCalledTimes(1));+ expect(screen.getAllByRole('button', { name: 'Connect' })).toHaveLength(2);+ expect(resumeMcpAuth).not.toHaveBeenCalled();+ });++ it('does not mark a server connected when AUTHENTICATED is not confirmed', async () => {+ const resumeMcpAuth = vi.fn().mockResolvedValue(undefined);+ const authenticateConnector = vi.fn().mockResolvedValue({ status: 'AUTHENTICATED' });+ const getConnector = vi.fn(async ({ id }: { id: string }) => ({+ id,+ name: id,+ description: '',+ url: 'https://example.test/mcp',+ auth: { type: 'dcr' as const },+ requiresAuth: true,+ authenticated: false,+ }));+ const catalog = createMockCatalog({+ connectorCatalog: {+ ...createMockCatalog().connectorCatalog,+ authenticateConnector,+ getConnector,+ },+ });+ const server = createMockAgentUIServer({ catalog });++ render(+ <McpAuthHarness pendingMcpAuth={{ mcpServers: [GITHUB_SERVER] }} resumeMcpAuth={resumeMcpAuth} server={server} />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));++ await waitFor(() => expect(getConnector).toHaveBeenCalledWith({ id: GITHUB_SERVER.id }));+ expect(screen.getByRole('button', { name: 'Connect' })).toBeInTheDocument();+ expect(screen.queryByText('Connected')).not.toBeInTheDocument();+ expect(resumeMcpAuth).not.toHaveBeenCalled();+ });++ it('allows retrying Continue when resume fails', async () => {+ const resumeMcpAuth = vi.fn().mockRejectedValue(new Error('Resume failed'));+ const authenticateConnector = vi.fn().mockResolvedValue({ status: 'AUTHENTICATED' });+ const getConnector = vi.fn(async ({ id }: { id: string }) => ({+ id,+ name: id,+ description: '',+ url: 'https://example.test/mcp',+ auth: { type: 'dcr' as const },+ requiresAuth: false,+ authenticated: true,+ }));+ const catalog = createMockCatalog({+ connectorCatalog: {+ ...createMockCatalog().connectorCatalog,+ authenticateConnector,+ getConnector,+ },+ });+ const server = createMockAgentUIServer({ catalog });++ render(+ <McpAuthHarness pendingMcpAuth={{ mcpServers: [GITHUB_SERVER] }} resumeMcpAuth={resumeMcpAuth} server={server} />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));++ await waitFor(() => expect(resumeMcpAuth).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled());++ fireEvent.click(screen.getByRole('button', { name: 'Continue' }));+ await waitFor(() => expect(resumeMcpAuth).toHaveBeenCalledTimes(2));+ });++ it('confirms chat MCP auth through getMcpConnector when settings getConnector is forbidden', async () => {+ const resumeMcpAuth = vi.fn().mockResolvedValue(undefined);+ const authenticateConnector = vi.fn().mockResolvedValue({ status: 'AUTHENTICATED' });+ const getConnector = vi.fn(async () => {+ throw new Error('Forbidden');+ });+ const getMcpConnector = vi.fn(async ({ connectorId }: { connectorId: string }) => ({+ id: connectorId,+ name: connectorId,+ authenticated: true,+ }));+ const catalog = createMockCatalog({+ connectorCatalog: {+ ...createMockCatalog().connectorCatalog,+ authenticateConnector,+ getConnector,+ },+ });+ const server = createMockAgentUIServer({ catalog, getMcpConnector });++ render(+ <McpAuthHarness pendingMcpAuth={{ mcpServers: [GITHUB_SERVER] }} resumeMcpAuth={resumeMcpAuth} server={server} />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));++ await waitFor(() => expect(getMcpConnector).toHaveBeenCalledWith({ connectorId: GITHUB_SERVER.id }));+ await waitFor(() => expect(screen.getByText('Connected')).toBeInTheDocument());+ expect(getConnector).not.toHaveBeenCalled();+ expect(resumeMcpAuth).toHaveBeenCalledTimes(1);+ });++ it('does not resume a paused turn after the prompt unmounts mid-authorize', async () => {+ const resumeMcpAuth = vi.fn().mockResolvedValue(undefined);+ let resolveAuth: ((value: { status: string }) => void) | undefined;+ const authenticateConnector = vi.fn(+ () =>+ new Promise<{ status: string }>(resolve => {+ resolveAuth = resolve;+ }),+ );+ const getConnector = vi.fn(async ({ id }: { id: string }) => ({+ id,+ name: id,+ description: '',+ url: 'https://example.test/mcp',+ auth: { type: 'dcr' as const },+ requiresAuth: false,+ authenticated: true,+ }));+ const catalog = createMockCatalog({+ connectorCatalog: {+ ...createMockCatalog().connectorCatalog,+ authenticateConnector,+ getConnector,+ },+ });+ const server = createMockAgentUIServer({ catalog });++ const { unmount } = render(+ <McpAuthHarness pendingMcpAuth={{ mcpServers: [GITHUB_SERVER] }} resumeMcpAuth={resumeMcpAuth} server={server} />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));+ await waitFor(() => expect(authenticateConnector).toHaveBeenCalledTimes(1));+ unmount();++ await act(async () => {+ resolveAuth?.({ status: 'AUTHENTICATED' });+ });++ expect(resumeMcpAuth).not.toHaveBeenCalled();+ });});diff --git a/packages/trueforge-ui/test/hooks/useMcpAuth.test.ts b/packages/trueforge-ui/test/hooks/useMcpAuth.test.tsindex 3d5ede323..cd1e89386 100644--- a/packages/trueforge-ui/test/hooks/useMcpAuth.test.ts+++ b/packages/trueforge-ui/test/hooks/useMcpAuth.test.ts@@ -1,11 +1,15 @@// @vitest-environment jsdom-import { act, cleanup, renderHook } from '@testing-library/react';+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { ConnectorCatalogServer } from '@/server/types.js';+import type { ConnectorBase, ConnectorCatalogServer } from '@/server/types.js';type CatalogHookValue = {- connectorCatalog: Pick<ConnectorCatalogServer, 'authenticateConnector'>;+ connectorCatalog: Pick<ConnectorCatalogServer, 'authenticateConnector' | 'getConnector'>;+};++type ServerHookValue = {+ getMcpConnector?: (req: { connectorId: string }) => Promise<ConnectorBase>;};type ToasterValue = {@@ -13,10 +17,12 @@ type ToasterValue = {};const useCatalogServer = vi.hoisted(() => vi.fn<() => CatalogHookValue>());+const useOptionalServer = vi.hoisted(() => vi.fn<() => ServerHookValue | null>());const useToasterOptional = vi.hoisted(() => vi.fn<() => ToasterValue | null>());vi.mock('@/server/ServerContext.js', () => ({useCatalogServer,+ useOptionalServer,}));vi.mock('@/containers/ToasterContainer.js', () => ({@@ -43,10 +49,32 @@ class BroadcastChannelStub {}const authenticateConnector = vi.fn<ConnectorCatalogServer['authenticateConnector']>();+const getConnector = vi.fn<ConnectorCatalogServer['getConnector']>();+const getMcpConnector = vi.fn<(req: { connectorId: string }) => Promise<ConnectorBase>>();const showError = vi.fn<(error: unknown) => void>();-function getPopupUid(): string {- const call = authenticateConnector.mock.calls.at(-1);+function authenticatedConnector(id: string): ConnectorBase {+ return {+ id,+ name: id,+ description: '',+ url: 'https://example.test/mcp',+ auth: { type: 'dcr' },+ requiresAuth: false,+ authenticated: true,+ };+}++function unauthenticatedConnector(id: string): ConnectorBase {+ return {+ ...authenticatedConnector(id),+ requiresAuth: true,+ authenticated: false,+ };+}++function getPopupUid(callIndex = -1): string {+ const call = authenticateConnector.mock.calls.at(callIndex);if (!call) throw new Error('Expected authenticateConnector to be called');const returnTo = call[0].returnTo;@@ -61,12 +89,16 @@ describe('useMCPAuth', () => {beforeEach(() => {channels.length = 0;authenticateConnector.mockReset();+ getConnector.mockReset();+ getMcpConnector.mockReset();showError.mockReset();useCatalogServer.mockReset();+ useOptionalServer.mockReset();useToasterOptional.mockReset();useCatalogServer.mockReturnValue({- connectorCatalog: { authenticateConnector },+ connectorCatalog: { authenticateConnector, getConnector },});+ useOptionalServer.mockReturnValue(null);useToasterOptional.mockReturnValue({ showError });vi.stubGlobal('BroadcastChannel', BroadcastChannelStub);window.history.replaceState({}, '', '/chat');@@ -80,6 +112,7 @@ describe('useMCPAuth', () => {it('completes immediately when the connector is already authenticated', async () => {authenticateConnector.mockResolvedValue({ status: 'AUTHENTICATED' });+ getConnector.mockResolvedValue(authenticatedConnector('connector-1'));const open = vi.spyOn(window, 'open');const callback = vi.fn();const { result } = renderHook(() => useMCPAuth());@@ -92,6 +125,7 @@ describe('useMCPAuth', () => {id: 'connector-1',returnTo: expect.stringMatching(/^\/chat\?/),});+ expect(getConnector).toHaveBeenCalledWith({ id: 'connector-1' });expect(callback).toHaveBeenCalledOnce();expect(callback).toHaveBeenCalledWith(true);expect(open).not.toHaveBeenCalled();@@ -100,10 +134,44 @@ describe('useMCPAuth', () => {expect(result.current.isOAuthLoading).toBe(false);});+ it('reports failure when AUTHENTICATED status is not confirmed by getConnector', async () => {+ authenticateConnector.mockResolvedValue({ status: 'AUTHENTICATED' });+ getConnector.mockResolvedValue(unauthenticatedConnector('connector-1'));+ const callback = vi.fn();+ const { result } = renderHook(() => useMCPAuth());++ await act(async () => {+ await result.current.handleAuthorize('connector-1', callback);+ });++ expect(getConnector).toHaveBeenCalledWith({ id: 'connector-1' });+ expect(callback).toHaveBeenCalledOnce();+ expect(callback).toHaveBeenCalledWith(false);+ expect(showError).toHaveBeenCalledOnce();+ expect(showError).toHaveBeenCalledWith(new Error('The MCP server is not authenticated yet. Please try again.'));+ });++ it('reports failure when post-auth getConnector throws', async () => {+ authenticateConnector.mockResolvedValue({ status: 'AUTHENTICATED' });+ getConnector.mockRejectedValue(new Error('Catalog unavailable'));+ const callback = vi.fn();+ const { result } = renderHook(() => useMCPAuth());++ await act(async () => {+ await result.current.handleAuthorize('connector-1', callback);+ });++ expect(callback).toHaveBeenCalledOnce();+ expect(callback).toHaveBeenCalledWith(false);+ expect(showError).toHaveBeenCalledOnce();+ expect(showError).toHaveBeenCalledWith(new Error('Catalog unavailable'));+ });+it('opens the authorization endpoint and accepts only its matching channel result', async () => {authenticateConnector.mockResolvedValue({authorization_endpoint: 'https://auth.example.test/authorize',});+ getConnector.mockResolvedValue(authenticatedConnector('connector-2'));const open = vi.spyOn(window, 'open').mockReturnValue(window);const focus = vi.spyOn(window, 'focus').mockImplementation(() => {});const close = vi.spyOn(window, 'close').mockImplementation(() => {});@@ -139,8 +207,11 @@ describe('useMCPAuth', () => {expect(channel.close).not.toHaveBeenCalled();expect(close).not.toHaveBeenCalled();- channel.emit({ popupUid: getPopupUid(), isSuccess: true });+ await act(async () => {+ channel.emit({ popupUid: getPopupUid(), isSuccess: true });+ });+ expect(getConnector).toHaveBeenCalledWith({ id: 'connector-2' });expect(callback).toHaveBeenCalledOnce();expect(callback).toHaveBeenCalledWith(true);expect(channel.close).toHaveBeenCalledOnce();@@ -148,6 +219,95 @@ describe('useMCPAuth', () => {expect(showError).not.toHaveBeenCalled();});+ it('does not report success when the popup succeeds but the connector is still unauthenticated', async () => {+ authenticateConnector.mockResolvedValue({+ authorization_endpoint: 'https://auth.example.test/authorize',+ });+ getConnector.mockResolvedValue(unauthenticatedConnector('connector-2'));+ vi.spyOn(window, 'open').mockReturnValue(window);+ vi.spyOn(window, 'focus').mockImplementation(() => {});+ vi.spyOn(window, 'close').mockImplementation(() => {});+ const callback = vi.fn();+ const { result } = renderHook(() => useMCPAuth());++ await act(async () => {+ await result.current.handleAuthorize('connector-2', callback);+ });++ const channel = channels[0];+ if (!channel) throw new Error('Expected an authorization channel');++ await act(async () => {+ channel.emit({ popupUid: getPopupUid(), isSuccess: true });+ });++ expect(getConnector).toHaveBeenCalledWith({ id: 'connector-2' });+ expect(callback).toHaveBeenCalledOnce();+ expect(callback).toHaveBeenCalledWith(false);+ expect(showError).toHaveBeenCalledOnce();+ });++ it('does not call getConnector when the popup reports failure', async () => {+ authenticateConnector.mockResolvedValue({+ authorization_endpoint: 'https://auth.example.test/authorize',+ });+ vi.spyOn(window, 'open').mockReturnValue(window);+ vi.spyOn(window, 'focus').mockImplementation(() => {});+ vi.spyOn(window, 'close').mockImplementation(() => {});+ const callback = vi.fn();+ const { result } = renderHook(() => useMCPAuth());++ await act(async () => {+ await result.current.handleAuthorize('connector-2', callback);+ });++ const channel = channels[0];+ if (!channel) throw new Error('Expected an authorization channel');++ await act(async () => {+ channel.emit({ popupUid: getPopupUid(), isSuccess: false });+ });++ expect(getConnector).not.toHaveBeenCalled();+ expect(callback).toHaveBeenCalledOnce();+ expect(callback).toHaveBeenCalledWith(false);+ expect(showError).not.toHaveBeenCalled();+ });++ it('keeps simultaneous server authorization attempts independent', async () => {+ authenticateConnector.mockResolvedValue({+ authorization_endpoint: 'https://auth.example.test/authorize',+ });+ getConnector.mockImplementation(async ({ id }) => authenticatedConnector(id));+ vi.spyOn(window, 'open').mockReturnValue(window);+ vi.spyOn(window, 'focus').mockImplementation(() => {});+ vi.spyOn(window, 'close').mockImplementation(() => {});+ const firstCallback = vi.fn();+ const secondCallback = vi.fn();+ const { result } = renderHook(() => useMCPAuth());++ await act(async () => {+ await Promise.all([+ result.current.handleAuthorize('connector-1', firstCallback),+ result.current.handleAuthorize('connector-2', secondCallback),+ ]);+ });++ expect(channels).toHaveLength(2);+ await act(async () => {+ channels[1]?.emit({ popupUid: getPopupUid(1), isSuccess: true });+ });+ expect(secondCallback).toHaveBeenCalledWith(true);+ expect(firstCallback).not.toHaveBeenCalled();++ await act(async () => {+ channels[0]?.emit({ popupUid: getPopupUid(0), isSuccess: true });+ });+ expect(firstCallback).toHaveBeenCalledWith(true);+ expect(getConnector).toHaveBeenCalledWith({ id: 'connector-1' });+ expect(getConnector).toHaveBeenCalledWith({ id: 'connector-2' });+ });+it('reports a blocked popup and completes authorization as failed', async () => {authenticateConnector.mockResolvedValue({authorization_endpoint: 'https://auth.example.test/authorize',@@ -162,6 +322,7 @@ describe('useMCPAuth', () => {expect(callback).toHaveBeenCalledOnce();expect(callback).toHaveBeenCalledWith(false);+ expect(getConnector).not.toHaveBeenCalled();expect(showError).toHaveBeenCalledOnce();expect(showError).toHaveBeenCalledWith(new Error('Popup blocked. Please allow pop-ups to authorize the MCP server.'),@@ -193,5 +354,49 @@ describe('useMCPAuth', () => {expect(channel.close).toHaveBeenCalledOnce();expect(close).toHaveBeenCalledOnce();expect(callback).not.toHaveBeenCalled();+ expect(getConnector).not.toHaveBeenCalled();+ });++ it('confirms OAuth via getMcpConnector when the chat projection is available', async () => {+ authenticateConnector.mockResolvedValue({ status: 'AUTHENTICATED' });+ getMcpConnector.mockResolvedValue(authenticatedConnector('connector-1'));+ useOptionalServer.mockReturnValue({ getMcpConnector });+ const callback = vi.fn();+ const { result } = renderHook(() => useMCPAuth());++ await act(async () => {+ await result.current.handleAuthorize('connector-1', callback);+ });++ expect(getMcpConnector).toHaveBeenCalledWith({ connectorId: 'connector-1' });+ expect(getConnector).not.toHaveBeenCalled();+ expect(callback).toHaveBeenCalledOnce();+ expect(callback).toHaveBeenCalledWith(true);+ expect(showError).not.toHaveBeenCalled();+ });++ it('does not invoke the callback after unmount while connector verification is in flight', async () => {+ authenticateConnector.mockResolvedValue({ status: 'AUTHENTICATED' });+ let resolveGet: ((connector: ConnectorBase) => void) | undefined;+ getConnector.mockImplementation(+ () =>+ new Promise(resolve => {+ resolveGet = resolve;+ }),+ );+ const callback = vi.fn();+ const { result, unmount } = renderHook(() => useMCPAuth());++ const authorizePromise = result.current.handleAuthorize('connector-1', callback);+ await waitFor(() => expect(getConnector).toHaveBeenCalledWith({ id: 'connector-1' }));++ unmount();+ await act(async () => {+ resolveGet?.(authenticatedConnector('connector-1'));+ await authorizePromise;+ });++ expect(callback).not.toHaveBeenCalled();+ expect(showError).not.toHaveBeenCalled();});});