Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(mcp): migrate MCP components to use new socket service

Steven Enamakel7db60ac7fb3f
diff --git a/app/src/App.tsx b/app/src/App.tsx
index 603e08a1d7..fa3f3c4102 100644
--- a/app/src/App.tsx
+++ b/app/src/App.tsx
@@ -25,7 +25,6 @@ import AppSidebar from './components/layout/shell/AppSidebar';
import RootShellLayout from './components/layout/shell/RootShellLayout';
import { SidebarSlotProvider } from './components/layout/shell/SidebarSlot';
import LocalAIDownloadSnackbar from './components/LocalAIDownloadSnackbar';
-import SecretPromptDialog from './components/mcp-setup/SecretPromptDialog';
import NoticeCenter from './components/notices/NoticeCenter';
import OpenhumanLinkModal from './components/OpenhumanLinkModal';
import PersistRehydrationScreen from './components/PersistRehydrationScreen';
@@ -140,7 +139,6 @@ function App() {
<KeyringConsentOverlay />
<HarnessInitOverlay />
<AnnouncementGate />
- <SecretPromptDialog />
</ServiceBlockingGate>
</CommandProvider>
</Router>
diff --git a/app/src/components/channels/mcp/ConfigAssistantPanel.test.tsx b/app/src/components/channels/mcp/ConfigAssistantPanel.test.tsx
deleted file mode 100644
index 11e28a0873..0000000000
--- a/app/src/components/channels/mcp/ConfigAssistantPanel.test.tsx
+++ /dev/null
@@ -1,135 +0,0 @@
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import ConfigAssistantPanel from './ConfigAssistantPanel';
-
-const mockConfigAssist = vi.fn();
-
-vi.mock('../../../services/api/mcpClientsApi', () => ({
- mcpClientsApi: { configAssist: (...args: unknown[]) => mockConfigAssist(...args) },
-}));
-
-describe('ConfigAssistantPanel', () => {
- beforeEach(() => {
- mockConfigAssist.mockReset();
- });
-
- it('renders the input textarea and Send button', () => {
- render(<ConfigAssistantPanel qualifiedName="acme/test" />);
- expect(screen.getByPlaceholderText(/ask a question/i)).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Send' })).toBeInTheDocument();
- });
-
- it('send button is disabled when input is empty', () => {
- render(<ConfigAssistantPanel qualifiedName="acme/test" />);
- expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();
- });
-
- it('enables send button when input has text', () => {
- render(<ConfigAssistantPanel qualifiedName="acme/test" />);
- fireEvent.change(screen.getByPlaceholderText(/ask a question/i), {
- target: { value: 'What env vars do I need?' },
- });
- expect(screen.getByRole('button', { name: 'Send' })).not.toBeDisabled();
- });
-
- it('sends message and renders assistant reply', async () => {
- mockConfigAssist.mockResolvedValue({ reply: 'You need an API_KEY env var.' });
- render(<ConfigAssistantPanel qualifiedName="acme/test" />);
-
- fireEvent.change(screen.getByPlaceholderText(/ask a question/i), {
- target: { value: 'What do I need?' },
- });
-
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'Send' }));
- });
-
- await waitFor(() => {
- expect(screen.getByText('You need an API_KEY env var.')).toBeInTheDocument();
- });
-
- expect(mockConfigAssist).toHaveBeenCalledWith({
- qualified_name: 'acme/test',
- user_message: 'What do I need?',
- history: [{ role: 'user', content: 'What do I need?' }],
- });
- });
-
- it('shows suggested_env values and Apply button', async () => {
- mockConfigAssist.mockResolvedValue({
- reply: 'Here are suggested values',
- suggested_env: { API_KEY: 'abc123' },
- });
-
- const onApply = vi.fn();
- render(<ConfigAssistantPanel qualifiedName="acme/test" onApplySuggestedEnv={onApply} />);
-
- fireEvent.change(screen.getByPlaceholderText(/ask a question/i), {
- target: { value: 'Help me configure' },
- });
-
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'Send' }));
- });
-
- await waitFor(() => {
- expect(screen.getByText('Here are suggested values')).toBeInTheDocument();
- });
-
- // Shows key name (the colon is in the same text node with whitespace)
- expect(screen.getByText(/API_KEY:/)).toBeInTheDocument();
-
- // Apply button exists and calls the callback
- const applyBtn = screen.getByRole('button', { name: 'Apply suggested values' });
- fireEvent.click(applyBtn);
- expect(onApply).toHaveBeenCalledWith({ API_KEY: 'abc123' });
- });
-
- it('shows error on failed request', async () => {
- mockConfigAssist.mockRejectedValue(new Error('AI service unavailable'));
- render(<ConfigAssistantPanel qualifiedName="acme/test" />);
-
- fireEvent.change(screen.getByPlaceholderText(/ask a question/i), {
- target: { value: 'Hello' },
- });
-
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'Send' }));
- });
-
- await waitFor(() => {
- expect(screen.getByText('AI service unavailable')).toBeInTheDocument();
- });
- });
-
- it('clears input after sending', async () => {
- mockConfigAssist.mockResolvedValue({ reply: 'OK' });
- render(<ConfigAssistantPanel qualifiedName="acme/test" />);
-
- const textarea = screen.getByPlaceholderText(/ask a question/i) as HTMLTextAreaElement;
- fireEvent.change(textarea, { target: { value: 'Question?' } });
-
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'Send' }));
- });
-
- expect(textarea.value).toBe('');
- });
-
- it('sends on Enter key press', async () => {
- mockConfigAssist.mockResolvedValue({ reply: 'reply' });
- render(<ConfigAssistantPanel qualifiedName="acme/test" />);
-
- const textarea = screen.getByPlaceholderText(/ask a question/i);
- fireEvent.change(textarea, { target: { value: 'test message' } });
-
- await act(async () => {
- fireEvent.keyDown(textarea, { key: 'Enter', shiftKey: false });
- });
-
- await waitFor(() => {
- expect(mockConfigAssist).toHaveBeenCalledTimes(1);
- });
- });
-});
diff --git a/app/src/components/channels/mcp/ConfigAssistantPanel.tsx b/app/src/components/channels/mcp/ConfigAssistantPanel.tsx
deleted file mode 100644
index 2e48e0a6ea..0000000000
--- a/app/src/components/channels/mcp/ConfigAssistantPanel.tsx
+++ /dev/null
@@ -1,233 +0,0 @@
-/**
- * Inline LLM-driven configuration assistant chat.
- * Maintains a local message history and calls config_assist with each send.
- * If the reply includes suggested_env, shows an "Apply suggested values" button
- * that passes them up to the caller (e.g. to pre-fill the install dialog).
- */
-import debug from 'debug';
-import { useCallback, useEffect, useRef, useState } from 'react';
-
-import { BubbleMarkdown } from '../../../features/conversations/components/AgentMessageBubble';
-import { useT } from '../../../lib/i18n/I18nContext';
-import { mcpClientsApi } from '../../../services/api/mcpClientsApi';
-import Button from '../../ui/Button';
-import TextArea from '../../ui/TextArea';
-
-const log = debug('mcp-clients:config-assist');
-
-interface Message {
- role: 'user' | 'assistant';
- content: string;
- suggested_env?: Record<string, string>;
-}
-
-// Per-server chat cache (keyed by qualified_name). Lets the help chat survive
-// closing+reopening the modal (you keep your place) while you stay on the MCP's
-// detail page. `clearConfigChat` is called when the detail page unmounts (back
-// to the list), so re-entering a server starts fresh.
-const chatCache = new Map<string, Message[]>();
-
-/** Drop the cached help chat for a server (called on detail-page unmount). */
-export function clearConfigChat(qualifiedName: string): void {
- chatCache.delete(qualifiedName);
-}
-
-interface ConfigAssistantPanelProps {
- qualifiedName: string;
- onApplySuggestedEnv?: (env: Record<string, string>) => void;
- /** A fixed, server-specific prompt offered as a one-click action in the empty
- * state. It is NOT auto-sent: firing the LLM research call on open made the
- * help panel block for seconds before showing anything (#4272). The user taps
- * the suggestion when they actually want guidance. */
- autoPrompt?: string;
-}
-
-const ConfigAssistantPanel = ({
- qualifiedName,
- onApplySuggestedEnv,
- autoPrompt,
-}: ConfigAssistantPanelProps) => {
- const { t } = useT();
- // Restore any in-progress chat for this server (survives modal reopen).
- const [messages, setMessages] = useState<Message[]>(() => chatCache.get(qualifiedName) ?? []);
- const [input, setInput] = useState('');
- const [sending, setSending] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const bottomRef = useRef<HTMLDivElement | null>(null);
-
- const scrollToBottom = useCallback(() => {
- bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
- }, []);
-
- const send = useCallback(
- async (text: string) => {
- const trimmed = text.trim();
- if (!trimmed || sending) return;
-
- const userMessage: Message = { role: 'user', content: trimmed };
- const updatedHistory = [...messages, userMessage];
- setMessages(updatedHistory);
- setSending(true);
- setError(null);
- log('sending message: %s', trimmed);
-
- try {
- const result = await mcpClientsApi.configAssist({
- qualified_name: qualifiedName,
- user_message: trimmed,
- history: updatedHistory.map(m => ({ role: m.role, content: m.content })),
- });
- log(
- 'received reply length=%d suggested_env=%s',
- result.reply.length,
- result.suggested_env ? 'yes' : 'no'
- );
-
- const assistantMessage: Message = {
- role: 'assistant',
- content: result.reply,
- suggested_env: result.suggested_env,
- };
- setMessages(prev => [...prev, assistantMessage]);
- setTimeout(scrollToBottom, 50);
- } catch (err) {
- const msg = err instanceof Error ? err.message : t('mcp.configAssistant.failedResponse');
- log('config_assist error: %s', msg);
- setError(msg);
- setMessages(messages);
- } finally {
- setSending(false);
- }
- },
- [messages, qualifiedName, sending, scrollToBottom, t]
- );
-
- const handleSend = useCallback(() => {
- const text = input.trim();
- if (!text) return;
- setInput('');
- void send(text);
- }, [input, send]);
-
- // Persist the chat per-server so reopening the modal restores it.
- useEffect(() => {
- chatCache.set(qualifiedName, messages);
- }, [qualifiedName, messages]);
-
- const handleKeyDown = useCallback(
- (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
- if (e.key === 'Enter' && !e.shiftKey) {
- e.preventDefault();
- void handleSend();
- }
- },
- [handleSend]
- );
-
- return (
- <div className="flex flex-col h-full space-y-2">
- {/* Message list */}
- <div className="flex-1 overflow-y-auto space-y-2 min-h-0 rounded-lg border border-line-subtle p-2">
- {messages.length === 0 && (
- <div className="py-2 text-center space-y-2">
- <p className="text-xs text-content-faint">{t('mcp.configAssistant.empty')}</p>
- {autoPrompt && (
- <Button
- variant="secondary"
- size="sm"
- disabled={sending}
- onClick={() => void send(autoPrompt)}>
- {t('mcp.configAssistant.autoPromptCta')}
- </Button>
- )}
- </div>
- )}
- {messages.map((msg, idx) => (
- <div
- key={idx}
- className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
- <div
- className={`max-w-[85%] rounded-lg px-3 py-2 text-sm ${
- msg.role === 'user'
- ? 'bg-primary-500 text-content-inverted'
- : 'bg-surface-subtle text-content'
- }`}>
- {msg.role === 'assistant' ? (
- <BubbleMarkdown content={msg.content} tone="agent" />
- ) : (
- <p className="whitespace-pre-wrap">{msg.content}</p>
- )}
- {msg.suggested_env && Object.keys(msg.suggested_env).length > 0 && (
- <div className="mt-2 pt-2 border-t border-content-inverted/20 space-y-1">
- <p className="text-[11px] font-medium opacity-80">
- {t('mcp.configAssistant.suggestedValues')}
- </p>
- <ul className="space-y-0.5">
- {Object.keys(msg.suggested_env).map(key => (
- <li key={key} className="text-[11px] font-mono opacity-90">
- {key}:{' '}
- <span className="opacity-60">{t('mcp.configAssistant.valueHidden')}</span>
- </li>
- ))}
- </ul>
- {onApplySuggestedEnv && (
- <Button
- variant="tertiary"
- size="xs"
- onClick={() => onApplySuggestedEnv(msg.suggested_env!)}
- className="mt-1 h-auto bg-content-inverted/10 px-2 py-1 text-[11px] font-medium hover:bg-content-inverted/20">
- {t('mcp.configAssistant.applySuggested')}
- </Button>
- )}
- {!onApplySuggestedEnv && (
- <p className="text-[11px] opacity-70">
- {t('mcp.configAssistant.reinstallHint')}
- </p>
- )}
- </div>
- )}
- </div>
- </div>
- ))}
- {sending && (
- <div className="flex justify-start">
- <div className="rounded-lg px-3 py-2 text-sm bg-surface-subtle text-content-faint">
- {t('mcp.configAssistant.thinking')}
- </div>
- </div>
- )}
- <div ref={bottomRef} />
- </div>
-
- {/* Error */}
- {error && (
- <div className="rounded-lg border border-coral-200 dark:border-coral-500/30 bg-coral-50 dark:bg-coral-500/10 px-3 py-2 text-xs text-coral-700 dark:text-coral-300">
- {error}
- </div>
- )}
-
- {/* Input row */}
- <div className="flex gap-2">
- <TextArea
- rows={2}
- value={input}
- onChange={e => setInput(e.target.value)}
- onKeyDown={handleKeyDown}
- disabled={sending}
- placeholder={t('mcp.configAssistant.inputPlaceholder')}
- className="flex-1 resize-none focus:ring-primary-500/40"
- />
- <Button
- variant="primary"
- size="md"
- disabled={sending || !input.trim()}
- onClick={() => void handleSend()}
- className="self-end shrink-0">
- {t('mcp.configAssistant.send')}
- </Button>
- </div>
- </div>
- );
-};
-
-export default ConfigAssistantPanel;
diff --git a/app/src/components/channels/mcp/ConfigHelpModal.test.tsx b/app/src/components/channels/mcp/ConfigHelpModal.test.tsx
deleted file mode 100644
index bd4b0f8760..0000000000
--- a/app/src/components/channels/mcp/ConfigHelpModal.test.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { clearConfigChat } from './ConfigAssistantPanel';
-import ConfigHelpModal from './ConfigHelpModal';
-
-const mockConfigAssist = vi.fn();
-
-vi.mock('../../../services/api/mcpClientsApi', () => ({
- mcpClientsApi: { configAssist: (...args: unknown[]) => mockConfigAssist(...args) },
-}));
-
-describe('ConfigHelpModal', () => {
- beforeEach(() => {
- mockConfigAssist.mockReset();
- // The embedded ConfigAssistantPanel caches chat history per qualified_name at
- // module scope; clear it so each test starts with a fresh chat (and the
- // one-click setup-help action is offered again).
- clearConfigChat('acme/test-server');
- // The on-demand prompt resolves when the user triggers it.
- mockConfigAssist.mockResolvedValue({ reply: 'Get a token from the dashboard.' });
- });
-
- it('renders the modal with the help heading and embedded assistant panel', async () => {
- render(
- <ConfigHelpModal
- qualifiedName="acme/test-server"
- displayName="Test Server"
- description="A test MCP server"
- onClose={() => {}}
- />
- );
- expect(screen.getByRole('dialog')).toBeInTheDocument();
- // Heading uses the "How do I get a token?" label.
- expect(screen.getByRole('heading', { name: 'Help & configure' })).toBeInTheDocument();
- // Embedded ConfigAssistantPanel renders its input.
- expect(screen.getByPlaceholderText(/ask a question/i)).toBeInTheDocument();
- // The help opens instantly — no blocking LLM call on open (#4272). The
- // research is offered as a one-click action instead.
- expect(mockConfigAssist).not.toHaveBeenCalled();
- expect(screen.getByRole('button', { name: 'Get step-by-step setup help' })).toBeInTheDocument();
- });
-
- it('runs a server-specific prompt on demand, naming the display name and qualified name', async () => {
- render(
- <ConfigHelpModal
- qualifiedName="acme/test-server"
- displayName="Test Server"
- description="A test MCP server"
- onClose={() => {}}
- />
- );
- // Nothing fires until the user asks for help.
- expect(mockConfigAssist).not.toHaveBeenCalled();
- fireEvent.click(screen.getByRole('button', { name: 'Get step-by-step setup help' }));
- await waitFor(() => {
- expect(mockConfigAssist).toHaveBeenCalledTimes(1);
- });
- const [{ qualified_name, user_message }] = mockConfigAssist.mock.calls[0];
- expect(qualified_name).toBe('acme/test-server');
- // The prompt embeds the friendly name, the qualified name, and description.
- expect(user_message).toContain('Test Server');
- expect(user_message).toContain('acme/test-server');
- expect(user_message).toContain('A test MCP server');
- });
-
- it('builds an on-demand prompt that omits the description sentence when none is given', async () => {
- render(
- <ConfigHelpModal
- qualifiedName="acme/test-server"
- displayName="Test Server"
- onClose={() => {}}
- />
- );
- fireEvent.click(screen.getByRole('button', { name: 'Get step-by-step setup help' }));
- await waitFor(() => {
- expect(mockConfigAssist).toHaveBeenCalledTimes(1);
- });
- const [{ user_message }] = mockConfigAssist.mock.calls[0];
- expect(user_message).toContain('Test Server');
- expect(user_message).toContain('acme/test-server');
- });
-
- it('closes via the close button', () => {
- const onClose = vi.fn();
- render(
- <ConfigHelpModal
- qualifiedName="acme/test-server"
- displayName="Test Server"
- onClose={onClose}
- />
- );
- // Migrated onto the shared `ModalShell` (#radix-ui-foundation): the close
- // button is now the shell's own, labelled with the common "Close" string
- // rather than the old hand-rolled ✕ button's "Cancel" label.
- fireEvent.click(screen.getByRole('button', { name: 'Close' }));
- expect(onClose).toHaveBeenCalled();
- });
-
- it('closes on Escape', () => {
- const onClose = vi.fn();
- render(
- <ConfigHelpModal
- qualifiedName="acme/test-server"
- displayName="Test Server"
- onClose={onClose}
- />
- );
- // Migrated onto `ModalShell` / Radix `Dialog`: dismissal is now via Escape
- // or the close button rather than a manual mousedown-on-self handler, so
- // this test now exercises the Radix escape-key path instead.
- fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
- expect(onClose).toHaveBeenCalled();
- });
-
- it('forwards onApplySuggestedEnv through to the assistant panel', async () => {
- mockConfigAssist.mockResolvedValue({
- reply: 'Here are values',
- suggested_env: { API_KEY: 'abc' },
- });
- const onApply = vi.fn();
- render(
- <ConfigHelpModal
- qualifiedName="acme/test-server"
- displayName="Test Server"
- onClose={() => {}}
- onApplySuggestedEnv={onApply}
- />
- );
- // Trigger the on-demand help; the reply carries suggested_env, so the Apply
- // button appears.
- fireEvent.click(screen.getByRole('button', { name: 'Get step-by-step setup help' }));
- const applyBtn = await screen.findByRole('button', { name: 'Apply suggested values' });
- fireEvent.click(applyBtn);
- expect(onApply).toHaveBeenCalledWith({ API_KEY: 'abc' });
- });
-});
diff --git a/app/src/components/channels/mcp/ConfigHelpModal.tsx b/app/src/components/channels/mcp/ConfigHelpModal.tsx
deleted file mode 100644
index 3ec7bfd522..0000000000
--- a/app/src/components/channels/mcp/ConfigHelpModal.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-/**
- * ConfigHelpModal — a focused, roomy modal that hosts the configuration-help
- * chat (ConfigAssistantPanel) for one MCP server. Launched from the Connect
- * modal's "How do I get a token?" link and from the server detail page, so the
- * chat gets its own space instead of crowding the auth inputs.
- *
- * Built on the shared `ModalShell` primitive (Radix `Dialog` underneath), so it
- * gets a real focus trap and stacks correctly above the Connect modal via
- * Radix's own layering rather than a hand-picked z-index.
- */
-import { useId } from 'react';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import { ModalShell } from '../../ui/ModalShell';
-import ConfigAssistantPanel from './ConfigAssistantPanel';
-
-interface ConfigHelpModalProps {
- qualifiedName: string;
- displayName: string;
- description?: string;
- onClose: () => void;
- /** Optional — when set, the assistant's "apply suggested values" wires back to
- * the caller (e.g. the detail page's reconfigure form). */
- onApplySuggestedEnv?: (env: Record<string, string>) => void;
-}
-
-const ConfigHelpModal = ({
- qualifiedName,
- displayName,
- description,
- onClose,
- onApplySuggestedEnv,
-}: ConfigHelpModalProps) => {
- const { t } = useT();
- const titleId = useId();
-
- // Fixed, server-specific research prompt the assistant auto-runs on open.
- const autoPrompt =
- `I'm connecting the MCP server "${displayName}" (${qualifiedName}).` +
- (description ? ` ${description}.` : '') +
- ` Walk me through, step by step, exactly where to obtain the credential I need:` +
- ` which website or dashboard, which account/settings page, and what scopes or permissions to enable,` +
- ` and the exact header name and value format to paste. Be concise and specific to this service.`;
-
- return (
- <ModalShell
- onClose={onClose}
- titleId={titleId}
- title={t('mcp.connectAuth.howToGetToken')}
- maxWidthClassName="max-w-2xl"
- contentClassName="flex h-[78vh] max-h-[88vh] min-h-0 flex-col px-5 py-4">
- <ConfigAssistantPanel
- qualifiedName={qualifiedName}
- autoPrompt={autoPrompt}
- onApplySuggestedEnv={onApplySuggestedEnv}
- />
- </ModalShell>
- );
-};
-
-export default ConfigHelpModal;
diff --git a/app/src/components/channels/mcp/InstallDialog.test.tsx b/app/src/components/channels/mcp/InstallDialog.test.tsx
deleted file mode 100644
index 30c3eb9563..0000000000
--- a/app/src/components/channels/mcp/InstallDialog.test.tsx
+++ /dev/null
@@ -1,372 +0,0 @@
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { McpRegistryUserError } from '../../../services/api/mcpRegistryErrors';
-import InstallDialog from './InstallDialog';
-
-const mockRegistryGet = vi.fn();
-const mockInstall = vi.fn();
-const mockConnect = vi.fn();
-
-vi.mock('../../../services/api/mcpClientsApi', () => ({
- mcpClientsApi: {
- registryGet: (...args: unknown[]) => mockRegistryGet(...args),
- install: (...args: unknown[]) => mockInstall(...args),
- connect: (...args: unknown[]) => mockConnect(...args),
- },
-}));
-
-const DETAIL = {
- qualified_name: 'acme/test-server',
- display_name: 'Test Server',
- description: 'A test server',
- connections: [{ type: 'stdio', published: true }],
- required_env_keys: ['API_KEY', 'SECRET_TOKEN'],
-};
-
-const DETAIL_NO_ENV = {
- qualified_name: 'acme/simple-server',
- display_name: 'Simple Server',
- description: 'No env needed',
- connections: [{ type: 'stdio', published: true }],
- required_env_keys: [],
-};
-
-async function goToConfigureStep() {
- await waitFor(() => screen.getByRole('button', { name: 'Configure & install' }));
- fireEvent.click(screen.getByRole('button', { name: 'Configure & install' }));
-}
-
-describe('InstallDialog', () => {
- beforeEach(() => {
- mockRegistryGet.mockReset();
- mockInstall.mockReset();
- mockConnect.mockReset();
- mockConnect.mockResolvedValue({ server_id: 'srv-1', status: 'connected', tools: [] });
- });
-
- it('shows loading state while fetching detail', () => {
- mockRegistryGet.mockReturnValue(new Promise(() => {}));
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={() => {}} onCancel={() => {}} />
- );
- expect(screen.getByText('Loading server details...')).toBeInTheDocument();
- });
-
- it('renders detail overview with server info', async () => {
- mockRegistryGet.mockResolvedValue(DETAIL);
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={() => {}} onCancel={() => {}} />
- );
-
- await waitFor(() => {
- expect(screen.getByText('Test Server')).toBeInTheDocument();
- });
- expect(screen.getByText('A test server')).toBeInTheDocument();
- // Transport badge uses the same Stdio/Hosted vocabulary as the catalog list
- // (the old separate "Cloud hosted"/"Requires configuration" pills were
- // dropped — the env-vars section below already conveys configuration).
- // Derived from the connection type (stdio here), NOT the detail DTO's
- // absent `is_deployed`.
- expect(screen.getByText('Stdio')).toBeInTheDocument();
- });
-
- it('labels a server with an http connection as Hosted', async () => {
- mockRegistryGet.mockResolvedValue({
- ...DETAIL,
- qualified_name: 'acme/hosted-server',
- display_name: 'Hosted Server',
- connections: [{ type: 'http', deployment_url: 'https://x.example/mcp', published: true }],
- });
- render(
- <InstallDialog qualifiedName="acme/hosted-server" onSuccess={() => {}} onCancel={() => {}} />
- );
-
- await waitFor(() => expect(screen.getByText('Hosted Server')).toBeInTheDocument());
- // The detail DTO carries no `is_deployed`; the badge must derive from the
- // http connection (this regressed to always-"Stdio" before the fix).
- expect(screen.getByText('Hosted')).toBeInTheDocument();
- expect(screen.queryByText('Stdio')).not.toBeInTheDocument();
- });
-
- it('shows env key preview badges on detail step', async () => {
- mockRegistryGet.mockResolvedValue(DETAIL);
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={() => {}} onCancel={() => {}} />
- );
-
- await waitFor(() => screen.getByText('API_KEY'));
- expect(screen.getByText('SECRET_TOKEN')).toBeInTheDocument();
- });
-
- it('shows friendly guidance instead of raw registry 404 JSON when detail load fails', async () => {
- mockRegistryGet.mockRejectedValue(
- new Error(
- 'MCP official registry GET unreal-mcp returned HTTP 404 Not Found: {"title":"Not Found","status":404,"detail":"Server not found"}'
- )
- );
- render(<InstallDialog qualifiedName="unreal-mcp" onSuccess={() => {}} onCancel={() => {}} />);
-
- await waitFor(() => screen.getByText(/Server not found in registry/));
-
- expect(screen.getByText(/browse available MCP servers/)).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Browse catalog' })).toBeInTheDocument();
- expect(screen.queryByText(/"title":"Not Found"/)).not.toBeInTheDocument();
- expect(screen.queryByText(/HTTP 404/)).not.toBeInTheDocument();
- });
-
- it('renders env key inputs after clicking configure', async () => {
- mockRegistryGet.mockResolvedValue(DETAIL);
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={() => {}} onCancel={() => {}} />
- );
-
- await goToConfigureStep();
- expect(screen.getByLabelText('API_KEY')).toBeInTheDocument();
- expect(screen.getByLabelText('SECRET_TOKEN')).toBeInTheDocument();
- });
-
- it('renders env inputs as password type by default', async () => {
- mockRegistryGet.mockResolvedValue(DETAIL);
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={() => {}} onCancel={() => {}} />
- );
-
- await goToConfigureStep();
- const input = screen.getByLabelText('API_KEY') as HTMLInputElement;
- expect(input.type).toBe('password');
- });
-
- it('toggles env input to text on Show click', async () => {
- mockRegistryGet.mockResolvedValue(DETAIL);
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={() => {}} onCancel={() => {}} />
- );
-
- await goToConfigureStep();
- const showButtons = screen.getAllByRole('button', { name: 'Show' });
- fireEvent.click(showButtons[0]);
- const input = screen.getByLabelText('API_KEY') as HTMLInputElement;
- expect(input.type).toBe('text');
- });
-
- it('calls install with filled values on submit', async () => {
- const installedServer = {
- server_id: 'srv-1',
- ...DETAIL,
- command_kind: 'node' as const,
- command: 'node',
- args: [],
- env_keys: ['API_KEY', 'SECRET_TOKEN'],
- installed_at: 1000,
- };
- mockRegistryGet.mockResolvedValue(DETAIL);
- mockInstall.mockResolvedValue(installedServer);
-
- const onSuccess = vi.fn();
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={onSuccess} onCancel={() => {}} />
- );
-
- await goToConfigureStep();
- fireEvent.change(screen.getByLabelText('API_KEY'), { target: { value: 'my-api-key' } });
- fireEvent.change(screen.getByLabelText('SECRET_TOKEN'), { target: { value: 'my-secret' } });
-
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'Install' }));
- });
-
- expect(mockInstall).toHaveBeenCalledWith({
- qualified_name: 'acme/test-server',
- env: { API_KEY: 'my-api-key', SECRET_TOKEN: 'my-secret' },
- config: undefined,
- });
- expect(mockConnect).toHaveBeenCalledWith('srv-1');
- expect(onSuccess).toHaveBeenCalledWith(installedServer);
- });
-
- it('still reports success when auto-connect fails (best-effort)', async () => {
- const installedServer = {
- server_id: 'srv-1',
- ...DETAIL,
- command_kind: 'node' as const,
- command: 'node',
- args: [],
- env_keys: ['API_KEY', 'SECRET_TOKEN'],
- installed_at: 1000,
- };
- mockRegistryGet.mockResolvedValue(DETAIL);
- mockInstall.mockResolvedValue(installedServer);
- mockConnect.mockRejectedValue(new Error('spawn failed'));
-
- const onSuccess = vi.fn();
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={onSuccess} onCancel={() => {}} />
- );
-
- await goToConfigureStep();
- fireEvent.change(screen.getByLabelText('API_KEY'), { target: { value: 'k' } });
- fireEvent.change(screen.getByLabelText('SECRET_TOKEN'), { target: { value: 's' } });
-
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'Install' }));
- });
-
- expect(mockConnect).toHaveBeenCalledWith('srv-1');
- expect(onSuccess).toHaveBeenCalledWith(installedServer);
- });
-
- it('shows validation error when required field is empty', async () => {
- mockRegistryGet.mockResolvedValue(DETAIL);
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={() => {}} onCancel={() => {}} />
- );
-
- await goToConfigureStep();
- fireEvent.change(screen.getByLabelText('SECRET_TOKEN'), { target: { value: 'secret' } });
-
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'Install' }));
- });
-
- expect(screen.getByText('"API_KEY" is required')).toBeInTheDocument();
- expect(mockInstall).not.toHaveBeenCalled();
- });
-
- it('shows install error on failure', async () => {
- mockRegistryGet.mockResolvedValue(DETAIL);
- mockInstall.mockRejectedValue(new Error('Server error'));
-
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={() => {}} onCancel={() => {}} />
- );
-
- await goToConfigureStep();
- fireEvent.change(screen.getByLabelText('API_KEY'), { target: { value: 'key' } });
- fireEvent.change(screen.getByLabelText('SECRET_TOKEN'), { target: { value: 'secret' } });
-
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'Install' }));
- });
-
- await waitFor(() => screen.getByText('Install failed'));
- });
-
- it('shows friendly guidance instead of raw registry JSON when install re-fetch fails', async () => {
- mockRegistryGet.mockResolvedValue(DETAIL);
- mockInstall.mockRejectedValue(
- new McpRegistryUserError(
- 'not_found',
- 'Failed to fetch registry detail: MCP official registry GET unreal-mcp returned HTTP 404 Not Found: {"title":"Not Found","status":404,"detail":"Server not found"}'
- )
- );
-
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={() => {}} onCancel={() => {}} />
- );
-
- await goToConfigureStep();
- fireEvent.change(screen.getByLabelText('API_KEY'), { target: { value: 'key' } });
- fireEvent.change(screen.getByLabelText('SECRET_TOKEN'), { target: { value: 'secret' } });
-
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'Install' }));
- });
-
- await waitFor(() => screen.getByText(/Server not found in registry/));
-
- expect(screen.queryByText(/"title":"Not Found"/)).not.toBeInTheDocument();
- expect(screen.queryByText(/HTTP 404/)).not.toBeInTheDocument();
- });
-
- it('calls onCancel when Cancel is clicked on detail step', async () => {
- mockRegistryGet.mockResolvedValue(DETAIL);
- const onCancel = vi.fn();
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={() => {}} onCancel={onCancel} />
- );
-
- await waitFor(() => screen.getByRole('button', { name: 'Cancel' }));
- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
- expect(onCancel).toHaveBeenCalledTimes(1);
- });
-
- it('pre-fills env values from prefillEnv prop', async () => {
- mockRegistryGet.mockResolvedValue(DETAIL);
- render(
- <InstallDialog
- qualifiedName="acme/test-server"
- prefillEnv={{ API_KEY: 'prefilled-key' }}
- onSuccess={() => {}}
- onCancel={() => {}}
- />
- );
-
- await goToConfigureStep();
- const input = screen.getByLabelText('API_KEY') as HTMLInputElement;
- expect(input.value).toBe('prefilled-key');
- });
-
- it('installs directly from detail step when no env keys required', async () => {
- const installedServer = {
- server_id: 'srv-2',
- ...DETAIL_NO_ENV,
- command_kind: 'node' as const,
- command: 'node',
- args: [],
- env_keys: [],
- installed_at: 2000,
- };
- mockRegistryGet.mockResolvedValue(DETAIL_NO_ENV);
- mockInstall.mockResolvedValue(installedServer);
-
- const onSuccess = vi.fn();
- render(
- <InstallDialog qualifiedName="acme/simple-server" onSuccess={onSuccess} onCancel={() => {}} />
- );
-
- await waitFor(() => screen.getByRole('button', { name: 'Install' }));
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'Install' }));
- });
-
- expect(mockInstall).toHaveBeenCalledWith({
- qualified_name: 'acme/simple-server',
- env: {},
- config: undefined,
- });
- expect(onSuccess).toHaveBeenCalledWith(installedServer);
- });
-
- it('shows connection info on detail step', async () => {
- mockRegistryGet.mockResolvedValue({
- ...DETAIL,
- connections: [
- { type: 'stdio', published: true },
- { type: 'http', published: false, deployment_url: 'https://example.com/mcp' },
- ],
- });
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={() => {}} onCancel={() => {}} />
- );
-
- await waitFor(() => screen.getByText('Available connections'));
- expect(screen.getByText('stdio')).toBeInTheDocument();
- expect(screen.getByText('http')).toBeInTheDocument();
- });
-
- it('navigates back from configure to detail step', async () => {
- mockRegistryGet.mockResolvedValue(DETAIL);
- render(
- <InstallDialog qualifiedName="acme/test-server" onSuccess={() => {}} onCancel={() => {}} />
- );
-
- await goToConfigureStep();
- expect(screen.getByLabelText('API_KEY')).toBeInTheDocument();
-
- fireEvent.click(screen.getByText(`← Test Server`));
- await waitFor(() => {
- expect(screen.getByText('A test server')).toBeInTheDocument();
- });
- });
-});
diff --git a/app/src/components/channels/mcp/InstallDialog.tsx b/app/src/components/channels/mcp/InstallDialog.tsx
deleted file mode 100644
index 79e08b10b4..0000000000
--- a/app/src/components/channels/mcp/InstallDialog.tsx
+++ /dev/null
@@ -1,454 +0,0 @@
-/**
- * Rich install screen for an MCP server.
- *
- * Two-step flow:
- * 1. **Detail** — server overview (icon, title, author, description, stats,
- * transport type). If no env vars are required, a single "Install" button
- * kicks off the install directly.
- * 2. **Configure** — env var inputs + optional raw JSON config, then install.
- *
- * Uses `mcpClientsApi.registryGet` for detail, `mcpClientsApi.install` for
- * the install itself, and best-effort `mcpClientsApi.connect` post-install.
- */
-import debug from 'debug';
-import { useCallback, useEffect, useRef, useState } from 'react';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import { mcpClientsApi } from '../../../services/api/mcpClientsApi';
-import Button from '../../ui/Button';
-import TextArea from '../../ui/TextArea';
-import TextField from '../../ui/TextField';
-import { mcpRegistryErrorMessage } from './mcpRegistryErrorMessage';
-import { deriveAuthor } from './McpServerCard';
-import type { InstalledServer, SmitheryServerDetail } from './types';
-
-const log = debug('mcp-clients:install');
-
-type Step = 'detail' | 'configure';
-
-interface InstallDialogProps {
- qualifiedName: string;
- prefillEnv?: Record<string, string>;
- onSuccess: (server: InstalledServer) => void;
- onCancel: () => void;
-}
-
-function formatUseCount(count: number): string {
- if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
- if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`;
- return String(count);
-}
-
-const InstallDialog = ({ qualifiedName, prefillEnv, onSuccess, onCancel }: InstallDialogProps) => {
- const { t } = useT();
-
- const [detail, setDetail] = useState<SmitheryServerDetail | null>(null);
- const [loadingDetail, setLoadingDetail] = useState(true);
- const [detailError, setDetailError] = useState<string | null>(null);
- const latestQualifiedNameRef = useRef(qualifiedName);
-
- const [step, setStep] = useState<Step>('detail');
-
- const [envValues, setEnvValues] = useState<Record<string, string>>({});
- const [showEnv, setShowEnv] = useState<Record<string, boolean>>({});
- const [configJson, setConfigJson] = useState('');
- const [showAdvanced, setShowAdvanced] = useState(false);
-
- const [installing, setInstalling] = useState(false);
- const [installError, setInstallError] = useState<string | null>(null);
-
- useEffect(() => {
- latestQualifiedNameRef.current = qualifiedName;
- setLoadingDetail(true);
- setDetailError(null);
- log('fetching detail for %s', qualifiedName);
- const requestedName = qualifiedName;
- mcpClientsApi
- .registryGet(qualifiedName)
- .then(d => {
- if (latestQualifiedNameRef.current !== requestedName) return;
- setDetail(d);
- const initial: Record<string, string> = {};
- for (const key of d.required_env_keys ?? []) {
- initial[key] = prefillEnv?.[key] ?? '';
- }
- setEnvValues(initial);
- log('detail loaded, required_env_keys=%o', d.required_env_keys);
- })
- .catch(err => {
- if (latestQualifiedNameRef.current !== requestedName) return;
- const msg = mcpRegistryErrorMessage(err, t, 'mcp.install.failedDetail');
- log('detail error: %s', msg);
- setDetailError(msg);
- })
- .finally(() => {
- if (latestQualifiedNameRef.current === requestedName) {
- setLoadingDetail(false);
- }
- });
- }, [qualifiedName, prefillEnv, t]);
-
- const hasEnvKeys = (detail?.required_env_keys ?? []).length > 0;
-
- const toggleShowEnv = useCallback((key: string) => {
- setShowEnv(prev => ({ ...prev, [key]: !prev[key] }));
- }, []);
-
- const handleEnvChange = useCallback((key: string, value: string) => {
- setEnvValues(prev => ({ ...prev, [key]: value }));
- }, []);
-
- const handleInstall = useCallback(async () => {
- if (!detail) return;
-
- for (const key of detail.required_env_keys ?? []) {
- if (!envValues[key]?.trim()) {
- setInstallError(t('mcp.install.missingRequired').replace('{key}', key));
- return;
- }
- }
-
- let parsedConfig: unknown = undefined;
- if (configJson.trim()) {
- try {
- parsedConfig = JSON.parse(configJson.trim());
- } catch {
- setInstallError(t('mcp.install.invalidJson'));
- return;
- }
- }
-
- setInstalling(true);
- setInstallError(null);
- log('installing %s', qualifiedName);
-
- try {
- const server = await mcpClientsApi.install({
- qualified_name: qualifiedName,
- env: envValues,
- config: parsedConfig,
- });
- log('install success server_id=%s', server.server_id);
- // Await the first connect so the detail view opens with an accurate
- // status rather than a stale "disconnected" that races the background
- // attempt. A failed connect is expected for servers that need auth
- // (OAuth sign-in / token) — we keep the install and let the detail view
- // surface the error and prompt to connect, so we never treat a connect
- // failure as an install failure.
- try {
- await mcpClientsApi.connect(server.server_id);
- log('auto-connect success server_id=%s', server.server_id);
- } catch (connectErr: unknown) {
- log(
- 'auto-connect failed server_id=%s: %s',
- server.server_id,
- connectErr instanceof Error ? connectErr.message : String(connectErr)
- );
- }
- onSuccess(server);
- } catch (err) {
- const msg = mcpRegistryErrorMessage(err, t, 'mcp.install.failedInstall');
- log('install error: %s', msg);
- setInstallError(msg);
- } finally {
- setInstalling(false);
- }
- }, [detail, envValues, configJson, qualifiedName, onSuccess, t]);
-
- const handleDirectInstall = useCallback(async () => {
- if (hasEnvKeys) {
- setStep('configure');
- setInstallError(null);
- return;
- }
- await handleInstall();
- }, [hasEnvKeys, handleInstall]);
-
- // ── Loading / error states ───────────────────────────────────────────────
-
- if (loadingDetail) {
- return (
- <div className="py-10 text-center text-sm text-content-faint">
- {t('mcp.install.loadingDetail')}
- </div>
- );
- }
-
- if (detailError) {
- return (
- <div className="space-y-3">
- <div className="rounded-lg border border-coral-200 dark:border-coral-500/30 bg-coral-50 dark:bg-coral-500/10 px-4 py-3 text-sm text-coral-700 dark:text-coral-300">
- {detailError}
- </div>
- <Button
- variant="tertiary"
- size="sm"
- onClick={onCancel}
- className="text-content-muted hover:underline">
- {t('mcp.installed.browseCatalog')}
- </Button>
- </div>
- );
- }
-
- if (!detail) return null;
-
- const author = deriveAuthor(qualifiedName);
- // The detail DTO doesn't carry `is_deployed`, so derive transport from the
- // connection types instead (an `http` connection ⇒ hosted, else stdio) —
- // otherwise hosted-only servers are always mislabeled "Stdio".
- const isHosted = (detail.connections ?? []).some(c => c.type === 'http');
-
- // ── Step 1: Detail overview ──────────────────────────────────────────────
-
- if (step === 'detail') {
- return (
- <div className="space-y-5">
- <Button
- variant="tertiary"
- size="xs"
- onClick={onCancel}
- className="text-content-muted hover:underline">
- ← {t('mcp.install.back')}
- </Button>
-
- {/* Header */}
- <div className="flex items-start gap-4">
- {detail.icon_url ? (
- <img
- src={detail.icon_url}
- alt=""
- className="w-14 h-14 rounded-lg shrink-0 object-contain bg-surface border border-line-subtle"
- />
- ) : (
- <div className="w-14 h-14 rounded-lg shrink-0 bg-primary-100 dark:bg-primary-500/20 flex items-center justify-center text-2xl">
- 🔌
- </div>
- )}
- <div className="min-w-0 flex-1">
- <h3 className="text-lg font-semibold text-content">{detail.display_name}</h3>
- {author && (
- <p className="text-sm text-content-muted mt-0.5">
- {t('mcp.install.by')} {author}
- </p>
- )}
- </div>
- </div>
-
- {/* Stats badges — same Hosted/Stdio vocabulary as the catalog list (no
- separate "Cloud hosted"/"Requires configuration" pills: the
- transport badge and the "Required environment variables" section
- below already convey both). */}
- <div className="flex flex-wrap gap-2">
- <span className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium bg-surface-subtle text-content-secondary">
- {isHosted ? t('mcp.tab.transport.hosted') : t('mcp.tab.transport.local')}
- </span>
- {detail.use_count != null && detail.use_count > 0 && (
- <span className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium bg-surface-subtle text-content-secondary">
- {t('mcp.install.useCount').replace('{count}', formatUseCount(detail.use_count))}
- </span>
- )}
- </div>
-
- {/* Description */}
- {detail.description && (
- <div className="text-sm text-content-secondary leading-relaxed whitespace-pre-line">
- {detail.description}
- </div>
- )}
-
- {/* Connections info */}
- {detail.connections.length > 0 && (
- <div className="rounded-lg border border-line dark:border-line-strong/60 bg-surface-muted p-3">
- <p className="text-xs font-medium text-content-muted mb-2">
- {t('mcp.install.connections')}
- </p>
- <div className="space-y-1.5">
- {detail.connections.map((conn, i) => (
- <div key={i} className="flex items-center gap-2 text-xs text-content-secondary">
- <span
- className={`w-2 h-2 rounded-full shrink-0 ${conn.published ? 'bg-sage-500' : 'bg-surface-strong'}`}
- />
- <span className="font-mono">{conn.type}</span>
- {conn.published && (
- <span className="text-content-faint">({t('mcp.install.published')})</span>
- )}
- {conn.deployment_url && (
- <span className="text-content-faint truncate">{conn.deployment_url}</span>
- )}
- </div>
- ))}
- </div>
- </div>
- )}
-
- {/* Required env keys preview */}
- {hasEnvKeys && (
- <div className="rounded-lg border border-amber-200 dark:border-amber-500/20 bg-amber-50 dark:bg-amber-500/10 p-3">
- <p className="text-xs font-medium text-amber-700 dark:text-amber-300 mb-1.5">
- {t('mcp.install.requiredEnv')}
- </p>
- <div className="flex flex-wrap gap-1.5">
- {detail.required_env_keys!.map(key => (
- <code
- key={key}
- className="rounded bg-amber-100 dark:bg-amber-500/20 px-1.5 py-0.5 text-xs font-mono text-amber-800 dark:text-amber-200">
- {key}
- </code>
- ))}
- </div>
- </div>
- )}
-
- {/* Install error (shown when no-config install fails) */}
- {installError && (
- <div className="rounded-lg border border-coral-200 dark:border-coral-500/30 bg-coral-50 dark:bg-coral-500/10 px-4 py-3 text-sm text-coral-700 dark:text-coral-300">
- {installError}
- </div>
- )}
-
- {/* Actions */}
- <div className="flex gap-2 pt-1">
- <Button
- variant="primary"
- size="lg"
- disabled={installing}
- onClick={() => void handleDirectInstall()}>
- {installing
- ? t('mcp.install.installing')
- : hasEnvKeys
- ? t('mcp.install.configureAndInstall')
- : t('mcp.install.button')}
- </Button>
- <Button variant="secondary" size="lg" disabled={installing} onClick={onCancel}>
- {t('common.cancel')}
- </Button>
- </div>
- </div>
- );
- }
-
- // ── Step 2: Configure & install ──────────────────────────────────────────
-
- return (
- <div className="space-y-4">
- <Button
- variant="tertiary"
- size="xs"
- onClick={() => {
- setStep('detail');
- setInstallError(null);
- }}
- className="text-content-muted hover:underline">
- ← {detail.display_name}
- </Button>
-
- {/* Compact header */}
- <div className="flex items-center gap-3">
- {detail.icon_url ? (
- <img
- src={detail.icon_url}
- alt=""
- className="w-8 h-8 rounded shrink-0 object-contain bg-surface"
- />
- ) : (
- <div className="w-8 h-8 rounded shrink-0 bg-primary-100 dark:bg-primary-500/20 flex items-center justify-center text-sm">
- 🔌
- </div>
- )}
- <h3 className="text-base font-semibold text-content">
- {t('mcp.install.configureTitle').replace('{name}', detail.display_name)}
- </h3>
- </div>
-
- {/* Env var inputs */}
- {hasEnvKeys && (
- <div className="space-y-3">
- <p className="text-xs font-medium text-content-secondary">
- {t('mcp.install.requiredEnv')}
- </p>
- {detail.required_env_keys!.map(key => (
- <div key={key} className="space-y-1">
- <label
- htmlFor={`env-${key}`}
- className="block text-xs font-medium text-content-secondary font-mono">
- {key}
- </label>
- <div className="flex gap-2">
- <TextField
- id={`env-${key}`}
- type={showEnv[key] ? 'text' : 'password'}
- value={envValues[key] ?? ''}
- onChange={e => handleEnvChange(key, e.target.value)}
- placeholder={t('mcp.install.enterValue').replace('{key}', key)}
- disabled={installing}
- className="flex-1"
- />
- <Button
- variant="secondary"
- size="sm"
- onClick={() => toggleShowEnv(key)}
- disabled={installing}
- className="shrink-0">
- {showEnv[key] ? t('mcp.install.hide') : t('mcp.install.show')}
- </Button>
- </div>
- </div>
- ))}
- </div>
- )}
-
- {/* Advanced: optional JSON config */}
- <div>
- <Button
- variant="tertiary"
- size="xs"
- onClick={() => setShowAdvanced(!showAdvanced)}
- className="h-auto p-0 text-xs text-content-muted hover:text-content-secondary">
- {showAdvanced ? '▾' : '▸'} {t('mcp.install.advancedConfig')}
- </Button>
- {showAdvanced && (
- <div className="mt-2 space-y-1">
- <label
- htmlFor="mcp-config-json"
- className="block text-xs font-medium text-content-secondary">
- {t('mcp.install.configLabel')}
- </label>
- <TextArea
- id="mcp-config-json"
- value={configJson}
- onChange={e => setConfigJson(e.target.value)}
- disabled={installing}
- rows={4}
- placeholder={t('mcp.install.configPlaceholder')}
- className="w-full font-mono focus:ring-primary-500/40"
- />
- </div>
- )}
- </div>
-
- {/* Errors */}
- {installError && (
- <div className="rounded-lg border border-coral-200 dark:border-coral-500/30 bg-coral-50 dark:bg-coral-500/10 px-4 py-3 text-sm text-coral-700 dark:text-coral-300">
- {installError}
- </div>
- )}
-
- {/* Actions */}
- <div className="flex gap-2 pt-1">
- <Button
- variant="primary"
- size="lg"
- disabled={installing}
- onClick={() => void handleInstall()}>
- {installing ? t('mcp.install.installing') : t('mcp.install.button')}
- </Button>
- <Button variant="secondary" size="lg" disabled={installing} onClick={onCancel}>
- {t('common.cancel')}
- </Button>
- </div>
- </div>
- );
-};
-
-export default InstallDialog;
diff --git a/app/src/components/channels/mcp/McpCatalogBrowser.test.tsx b/app/src/components/channels/mcp/McpCatalogBrowser.test.tsx
deleted file mode 100644
index d86846c986..0000000000
--- a/app/src/components/channels/mcp/McpCatalogBrowser.test.tsx
+++ /dev/null
@@ -1,225 +0,0 @@
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { StrictMode } from 'react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-// Static import — follows project no-dynamic-import rule for test files.
-import McpCatalogBrowser from './McpCatalogBrowser';
-
-const mockRegistrySearch = vi.fn();
-
-const deferred = <T,>() => {
- let resolve!: (value: T) => void;
- const promise = new Promise<T>(resolvePromise => {
- resolve = resolvePromise;
- });
- return { promise, resolve };
-};
-
-vi.mock('../../../services/api/mcpClientsApi', () => ({
- mcpClientsApi: { registrySearch: (...args: unknown[]) => mockRegistrySearch(...args) },
-}));
-
-describe('McpCatalogBrowser', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- mockRegistrySearch.mockReset();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('renders search input', async () => {
- mockRegistrySearch.mockResolvedValue({ servers: [], page: 1, total_pages: 1 });
- render(<McpCatalogBrowser onSelectInstall={() => {}} />);
- const search = screen.getByPlaceholderText('Search MCP servers...');
- expect(search).toHaveAttribute('type', 'search');
- expect(search).toHaveClass('h-9');
- });
-
- it('fetches only the latest debounced query and resets pagination', async () => {
- mockRegistrySearch.mockImplementation(({ page }: { page: number }) =>
- Promise.resolve({
- servers: [{ qualified_name: `acme/page-${page}`, display_name: `Page ${page}` }],
- page,
- total_pages: 2,
- })
- );
- render(<McpCatalogBrowser onSelectInstall={() => {}} />);
-
- await act(async () => {
- await Promise.resolve();
- });
- fireEvent.click(screen.getByRole('button', { name: 'Load more' }));
- expect(mockRegistrySearch).toHaveBeenLastCalledWith({
- query: undefined,
- page: 2,
- page_size: 20,
- });
- mockRegistrySearch.mockClear();
-
- const input = screen.getByPlaceholderText('Search MCP servers...');
- fireEvent.change(input, { target: { value: 'git' } });
- act(() => vi.advanceTimersByTime(100));
- fireEvent.change(input, { target: { value: 'github' } });
-
- // Before debounce fires, no new call
- act(() => vi.advanceTimersByTime(249));
- expect(mockRegistrySearch).not.toHaveBeenCalled();
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(1);
- });
-
- expect(mockRegistrySearch).toHaveBeenCalledTimes(1);
- expect(mockRegistrySearch).toHaveBeenCalledWith({ query: 'github', page: 1, page_size: 20 });
- });
-
- it('coalesces StrictMode fetches for each stable debounced query', async () => {
- const initialRequest = deferred<{ servers: never[]; page: number; total_pages: number }>();
- const changedRequest = deferred<{ servers: never[]; page: number; total_pages: number }>();
- mockRegistrySearch.mockImplementation(({ query }: { query?: string }) =>
- query === 'github' ? changedRequest.promise : initialRequest.promise
- );
-
- render(
- <StrictMode>
- <McpCatalogBrowser onSelectInstall={() => {}} />
- </StrictMode>
- );
-
- initialRequest.resolve({ servers: [], page: 1, total_pages: 1 });
- await act(async () => {
- await initialRequest.promise;
- });
- expect(mockRegistrySearch).toHaveBeenCalledTimes(1);
-
- fireEvent.change(screen.getByPlaceholderText('Search MCP servers...'), {
- target: { value: 'github' },
- });
- act(() => vi.advanceTimersByTime(249));
- expect(mockRegistrySearch).toHaveBeenCalledTimes(1);
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(1);
- });
- expect(mockRegistrySearch).toHaveBeenCalledTimes(2);
- expect(mockRegistrySearch).toHaveBeenLastCalledWith({
- query: 'github',
- page: 1,
- page_size: 20,
- });
-
- changedRequest.resolve({ servers: [], page: 1, total_pages: 1 });
- await act(async () => {
- await changedRequest.promise;
- });
- });
-
- it('renders server cards from search results', async () => {
- const servers = [
- {
- qualified_name: 'acme/file-server',
- display_name: 'File Server',
- description: 'Reads files',
- use_count: 100,
- is_deployed: true,
- },
- ];
- mockRegistrySearch.mockResolvedValue({ servers, page: 1, total_pages: 1 });
- render(<McpCatalogBrowser onSelectInstall={() => {}} />);
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(300);
- });
- // waitFor polls via real setTimeout; switch back so it isn't deadlocked by fake timers.
- vi.useRealTimers();
-
- await waitFor(() => {
- expect(screen.getByText('File Server')).toBeInTheDocument();
- });
- expect(screen.getByText('Reads files')).toBeInTheDocument();
- });
-
- it('calls onSelectInstall when Install button is clicked', async () => {
- const servers = [{ qualified_name: 'acme/file-server', display_name: 'File Server' }];
- mockRegistrySearch.mockResolvedValue({ servers, page: 1, total_pages: 1 });
- const onSelectInstall = vi.fn();
- render(<McpCatalogBrowser onSelectInstall={onSelectInstall} />);
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(300);
- });
- vi.useRealTimers();
-
- await waitFor(() => screen.getByText('File Server'));
-
- fireEvent.click(screen.getByRole('button', { name: /File Server/ }));
- expect(onSelectInstall).toHaveBeenCalledWith('acme/file-server');
- });
-
- it('shows load more when more pages available', async () => {
- const servers = [{ qualified_name: 'a/b', display_name: 'B' }];
- mockRegistrySearch.mockResolvedValue({ servers, page: 1, total_pages: 3 });
- render(<McpCatalogBrowser onSelectInstall={() => {}} />);
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(300);
- });
- vi.useRealTimers();
-
- await waitFor(() => screen.getByText('Load more'));
- expect(screen.getByRole('button', { name: 'Load more' })).toBeInTheDocument();
- });
-
- it('does not crash when registrySearch returns servers: undefined', async () => {
- // Simulates a malformed envelope where the `servers` field is missing.
- // The catalog component spreads `result.servers` — if undefined, the spread
- // would throw. This test verifies a graceful "no results" render instead.
- mockRegistrySearch.mockResolvedValue({ servers: undefined, page: 1, total_pages: 1 });
- render(<McpCatalogBrowser onSelectInstall={() => {}} />);
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(300);
- });
- vi.useRealTimers();
-
- // Should show empty/no-results state, not crash
- await waitFor(() => {
- expect(screen.getByPlaceholderText('Search MCP servers...')).toBeInTheDocument();
- });
- // No "Install" button — nothing to install from an undefined list
- expect(screen.queryByRole('button', { name: 'Install' })).not.toBeInTheDocument();
- });
-
- it('does not crash when registrySearch returns null servers', async () => {
- mockRegistrySearch.mockResolvedValue({ servers: null, page: 1, total_pages: 1 });
- render(<McpCatalogBrowser onSelectInstall={() => {}} />);
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(300);
- });
- vi.useRealTimers();
-
- await waitFor(() => {
- expect(screen.getByPlaceholderText('Search MCP servers...')).toBeInTheDocument();
- });
- expect(screen.queryByRole('button', { name: 'Install' })).not.toBeInTheDocument();
- });
-
- it('shows friendly guidance when search fails', async () => {
- mockRegistrySearch.mockRejectedValue(
- new Error('MCP official registry returned HTTP 500: {"detail":"upstream down"}')
- );
- render(<McpCatalogBrowser onSelectInstall={() => {}} />);
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(300);
- });
- vi.useRealTimers();
-
- await waitFor(() => screen.getByText(/The MCP registry is unavailable right now/));
- expect(screen.getByText(/browse available MCP servers/)).toBeInTheDocument();
- expect(screen.queryByText(/"detail":"upstream down"/)).not.toBeInTheDocument();
- });
-});
diff --git a/app/src/components/channels/mcp/McpCatalogBrowser.tsx b/app/src/components/channels/mcp/McpCatalogBrowser.tsx
deleted file mode 100644
index c8a6dd728f..0000000000
--- a/app/src/components/channels/mcp/McpCatalogBrowser.tsx
+++ /dev/null
@@ -1,142 +0,0 @@
-/**
- * MCP server catalog browser with debounced search and pagination.
- * Clicking "Install" on a card opens the InstallDialog flow.
- */
-import debug from 'debug';
-import { useCallback, useEffect, useRef, useState } from 'react';
-
-import { useDebouncedValue } from '../../../hooks/useDebouncedValue';
-import { useT } from '../../../lib/i18n/I18nContext';
-import { mcpClientsApi } from '../../../services/api/mcpClientsApi';
-import Button from '../../ui/Button';
-import Input from '../../ui/Input';
-import { mcpRegistryErrorMessage } from './mcpRegistryErrorMessage';
-import McpServerCard from './McpServerCard';
-import type { SmitheryServer } from './types';
-
-const log = debug('mcp-clients:catalog');
-const DEBOUNCE_MS = 250;
-const PAGE_SIZE = 20;
-
-interface McpCatalogBrowserProps {
- onSelectInstall: (qualifiedName: string) => void;
-}
-
-const McpCatalogBrowser = ({ onSelectInstall }: McpCatalogBrowserProps) => {
- const { t } = useT();
- const [query, setQuery] = useState('');
- const [servers, setServers] = useState<SmitheryServer[]>([]);
- const [page, setPage] = useState(1);
- const [totalPages, setTotalPages] = useState(1);
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const debouncedQuery = useDebouncedValue(query, DEBOUNCE_MS);
- // Monotonically-increasing counter used to discard stale registrySearch
- // responses when a newer request has already been issued.
- const requestSeqRef = useRef(0);
-
- const fetchPage = useCallback(
- async (searchQuery: string, pageNum: number, append: boolean) => {
- const seq = ++requestSeqRef.current;
- setLoading(true);
- setError(null);
- log('fetching page=%d query=%s seq=%d', pageNum, searchQuery, seq);
- try {
- const result = await mcpClientsApi.registrySearch({
- query: searchQuery || undefined,
- page: pageNum,
- page_size: PAGE_SIZE,
- });
- // Discard if a newer request has already been dispatched.
- if (seq !== requestSeqRef.current) {
- log('discarding stale response seq=%d (latest=%d)', seq, requestSeqRef.current);
- return;
- }
- setTotalPages(result.total_pages);
- setPage(result.page);
- // Guard against malformed envelope where `servers` is null/undefined.
- const incoming = result.servers ?? [];
- setServers(prev => (append ? [...prev, ...incoming] : incoming));
- log('loaded %d servers (append=%s)', incoming.length, append);
- } catch (err) {
- if (seq !== requestSeqRef.current) return;
- const msg = mcpRegistryErrorMessage(err, t, 'mcp.catalog.loadFailed');
- log('catalog fetch error: %s', msg);
- setError(msg);
- } finally {
- if (seq === requestSeqRef.current) {
- setLoading(false);
- }
- }
- },
- [t]
- );
- const lastEffectFetchRef = useRef<{ query: string; fetchPage: typeof fetchPage } | null>(null);
-
- // Reset to page 1 whenever the debounced query changes.
- useEffect(() => {
- const lastFetch = lastEffectFetchRef.current;
- if (lastFetch?.query === debouncedQuery && lastFetch.fetchPage === fetchPage) {
- return;
- }
- lastEffectFetchRef.current = { query: debouncedQuery, fetchPage };
- void fetchPage(debouncedQuery, 1, false);
- }, [debouncedQuery, fetchPage]);
-
- const handleLoadMore = () => {
- void fetchPage(debouncedQuery, page + 1, true);
- };
-
- return (
- <div className="space-y-3">
- <div className="flex items-center gap-2">
- <Input
- type="search"
- aria-label={t('mcp.catalog.searchAria')}
- placeholder={t('mcp.catalog.searchPlaceholder')}
- value={query}
- onChange={e => setQuery(e.target.value)}
- className="flex-1"
- />
- </div>
-
- {error && (
- <div className="rounded-lg border border-coral-200 dark:border-coral-500/30 bg-coral-50 dark:bg-coral-500/10 px-4 py-3 text-sm text-coral-700 dark:text-coral-300">
- {error}
- </div>
- )}
-
- {loading && servers.length === 0 ? (
- <div className="text-sm text-content-faint py-6 text-center">{t('common.loading')}</div>
- ) : servers.length === 0 ? (
- <div className="text-sm text-content-faint py-6 text-center">
- {query
- ? t('mcp.catalog.noResultsFor').replace('{query}', query)
- : t('mcp.catalog.noResults')}
- </div>
- ) : (
- <>
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
- {servers.map(server => (
- <McpServerCard
- key={server.qualified_name}
- server={server}
- onSelect={onSelectInstall}
- />
- ))}
- </div>
-
- {page < totalPages && (
- <div className="flex justify-center pt-2">
- <Button variant="secondary" size="md" disabled={loading} onClick={handleLoadMore}>
- {loading ? t('common.loading') : t('mcp.catalog.loadMore')}
- </Button>
- </div>
- )}
- </>
- )}
- </div>
- );
-};
-
-export default McpCatalogBrowser;
diff --git a/app/src/components/channels/mcp/McpInventoryExportTab.tsx b/app/src/components/channels/mcp/McpInventoryExportTab.tsx
deleted file mode 100644
index 5f61780bb5..0000000000
--- a/app/src/components/channels/mcp/McpInventoryExportTab.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-/**
- * Export tab of the Sharable MCP Inventory panel.
- *
- * Renders the user's current installed MCP servers as a versioned,
- * secret-free manifest in a code block, with Copy and Download
- * actions. A loud privacy banner re-states what is and is not in the
- * manifest so the user sees it before sharing the artifact.
- */
-import { useMemo, useState } from 'react';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import Button from '../../ui/Button';
-import {
- buildManifest,
- type McpInventoryManifest,
- serializeManifest,
- suggestedFilename,
-} from './McpInventoryManifest';
-import type { InstalledServer } from './types';
-
-interface McpInventoryExportTabProps {
- servers: InstalledServer[];
-}
-
-const McpInventoryExportTab = ({ servers }: McpInventoryExportTabProps) => {
- const { t } = useT();
- const [copyStatus, setCopyStatus] = useState<'idle' | 'copied'>('idle');
-
- const manifest: McpInventoryManifest = useMemo(() => buildManifest(servers), [servers]);
- const serialized = useMemo(() => serializeManifest(manifest), [manifest]);
-
- if (servers.length === 0) {
- return (
- <p className="text-sm text-content-muted py-6 text-center">
- {t('mcp.inventory.export.empty')}
- </p>
- );
- }
-
- const handleCopy = async () => {
- if (typeof navigator === 'undefined' || !navigator.clipboard) return;
- try {
- await navigator.clipboard.writeText(serialized);
- setCopyStatus('copied');
- window.setTimeout(() => setCopyStatus('idle'), 1500);
- } catch {
- // Silently no-op on platforms / contexts without clipboard access.
- // The serialized text is visible and selectable in the <pre>.
- }
- };
-
- const handleDownload = () => {
- if (typeof document === 'undefined') return;
- const blob = new Blob([serialized], { type: 'application/json' });
- const url = URL.createObjectURL(blob);
- const link = document.createElement('a');
- link.href = url;
- link.download = suggestedFilename(manifest);
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- // Revoke after the click handler is done so the browser has a
- // chance to start the download.
- setTimeout(() => URL.revokeObjectURL(url), 0);
- };
-
- return (
- <div className="space-y-3">
- <div
- role="note"
- className="rounded-lg border border-sage-200 dark:border-sage-500/30 bg-sage-50 dark:bg-sage-500/10 px-3 py-2 text-xs text-content-secondary">
- <p className="font-medium mb-1">{t('mcp.inventory.export.privacyTitle')}</p>
- <p>{t('mcp.inventory.export.privacyBody')}</p>
- </div>
- <div className="flex items-center justify-between gap-2">
- <p className="text-xs text-content-muted">
- {t('mcp.inventory.export.serverCount').replace('{count}', String(servers.length))}
- </p>
- <div className="flex items-center gap-2">
- <Button
- variant="secondary"
- size="sm"
- onClick={() => void handleCopy()}
- aria-label={t('mcp.inventory.export.copyAria')}>
- {copyStatus === 'copied'
- ? t('mcp.inventory.export.copied')
- : t('mcp.inventory.export.copy')}
- </Button>
- <Button
- variant="primary"
- size="sm"
- onClick={handleDownload}
- aria-label={t('mcp.inventory.export.downloadAria')}>
- {t('mcp.inventory.export.download')}
- </Button>
- </div>
- </div>
- <pre
- data-testid="mcp-inventory-export-pre"
- className="max-h-80 overflow-auto rounded-lg border border-line bg-surface-muted p-3 text-[11px] font-mono text-content whitespace-pre-wrap wrap-break-word">
- {serialized}
- </pre>
- </div>
- );
-};
-
-export default McpInventoryExportTab;
diff --git a/app/src/components/channels/mcp/McpInventoryImportTab.test.tsx b/app/src/components/channels/mcp/McpInventoryImportTab.test.tsx
deleted file mode 100644
index ce0af6e6c3..0000000000
--- a/app/src/components/channels/mcp/McpInventoryImportTab.test.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { fireEvent, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { renderWithProviders } from '../../../test/test-utils';
-import McpInventoryImportTab from './McpInventoryImportTab';
-import { buildManifest, serializeManifest } from './McpInventoryManifest';
-import type { InstalledServer } from './types';
-
-const SERVER: InstalledServer = {
- server_id: 'srv-1',
- qualified_name: 'acme/db-server',
- display_name: 'DB Server',
- command_kind: 'node',
- command: 'npx',
- args: ['-y', 'acme/db-server'],
- env_keys: ['DB_URL'],
- installed_at: 1_700_000_000,
- enabled: true,
-};
-
-describe('<McpInventoryImportTab />', () => {
- it('renders the paste textarea, disables Preview until there is input', () => {
- renderWithProviders(<McpInventoryImportTab installedServers={[]} onInstallServer={vi.fn()} />);
- expect(screen.getByLabelText('Paste manifest JSON')).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Preview' })).toBeDisabled();
- });
-
- it('previews a pasted manifest and installs a new entry', () => {
- const onInstallServer = vi.fn();
- renderWithProviders(
- <McpInventoryImportTab installedServers={[]} onInstallServer={onInstallServer} />
- );
- const manifestText = serializeManifest(buildManifest([SERVER]));
- fireEvent.change(screen.getByLabelText('Paste manifest JSON'), {
- target: { value: manifestText },
- });
- fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
- expect(screen.getByRole('heading', { name: 'Preview' })).toBeInTheDocument();
-
- fireEvent.click(screen.getByRole('button', { name: 'Install DB Server from this manifest' }));
- expect(onInstallServer).toHaveBeenCalledWith('acme/db-server', { DB_URL: '' });
- });
-});
diff --git a/app/src/components/channels/mcp/McpInventoryImportTab.tsx b/app/src/components/channels/mcp/McpInventoryImportTab.tsx
deleted file mode 100644
index 42c8725b04..0000000000
--- a/app/src/components/channels/mcp/McpInventoryImportTab.tsx
+++ /dev/null
@@ -1,299 +0,0 @@
-/**
- * Import tab of the Sharable MCP Inventory panel.
- *
- * The flow is intentionally THREE-STEP and never auto-installs:
- *
- * 1. **Source** — user pastes JSON or uploads a file.
- * 2. **Preview** — manifest is parsed + validated; each entry is
- * classified (`new` vs `already_installed`); the validation error,
- * if any, is surfaced via `role="alert"`.
- * 3. **Per-entry install** — each `new` entry has its own "Install"
- * button that calls the parent's existing install-dialog flow with
- * the env_keys pre-filled (as empty values). We deliberately do
- * NOT collect secret values here — the proven InstallDialog
- * surface already handles that.
- *
- * No automatic bulk-install was implemented: an MCP server is a piece of
- * trust the user is granting to their agent. A one-click-install-many
- * action would invite supply-chain attacks via malicious manifests. The
- * per-entry "Install" preserves friction at exactly the right step.
- */
-import { type ChangeEvent, useCallback, useMemo, useState } from 'react';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import Button from '../../ui/Button';
-import TextArea from '../../ui/TextArea';
-import {
- type ClassifiedImportEntry,
- classifyImport,
- type McpInventoryManifest,
- type ParseErrorCode,
- parseManifest,
-} from './McpInventoryManifest';
-import type { InstalledServer } from './types';
-
-interface McpInventoryImportTabProps {
- installedServers: InstalledServer[];
- onInstallServer: (qualifiedName: string, prefillEnv: Record<string, string>) => void;
-}
-
-const McpInventoryImportTab = ({
- installedServers,
- onInstallServer,
-}: McpInventoryImportTabProps) => {
- const { t } = useT();
- const [rawInput, setRawInput] = useState('');
- const [manifest, setManifest] = useState<McpInventoryManifest | null>(null);
- const [parseError, setParseError] = useState<string | null>(null);
- const [fileError, setFileError] = useState<string | null>(null);
-
- const classified: ClassifiedImportEntry[] = useMemo(
- () => (manifest ? classifyImport(manifest, installedServers) : []),
- [manifest, installedServers]
- );
-
- // Map a stable manifest-layer error code to the user-visible string.
- // Detail (machine context — JSON parse text, offending index, etc.)
- // is appended after a separator when present so the alert text reads
- // as one sentence.
- const renderParseError = useCallback(
- (errorCode: ParseErrorCode, detail?: string): string => {
- const base = t(`mcp.inventory.parseError.${errorCode}`);
- return detail ? `${base} (${detail})` : base;
- },
- [t]
- );
-
- const handleParse = useCallback(() => {
- setFileError(null);
- const result = parseManifest(rawInput);
- if (result.ok) {
- setManifest(result.manifest);
- setParseError(null);
- } else {
- setManifest(null);
- setParseError(renderParseError(result.errorCode, result.detail));
- }
- }, [rawInput, renderParseError]);
-
- const handleFileChange = useCallback(
- (event: ChangeEvent<HTMLInputElement>) => {
- const file = event.target.files?.[0];
- // Allow re-selecting the same file by clearing the input value.
- event.target.value = '';
- if (!file) return;
- if (file.size > 1_000_000) {
- // 1 MB is generous for a manifest (~10k servers at 100 bytes each).
- // Reject anything larger as a defence against accidental upload
- // of an unrelated big JSON blob. Clear any stale preview /
- // parse-error state so the rejected upload doesn't leave a
- // previous (and now misleading) preview actionable below.
- setManifest(null);
- setParseError(null);
- setFileError(t('mcp.inventory.import.fileTooLarge'));
- return;
- }
- setFileError(null);
- const reader = new FileReader();
- reader.onload = () => {
- const text = typeof reader.result === 'string' ? reader.result : '';
- setRawInput(text);
- const result = parseManifest(text);
- if (result.ok) {
- setManifest(result.manifest);
- setParseError(null);
- } else {
- setManifest(null);
- setParseError(renderParseError(result.errorCode, result.detail));
- }
- };
- reader.onerror = () => {
- // Same reasoning as the size-reject branch — drop any stale
- // preview so a failed re-upload doesn't leave the previous
- // manifest's preview rows still rendering / actionable.
- setManifest(null);
- setParseError(null);
- setFileError(t('mcp.inventory.import.fileReadFailed'));
- };
- reader.readAsText(file);
- },
- [t, renderParseError]
- );
-
- const handleClear = useCallback(() => {
- setRawInput('');
- setManifest(null);
- setParseError(null);
- setFileError(null);
- }, []);
-
- const handleInstall = useCallback(
- (entry: ClassifiedImportEntry['entry']) => {
- // Build the prefill object: keys from the manifest, empty values
- // for the user to fill in the existing InstallDialog. The dialog's
- // existing required-field validation does the rest.
- const prefill: Record<string, string> = {};
- for (const key of entry.env_keys) prefill[key] = '';
- onInstallServer(entry.qualified_name, prefill);
- },
- [onInstallServer]
- );
-
- const stats = useMemo(() => {
- let newly = 0;
- let already = 0;
- for (const c of classified) {
- if (c.status === 'new') newly += 1;
- else already += 1;
- }
- return { newly, already, total: classified.length };
- }, [classified]);
-
- return (
- <div className="space-y-3">
- <div
- role="note"
- className="rounded-lg border border-amber-200 dark:border-amber-500/30 bg-amber-50 dark:bg-amber-500/10 px-3 py-2 text-xs text-content-secondary">
- <p className="font-medium mb-1">{t('mcp.inventory.import.trustTitle')}</p>
- <p>{t('mcp.inventory.import.trustBody')}</p>
- </div>
-
- <div className="space-y-1.5">
- <label
- htmlFor="mcp-inventory-import-textarea"
- className="text-xs font-medium text-content-secondary">
- {t('mcp.inventory.import.pasteLabel')}
- </label>
- <TextArea
- id="mcp-inventory-import-textarea"
- value={rawInput}
- onChange={e => {
- setRawInput(e.target.value);
- // Live-clear stale parse errors so the user sees a clean
- // slate as they edit; they'll re-appear on "Preview".
- setParseError(null);
- }}
- spellCheck={false}
- rows={6}
- placeholder={t('mcp.inventory.import.pastePlaceholder')}
- aria-label={t('mcp.inventory.import.pasteLabel')}
- className="w-full font-mono text-xs focus:border-primary-400 focus:ring-primary-400"
- />
- </div>
-
- <div className="flex items-center justify-between gap-2 flex-wrap">
- <div className="flex items-center gap-2">
- <Button
- variant="primary"
- size="sm"
- onClick={handleParse}
- disabled={rawInput.trim().length === 0}>
- {t('mcp.inventory.import.preview')}
- </Button>
- {(manifest || parseError || rawInput.length > 0) && (
- <Button variant="secondary" size="sm" onClick={handleClear}>
- {t('mcp.inventory.import.clear')}
- </Button>
- )}
- </div>
- <label className="text-xs text-primary-600 dark:text-primary-300 cursor-pointer hover:underline">
- {t('mcp.inventory.import.uploadFile')}
- <input
- type="file"
- accept="application/json,.json"
- onChange={handleFileChange}
- className="sr-only"
- aria-label={t('mcp.inventory.import.uploadFileAria')}
- />
- </label>
- </div>
-
- {fileError && (
- <p role="alert" className="text-[11px] text-coral-700 dark:text-coral-300">
- {fileError}
- </p>
- )}
- {parseError && (
- <p role="alert" className="text-[11px] text-coral-700 dark:text-coral-300">
- {t('mcp.inventory.import.parseErrorPrefix')} {parseError}
- </p>
- )}
-
- {manifest && (
- <section aria-labelledby="mcp-inventory-import-preview-heading" className="space-y-2">
- <h3
- id="mcp-inventory-import-preview-heading"
- className="text-xs font-semibold text-content-secondary">
- {t('mcp.inventory.import.previewHeading')}
- </h3>
- <div role="status" aria-live="polite" className="text-[11px] text-content-muted">
- {t('mcp.inventory.import.previewCounts')
- .replace('{total}', String(stats.total))
- .replace('{newly}', String(stats.newly))
- .replace('{already}', String(stats.already))}
- </div>
- <div className="text-[10px] text-content-faint">
- {t('mcp.inventory.import.exportedFrom').replace('{exporter}', manifest.exported_by)} ·{' '}
- {t('mcp.inventory.import.exportedAt').replace('{when}', manifest.exported_at)}
- </div>
- {classified.length === 0 ? (
- <p className="text-xs text-content-muted">{t('mcp.inventory.import.previewEmpty')}</p>
- ) : (
- <ul className="space-y-1">
- {classified.map(({ entry, status }) => (
- <li
- key={entry.qualified_name}
- className="flex items-center justify-between gap-2 rounded-lg border border-line px-3 py-2">
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <span
- className={`inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-semibold uppercase tracking-wider shrink-0 ${
- status === 'new'
- ? 'bg-sage-100 dark:bg-sage-500/20 text-sage-700 dark:text-sage-300'
- : 'bg-surface-subtle text-content-secondary'
- }`}>
- {status === 'new'
- ? t('mcp.inventory.import.statusNew')
- : t('mcp.inventory.import.statusAlreadyInstalled')}
- </span>
- <span className="text-sm font-medium text-content truncate">
- {entry.display_name}
- </span>
- </div>
- <p className="text-[11px] font-mono text-content-faint truncate">
- {entry.qualified_name}
- </p>
- {entry.env_keys.length > 0 && (
- <p className="text-[10px] text-content-muted mt-0.5">
- {t('mcp.inventory.import.envKeysLabel')}: {entry.env_keys.join(', ')}
- </p>
- )}
- </div>
- {status === 'new' ? (
- <Button
- variant="primary"
- size="xs"
- onClick={() => handleInstall(entry)}
- aria-label={t('mcp.inventory.import.installAria').replace(
- '{name}',
- entry.display_name
- )}
- className="shrink-0">
- {t('mcp.inventory.import.install')}
- </Button>
- ) : (
- <span className="shrink-0 text-[10px] text-content-faint italic">
- {t('mcp.inventory.import.skipped')}
- </span>
- )}
- </li>
- ))}
- </ul>
- )}
- </section>
- )}
- </div>
- );
-};
-
-export default McpInventoryImportTab;
diff --git a/app/src/components/channels/mcp/McpInventoryManifest.test.ts b/app/src/components/channels/mcp/McpInventoryManifest.test.ts
deleted file mode 100644
index 334d79d67b..0000000000
--- a/app/src/components/channels/mcp/McpInventoryManifest.test.ts
+++ /dev/null
@@ -1,364 +0,0 @@
-/**
- * Tests for the McpInventoryManifest helpers. Pure-data layer — no React.
- *
- * The redaction contract is the most security-relevant invariant in the
- * whole inventory feature; the tests below pin it from both directions:
- * - `buildManifest` must NEVER include `server_id`, `installed_at`,
- * `last_connected_at`, `command`, `args`, `command_kind`, or any
- * `env` value.
- * - `parseManifest` must REJECT any input that smuggles back an `env`
- * map (or other shape violations).
- */
-import { describe, expect, it } from 'vitest';
-
-import {
- buildManifest,
- classifyImport,
- CURRENT_MANIFEST_SCHEMA,
- parseManifest,
- serializeManifest,
- suggestedFilename,
-} from './McpInventoryManifest';
-import type { InstalledServer } from './types';
-
-const SERVER_FS: InstalledServer = {
- server_id: 'srv-uuid-1',
- qualified_name: 'acme/fs-server',
- display_name: 'File Server',
- description: 'Reads files',
- icon_url: 'https://example.com/icon.png',
- command_kind: 'node',
- command: 'npx',
- args: ['-y', 'acme/fs-server'],
- env_keys: ['ROOT_DIR', 'API_KEY'],
- config: { region: 'us-east-1' },
- installed_at: 1_700_000_000,
- last_connected_at: 1_700_001_000,
- enabled: true,
-};
-
-const SERVER_DB: InstalledServer = {
- server_id: 'srv-uuid-2',
- qualified_name: 'acme/db-server',
- display_name: 'DB Server',
- description: undefined,
- command_kind: 'node',
- command: 'npx',
- args: ['-y', 'acme/db-server'],
- env_keys: ['DB_URL'],
- installed_at: 1_700_000_500,
- enabled: true,
-};
-
-describe('McpInventoryManifest: buildManifest', () => {
- it('returns the documented schema sentinel', () => {
- const m = buildManifest([]);
- expect(m.$schema).toBe(CURRENT_MANIFEST_SCHEMA);
- });
-
- it('uses an ISO-8601 timestamp for exported_at', () => {
- const m = buildManifest([]);
- // Loose check — anything `new Date()` accepts back must be valid.
- expect(Number.isNaN(Date.parse(m.exported_at))).toBe(false);
- });
-
- it('honours an explicit exported_by label', () => {
- const m = buildManifest([SERVER_FS], 'my-machine');
- expect(m.exported_by).toBe('my-machine');
- });
-
- it('defaults exported_by to "openhuman-desktop"', () => {
- const m = buildManifest([SERVER_FS]);
- expect(m.exported_by).toBe('openhuman-desktop');
- });
-
- it('redacts per-machine identifiers (server_id, installed_at, last_connected_at)', () => {
- const m = buildManifest([SERVER_FS]);
- const entry = m.servers[0];
- expect('server_id' in entry).toBe(false);
- expect('installed_at' in entry).toBe(false);
- expect('last_connected_at' in entry).toBe(false);
- });
-
- it('redacts transient spawn shape (command, args, command_kind)', () => {
- const m = buildManifest([SERVER_FS]);
- const entry = m.servers[0];
- expect('command' in entry).toBe(false);
- expect('args' in entry).toBe(false);
- expect('command_kind' in entry).toBe(false);
- });
-
- it('NEVER exports an env value map (only env_keys / NAMES)', () => {
- const m = buildManifest([SERVER_FS]);
- const entry = m.servers[0];
- expect('env' in entry).toBe(false);
- // env_keys IS present and matches the input (with any sort).
- expect([...entry.env_keys].sort()).toEqual(['API_KEY', 'ROOT_DIR']);
- });
-
- it('sorts env_keys deterministically for diff-stability', () => {
- // Input is in declaration order; output should always be sorted.
- const m = buildManifest([SERVER_FS]);
- expect(m.servers[0].env_keys).toEqual(['API_KEY', 'ROOT_DIR']);
- });
-
- it('sorts servers by qualified_name for diff-stability', () => {
- // Input out of order; output sorted.
- const m = buildManifest([SERVER_FS, SERVER_DB]);
- expect(m.servers.map(s => s.qualified_name)).toEqual(['acme/db-server', 'acme/fs-server']);
- });
-
- it('omits description when absent (not serialised as null/undefined)', () => {
- const m = buildManifest([SERVER_DB]);
- expect('description' in m.servers[0]).toBe(false);
- });
-
- it('includes description when present', () => {
- const m = buildManifest([SERVER_FS]);
- expect(m.servers.find(s => s.qualified_name === 'acme/fs-server')?.description).toBe(
- 'Reads files'
- );
- });
-
- it('omits config when undefined or null; includes when present', () => {
- const m = buildManifest([SERVER_FS, SERVER_DB]);
- const fs = m.servers.find(s => s.qualified_name === 'acme/fs-server');
- const db = m.servers.find(s => s.qualified_name === 'acme/db-server');
- expect(fs?.config).toEqual({ region: 'us-east-1' });
- expect('config' in (db as object)).toBe(false);
- });
-
- it('handles a server with an undefined env_keys (defensive) without crashing', () => {
- const broken = { ...SERVER_DB, env_keys: undefined as unknown as string[] };
- const m = buildManifest([broken]);
- expect(m.servers[0].env_keys).toEqual([]);
- });
-});
-
-describe('McpInventoryManifest: serializeManifest', () => {
- it('produces pretty-printed JSON with a trailing newline', () => {
- const m = buildManifest([SERVER_FS]);
- const text = serializeManifest(m);
- expect(text.endsWith('\n')).toBe(true);
- // Must parse back to an equivalent object.
- expect(JSON.parse(text).$schema).toBe(CURRENT_MANIFEST_SCHEMA);
- });
-
- it('byte-identical for repeated exports of the same input', () => {
- // Hold time constant via a fixed exporter label since exported_at
- // moves naturally; we test stable shape modulo timestamp.
- const a = buildManifest([SERVER_FS, SERVER_DB], 'fixed');
- const b = buildManifest([SERVER_DB, SERVER_FS], 'fixed');
- // Different declaration order in input, identical sorted output.
- expect(a.servers).toEqual(b.servers);
- });
-});
-
-describe('McpInventoryManifest: parseManifest', () => {
- const validRaw = serializeManifest(buildManifest([SERVER_FS, SERVER_DB]));
-
- it('round-trips: build → serialize → parse yields equivalent servers', () => {
- const result = parseManifest(validRaw);
- if (!result.ok) throw new Error(`expected ok, got: ${result.errorCode}`);
- expect(result.manifest.$schema).toBe(CURRENT_MANIFEST_SCHEMA);
- expect(result.manifest.servers.map(s => s.qualified_name)).toEqual([
- 'acme/db-server',
- 'acme/fs-server',
- ]);
- });
-
- it('rejects empty input with the "empty" code', () => {
- expect(parseManifest('')).toEqual({ ok: false, errorCode: 'empty' });
- expect(parseManifest(' ')).toEqual({ ok: false, errorCode: 'empty' });
- });
-
- it('rejects non-JSON input with the "invalidJson" code and a detail string', () => {
- const result = parseManifest('{not json');
- expect(result.ok).toBe(false);
- if (!result.ok) {
- expect(result.errorCode).toBe('invalidJson');
- // Detail carries the underlying JSON parse exception message.
- expect(typeof result.detail).toBe('string');
- }
- });
-
- it('rejects non-object root with the "rootNotObject" code', () => {
- for (const raw of ['[]', '"a string"', 'null']) {
- const r = parseManifest(raw);
- expect(r.ok).toBe(false);
- if (!r.ok) expect(r.errorCode).toBe('rootNotObject');
- }
- });
-
- it('rejects an unknown / mismatched $schema with the "unsupportedSchema" code', () => {
- const result = parseManifest(JSON.stringify({ $schema: 'something-else', servers: [] }));
- expect(result.ok).toBe(false);
- if (!result.ok) {
- expect(result.errorCode).toBe('unsupportedSchema');
- expect(result.detail).toContain('something-else');
- }
- });
-
- it('rejects missing exported_at / exported_by with the correct codes', () => {
- const r1 = parseManifest(JSON.stringify({ $schema: CURRENT_MANIFEST_SCHEMA, servers: [] }));
- expect(r1.ok).toBe(false);
- if (!r1.ok) expect(r1.errorCode).toBe('missingExportedAt');
- const r2 = parseManifest(
- JSON.stringify({ $schema: CURRENT_MANIFEST_SCHEMA, exported_at: '2026-05-25', servers: [] })
- );
- expect(r2.ok).toBe(false);
- if (!r2.ok) expect(r2.errorCode).toBe('missingExportedBy');
- });
-
- it('treats a blank or whitespace-only exported_by as missing', () => {
- for (const blank of ['', ' ', '\t\n']) {
- const result = parseManifest(
- JSON.stringify({
- $schema: CURRENT_MANIFEST_SCHEMA,
- exported_at: '2026-05-25T00:00:00Z',
- exported_by: blank,
- servers: [],
- })
- );
- expect(result.ok).toBe(false);
- if (!result.ok) expect(result.errorCode).toBe('missingExportedBy');
- }
- });
-
- it('rejects a non-array servers field with the "invalidServers" code', () => {
- const result = parseManifest(
- JSON.stringify({
- $schema: CURRENT_MANIFEST_SCHEMA,
- exported_at: '2026-05-25T00:00:00Z',
- exported_by: 'x',
- servers: 'not-an-array',
- })
- );
- expect(result.ok).toBe(false);
- if (!result.ok) expect(result.errorCode).toBe('invalidServers');
- });
-
- it('rejects entries missing qualified_name with the matching code', () => {
- const result = parseManifest(
- JSON.stringify({
- $schema: CURRENT_MANIFEST_SCHEMA,
- exported_at: '2026-05-25T00:00:00Z',
- exported_by: 'x',
- servers: [{ display_name: 'X', env_keys: [] }],
- })
- );
- expect(result.ok).toBe(false);
- if (!result.ok) expect(result.errorCode).toBe('serverMissingQualifiedName');
- });
-
- it('rejects entries whose env_keys is not an array of strings', () => {
- const result = parseManifest(
- JSON.stringify({
- $schema: CURRENT_MANIFEST_SCHEMA,
- exported_at: '2026-05-25T00:00:00Z',
- exported_by: 'x',
- servers: [{ qualified_name: 'a/b', display_name: 'AB', env_keys: [1, 2, 3] }],
- })
- );
- expect(result.ok).toBe(false);
- if (!result.ok) expect(result.errorCode).toBe('serverEnvKeysNotArray');
- });
-
- // The single most important security test in the file:
- it('SECURITY: refuses any manifest that smuggles an `env` value map', () => {
- const malicious = JSON.stringify({
- $schema: CURRENT_MANIFEST_SCHEMA,
- exported_at: '2026-05-25T00:00:00Z',
- exported_by: 'attacker',
- servers: [
- {
- qualified_name: 'evil/server',
- display_name: 'Evil',
- env_keys: ['API_KEY'],
- env: { API_KEY: 'attacker-supplied-secret-value' },
- },
- ],
- });
- const result = parseManifest(malicious);
- expect(result.ok).toBe(false);
- if (!result.ok) expect(result.errorCode).toBe('serverContainsEnv');
- });
-
- it('rejects manifests containing a duplicate qualified_name with the matching code', () => {
- const dup = JSON.stringify({
- $schema: CURRENT_MANIFEST_SCHEMA,
- exported_at: '2026-05-25T00:00:00Z',
- exported_by: 'x',
- servers: [
- { qualified_name: 'a/b', display_name: 'First', env_keys: [] },
- { qualified_name: 'a/b', display_name: 'Second', env_keys: [] },
- ],
- });
- const result = parseManifest(dup);
- expect(result.ok).toBe(false);
- if (!result.ok) {
- expect(result.errorCode).toBe('duplicateQualifiedName');
- // Detail includes the offending qualified_name for diagnosability.
- expect(result.detail).toContain('a/b');
- }
- });
-
- it('omits optional fields cleanly on parse (no undefined leaks)', () => {
- const minimal = JSON.stringify({
- $schema: CURRENT_MANIFEST_SCHEMA,
- exported_at: '2026-05-25T00:00:00Z',
- exported_by: 'x',
- servers: [{ qualified_name: 'a/b', display_name: 'AB', env_keys: [] }],
- });
- const result = parseManifest(minimal);
- if (!result.ok) throw new Error(result.errorCode);
- const e = result.manifest.servers[0];
- expect('description' in e).toBe(false);
- expect('config' in e).toBe(false);
- });
-});
-
-describe('McpInventoryManifest: classifyImport', () => {
- const manifest = buildManifest([SERVER_FS, SERVER_DB]);
-
- it('classifies each entry as new or already_installed by qualified_name', () => {
- const classified = classifyImport(manifest, [
- // Pretend SERVER_FS is already installed locally; SERVER_DB is not.
- { ...SERVER_FS },
- ]);
- const byName = Object.fromEntries(classified.map(c => [c.entry.qualified_name, c.status]));
- expect(byName['acme/fs-server']).toBe('already_installed');
- expect(byName['acme/db-server']).toBe('new');
- });
-
- it('returns all as "new" when nothing is installed locally', () => {
- const classified = classifyImport(manifest, []);
- expect(classified.every(c => c.status === 'new')).toBe(true);
- });
-
- it('returns all as "already_installed" when every manifest entry exists locally', () => {
- const classified = classifyImport(manifest, [SERVER_FS, SERVER_DB]);
- expect(classified.every(c => c.status === 'already_installed')).toBe(true);
- });
-
- it('preserves manifest entry order in the classified output', () => {
- const classified = classifyImport(manifest, []);
- // Manifest is sorted by qualified_name; classification preserves that.
- expect(classified.map(c => c.entry.qualified_name)).toEqual([
- 'acme/db-server',
- 'acme/fs-server',
- ]);
- });
-});
-
-describe('McpInventoryManifest: suggestedFilename', () => {
- it('produces a slug-style filename including a timestamp', () => {
- const m = buildManifest([SERVER_FS]);
- const name = suggestedFilename(m);
- expect(name.startsWith('openhuman-mcp-inventory-')).toBe(true);
- expect(name.endsWith('.json')).toBe(true);
- // Stamp must contain only digits (no T, no -, no :, no .).
- const stamp = name.replace('openhuman-mcp-inventory-', '').replace('.json', '');
- expect(/^\d+$/.test(stamp)).toBe(true);
- });
-});
diff --git a/app/src/components/channels/mcp/McpInventoryManifest.ts b/app/src/components/channels/mcp/McpInventoryManifest.ts
deleted file mode 100644
index e7e59b66fb..0000000000
--- a/app/src/components/channels/mcp/McpInventoryManifest.ts
+++ /dev/null
@@ -1,275 +0,0 @@
-/**
- * Sharable MCP Inventory — portable, versioned, secret-free manifest of
- * installed MCP servers.
- *
- * The shape is intentionally NOT just `InstalledServer[]`:
- *
- * - `server_id` is per-machine (UUID) and would mean nothing on the
- * importer's host. Stripped on export.
- * - `installed_at` / `last_connected_at` are local-time observability
- * fields irrelevant to the importer. Stripped.
- * - `env` *values* are SECRETS. Only the `env_keys` (NAMES) make the
- * manifest. The importer fills values per-server.
- * - `command` / `args` are intentionally NOT carried — the importer's
- * core decides how to spawn from the upstream registry entry. This
- * keeps manifests portable across `npx` / `uvx` upgrades and avoids
- * baking transient command shapes into shared artifacts.
- *
- * The schema field (`$schema`) is a string sentinel rather than a URL
- * so the manifest is fully self-contained and can be validated offline.
- * Bump `CURRENT_MANIFEST_VERSION` if the shape changes.
- */
-import type { InstalledServer } from './types';
-
-/**
- * Sentinel embedded in every exported manifest. Importer rejects any
- * payload whose `$schema` does not match exactly.
- */
-export const CURRENT_MANIFEST_SCHEMA = 'openhuman.mcp-inventory.v1' as const;
-
-/**
- * Per-server entry in the exported manifest. No secrets, no per-machine
- * identifiers. Optional fields are omitted when absent (NOT serialised as
- * `null` / `undefined`) to keep manifests stable across re-exports.
- */
-export interface McpInventoryEntry {
- qualified_name: string;
- display_name: string;
- description?: string;
- /** ENV variable NAMES (not values). The importer collects values. */
- env_keys: string[];
- /** Free-form non-secret config blob the server may need. */
- config?: unknown;
-}
-
-export interface McpInventoryManifest {
- $schema: typeof CURRENT_MANIFEST_SCHEMA;
- /** ISO-8601 UTC timestamp captured at export time. */
- exported_at: string;
- /** Free-form label for the exporting environment (host, user, env). */
- exported_by: string;
- servers: McpInventoryEntry[];
-}
-
-/**
- * Build the export entry for one installed server. Centralised here so
- * the redaction contract ("no secret values, no per-machine ids") is
- * stated exactly once and tested exactly once.
- */
-const toEntry = (server: InstalledServer): McpInventoryEntry => {
- const entry: McpInventoryEntry = {
- qualified_name: server.qualified_name,
- display_name: server.display_name,
- env_keys: Array.isArray(server.env_keys) ? [...server.env_keys].sort() : [],
- };
- if (server.description) entry.description = server.description;
- if (server.config !== undefined && server.config !== null) entry.config = server.config;
- return entry;
-};
-
-/** Produce a manifest object from a list of installed servers. */
-export function buildManifest(
- servers: InstalledServer[],
- exportedBy = 'openhuman-desktop'
-): McpInventoryManifest {
- return {
- $schema: CURRENT_MANIFEST_SCHEMA,
- exported_at: new Date().toISOString(),
- exported_by: exportedBy,
- // Sort by qualified_name for deterministic output (re-exporting the
- // same set twice produces byte-identical manifests, which makes
- // them diff-friendly in source control).
- servers: servers.map(toEntry).sort((a, b) => a.qualified_name.localeCompare(b.qualified_name)),
- };
-}
-
-/** Pretty-print a manifest to JSON suitable for clipboard / download. */
-export function serializeManifest(manifest: McpInventoryManifest): string {
- return `${JSON.stringify(manifest, null, 2)}\n`;
-}
-
-/**
- * Stable, locale-independent identifiers for every parse-failure mode.
- *
- * Mapped to translated text by the consumer (UI) via
- * `mcp.inventory.parseError.<code>` i18n keys — so the manifest layer
- * stays decoupled from any presentation locale, and the failure modes
- * are a fixed contract that external tooling (CLIs, test fixtures,
- * other clients) can match on without depending on the rendered text.
- */
-export type ParseErrorCode =
- | 'empty'
- | 'invalidJson'
- | 'rootNotObject'
- | 'unsupportedSchema'
- | 'missingExportedAt'
- | 'missingExportedBy'
- | 'invalidServers'
- | 'serverNotObject'
- | 'serverMissingQualifiedName'
- | 'serverMissingDisplayName'
- | 'serverEnvKeysNotArray'
- | 'serverContainsEnv'
- | 'duplicateQualifiedName';
-
-/**
- * Discriminated-union result of parsing a manifest. On failure carries
- * a stable `errorCode` for i18n + an optional `detail` string with
- * machine context (JSON parse exception text, offending index, the
- * actual schema string we got, etc.). Consumers render via
- * `t(\`mcp.inventory.parseError.\${errorCode}\`)` + optional detail.
- */
-type ParseResult =
- | { ok: true; manifest: McpInventoryManifest }
- | { ok: false; errorCode: ParseErrorCode; detail?: string };
-
-const isObject = (value: unknown): value is Record<string, unknown> =>
- typeof value === 'object' && value !== null && !Array.isArray(value);
-
-const isStringArray = (value: unknown): value is string[] =>
- Array.isArray(value) && value.every(v => typeof v === 'string');
-
-/**
- * Parse + validate a raw manifest string. Returns a discriminated union
- * with a stable `errorCode` on failure — never throws. Tolerant of
- * trailing whitespace; strict on the rest. Includes a duplicate-
- * `qualified_name` check so a malformed/malicious manifest can't
- * quietly install the same server twice with diverging env_keys.
- */
-export function parseManifest(raw: string): ParseResult {
- if (typeof raw !== 'string' || raw.trim().length === 0) {
- return { ok: false, errorCode: 'empty' };
- }
- let parsed: unknown;
- try {
- parsed = JSON.parse(raw);
- } catch (err) {
- return {
- ok: false,
- errorCode: 'invalidJson',
- detail: err instanceof Error ? err.message : undefined,
- };
- }
- if (!isObject(parsed)) {
- return { ok: false, errorCode: 'rootNotObject' };
- }
- if (parsed.$schema !== CURRENT_MANIFEST_SCHEMA) {
- return {
- ok: false,
- errorCode: 'unsupportedSchema',
- detail: `expected "${CURRENT_MANIFEST_SCHEMA}", got "${String(parsed.$schema)}"`,
- };
- }
- if (typeof parsed.exported_at !== 'string' || parsed.exported_at.length === 0) {
- return { ok: false, errorCode: 'missingExportedAt' };
- }
- if (typeof parsed.exported_by !== 'string' || parsed.exported_by.trim().length === 0) {
- // Blank/whitespace-only `exported_by` is treated as missing: the field
- // is observability metadata (which host/user produced the manifest)
- // and an empty value would render as "Exported from " in the preview.
- return { ok: false, errorCode: 'missingExportedBy' };
- }
- if (!Array.isArray(parsed.servers)) {
- return { ok: false, errorCode: 'invalidServers' };
- }
- const servers: McpInventoryEntry[] = [];
- // Track qualified_names we've already accepted, so a manifest that
- // lists the same server twice (with possibly diverging env_keys or
- // config) is rejected up-front rather than silently producing two
- // import rows that would both call install on the same upstream id.
- const seenQualifiedNames = new Set<string>();
- for (let i = 0; i < parsed.servers.length; i += 1) {
- const raw = parsed.servers[i];
- if (!isObject(raw)) {
- return { ok: false, errorCode: 'serverNotObject', detail: `servers[${i}]` };
- }
- if (typeof raw.qualified_name !== 'string' || raw.qualified_name.length === 0) {
- return { ok: false, errorCode: 'serverMissingQualifiedName', detail: `servers[${i}]` };
- }
- if (seenQualifiedNames.has(raw.qualified_name)) {
- return {
- ok: false,
- errorCode: 'duplicateQualifiedName',
- detail: `servers[${i}]: "${raw.qualified_name}"`,
- };
- }
- seenQualifiedNames.add(raw.qualified_name);
- if (typeof raw.display_name !== 'string' || raw.display_name.length === 0) {
- return { ok: false, errorCode: 'serverMissingDisplayName', detail: `servers[${i}]` };
- }
- if (!isStringArray(raw.env_keys)) {
- return { ok: false, errorCode: 'serverEnvKeysNotArray', detail: `servers[${i}]` };
- }
- // Pre-import safety net — refuse manifests that smuggle in an `env`
- // map. (The exporter never writes one, but an attacker / leaked
- // file might. We want NO path where parseManifest hands the
- // importer concrete secret values.)
- if ('env' in raw) {
- return { ok: false, errorCode: 'serverContainsEnv', detail: `servers[${i}]` };
- }
- const entry: McpInventoryEntry = {
- qualified_name: raw.qualified_name,
- display_name: raw.display_name,
- env_keys: raw.env_keys,
- };
- if (typeof raw.description === 'string') entry.description = raw.description;
- if ('config' in raw && raw.config !== undefined && raw.config !== null) {
- entry.config = raw.config;
- }
- servers.push(entry);
- }
- return {
- ok: true,
- manifest: {
- $schema: CURRENT_MANIFEST_SCHEMA,
- exported_at: parsed.exported_at,
- exported_by: parsed.exported_by,
- servers,
- },
- };
-}
-
-/**
- * Per-entry import classification. The Import UI uses these statuses to
- * colour-code the preview table and decide whether to surface an
- * "Install" action.
- */
-export type ImportEntryStatus = 'new' | 'already_installed';
-
-export interface ClassifiedImportEntry {
- entry: McpInventoryEntry;
- status: ImportEntryStatus;
-}
-
-/**
- * Cross-reference each manifest entry against the importer's current
- * installed servers (by `qualified_name`) to classify what would happen
- * on install. Stable order: matches the manifest's input order.
- */
-export function classifyImport(
- manifest: McpInventoryManifest,
- installed: InstalledServer[]
-): ClassifiedImportEntry[] {
- const installedNames = new Set(installed.map(s => s.qualified_name));
- return manifest.servers.map(entry => ({
- entry,
- status: installedNames.has(entry.qualified_name) ? 'already_installed' : 'new',
- }));
-}
-
-/** Suggested default filename for browser-side download. */
-export function suggestedFilename(manifest: McpInventoryManifest): string {
- // exported_at is "2026-05-25T20:14:15.123Z"; trim to a filename-safe
- // YYYYMMDDHHMMSS slug so the file sorts well in directory listings.
- //
- // The character class is built from a String.fromCharCode array rather
- // than a literal regex character class because Tailwind v4's content
- // scanner greps every JS/TS source string for arbitrary-value class
- // shapes and would mis-identify the literal as a Tailwind class,
- // emitting an invalid CSS rule that fails `lightningcss minify` during
- // the Tauri production build.
- const SEPARATORS = String.fromCharCode(45, 58, 84); // '-', ':', 'T'
- const stripPattern = new RegExp('[' + SEPARATORS + ']', 'g');
- const stamp = manifest.exported_at.replace(stripPattern, '').replace(/\..*$/, '');
- return `openhuman-mcp-inventory-${stamp}.json`;
-}
diff --git a/app/src/components/channels/mcp/McpInventoryPanel.test.tsx b/app/src/components/channels/mcp/McpInventoryPanel.test.tsx
deleted file mode 100644
index 6898cd4a19..0000000000
--- a/app/src/components/channels/mcp/McpInventoryPanel.test.tsx
+++ /dev/null
@@ -1,483 +0,0 @@
-/**
- * Tests for McpInventoryPanel + its Export / Import tab children.
- *
- * Strategy: drive the whole panel via the parent's public surface
- * (servers prop, onInstallServer, onClose) so the test asserts the
- * actual user-visible behaviour rather than internal state shape.
- */
-import { act, fireEvent, render, screen, within } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { buildManifest, CURRENT_MANIFEST_SCHEMA, serializeManifest } from './McpInventoryManifest';
-import McpInventoryPanel from './McpInventoryPanel';
-import type { InstalledServer } from './types';
-
-/**
- * Radix registers its outside-pointer listener in a macrotask, so the render
- * that opened the dialog cannot immediately be dismissed by it — flush first.
- * Same helper as `ui/ModalShell.test.tsx`.
- */
-async function flushDeferredWork(): Promise<void> {
- await new Promise(resolve => setTimeout(resolve, 0));
-}
-
-/**
- * Radix treats an outside interaction as pointerdown *followed by* a click.
- */
-function dismissByOutsideClick(overlay: HTMLElement): void {
- fireEvent.pointerDown(overlay);
- fireEvent.click(overlay);
-}
-
-const SERVER_FS: InstalledServer = {
- server_id: 'srv-uuid-1',
- qualified_name: 'acme/fs-server',
- display_name: 'File Server',
- description: 'Reads files',
- command_kind: 'node',
- command: 'npx',
- args: ['-y', 'acme/fs-server'],
- env_keys: ['ROOT_DIR'],
- installed_at: 1_700_000_000,
- enabled: true,
-};
-
-const SERVER_DB: InstalledServer = {
- server_id: 'srv-uuid-2',
- qualified_name: 'acme/db-server',
- display_name: 'DB Server',
- command_kind: 'node',
- command: 'npx',
- args: ['-y', 'acme/db-server'],
- env_keys: ['DB_URL'],
- installed_at: 1_700_000_500,
- enabled: true,
-};
-
-const renderPanel = (overrides?: {
- servers?: InstalledServer[];
- onInstallServer?: (qualifiedName: string, prefillEnv: Record<string, string>) => void;
- onClose?: () => void;
-}) =>
- render(
- <McpInventoryPanel
- servers={overrides?.servers ?? [SERVER_FS, SERVER_DB]}
- onInstallServer={overrides?.onInstallServer ?? (() => {})}
- onClose={overrides?.onClose ?? (() => {})}
- />
- );
-
-describe('McpInventoryPanel — shell', () => {
- it('renders as an accessible modal dialog with the title labelling it', () => {
- renderPanel();
- const dialog = screen.getByRole('dialog');
- // Migrated onto the shared `ModalShell` / Radix `Dialog`
- // (#radix-ui-foundation): this build's Radix Dialog.Content doesn't stamp
- // an `aria-modal` attribute (the real focus-trap + inert-background
- // behavior is still there), so this only asserts the `aria-labelledby`
- // contract the test actually cares about.
- expect(dialog).toHaveAttribute('aria-labelledby');
- expect(screen.getByText('Sharable MCP Inventory')).toBeInTheDocument();
- });
-
- it('Esc closes via onClose', () => {
- const onClose = vi.fn();
- renderPanel({ onClose });
- act(() => {
- fireEvent.keyDown(document, { key: 'Escape' });
- });
- expect(onClose).toHaveBeenCalledTimes(1);
- });
-
- it('close button calls onClose', () => {
- const onClose = vi.fn();
- renderPanel({ onClose });
- // Migrated onto `ModalShell`: the close button is now the shell's own,
- // labelled with the common "Close" string rather than the hand-rolled
- // "Close inventory panel" label.
- fireEvent.click(screen.getByRole('button', { name: 'Close' }));
- expect(onClose).toHaveBeenCalledTimes(1);
- });
-
- it('outside click closes; click on dialog card does not', async () => {
- const onClose = vi.fn();
- renderPanel({ onClose });
- const overlay = document.querySelector('[data-slot="dialog-overlay"]') as HTMLElement;
- expect(overlay).not.toBeNull();
- await flushDeferredWork();
- dismissByOutsideClick(overlay);
- expect(onClose).toHaveBeenCalledTimes(1);
- // A click on a descendant must NOT close.
- fireEvent.pointerDown(screen.getByText('Sharable MCP Inventory'));
- fireEvent.click(screen.getByText('Sharable MCP Inventory'));
- expect(onClose).toHaveBeenCalledTimes(1);
- });
-
- it('renders the Export tab by default and exposes both tabs', () => {
- renderPanel();
- const exportTab = screen.getByRole('tab', { name: 'Export' });
- const importTab = screen.getByRole('tab', { name: 'Import' });
- expect(exportTab).toHaveAttribute('aria-selected', 'true');
- expect(importTab).toHaveAttribute('aria-selected', 'false');
- });
-
- it('switches to the Import tab on click', () => {
- renderPanel();
- // Migrated onto Radix `Tabs` (#radix-ui-foundation): its trigger switches
- // on `mousedown`, not `click` (so it activates on the same gesture as
- // real pointer-driven browsers, before the click's mouseup) — `fireEvent`
- // has to fire the event Radix actually listens for.
- fireEvent.mouseDown(screen.getByRole('tab', { name: 'Import' }));
- expect(screen.getByRole('tab', { name: 'Import' })).toHaveAttribute('aria-selected', 'true');
- expect(screen.getByRole('tab', { name: 'Export' })).toHaveAttribute('aria-selected', 'false');
- });
-});
-
-describe('McpInventoryPanel — Export tab', () => {
- it('renders the empty state when there are no installed servers', () => {
- renderPanel({ servers: [] });
- expect(screen.getByText(/Install one from the catalog first/)).toBeInTheDocument();
- });
-
- it('renders the manifest JSON in the preview <pre> when servers exist', () => {
- renderPanel({ servers: [SERVER_FS] });
- const pre = screen.getByTestId('mcp-inventory-export-pre');
- expect(pre.textContent).toContain(`"$schema": "${CURRENT_MANIFEST_SCHEMA}"`);
- expect(pre.textContent).toContain('"qualified_name": "acme/fs-server"');
- expect(pre.textContent).toContain('"env_keys"');
- // The preview MUST NOT contain server_id, command, args, etc.
- expect(pre.textContent).not.toContain('"server_id"');
- expect(pre.textContent).not.toContain('"installed_at"');
- expect(pre.textContent).not.toContain('"command"');
- });
-
- it('renders the server count', () => {
- renderPanel({ servers: [SERVER_FS, SERVER_DB] });
- expect(screen.getByText('2 servers in this manifest')).toBeInTheDocument();
- });
-
- it('renders the privacy banner verbatim', () => {
- renderPanel({ servers: [SERVER_FS] });
- expect(screen.getByText('What is in this manifest')).toBeInTheDocument();
- expect(
- screen.getByText(/env-variable KEY NAMES, and non-secret config only/)
- ).toBeInTheDocument();
- });
-
- it('Download button creates a Blob URL, triggers a click on a hidden link, and revokes', async () => {
- const createObjectURL = vi.fn().mockReturnValue('blob:fake-url-123');
- const revokeObjectURL = vi.fn();
- const originalCreate = URL.createObjectURL;
- const originalRevoke = URL.revokeObjectURL;
- URL.createObjectURL = createObjectURL;
- URL.revokeObjectURL = revokeObjectURL;
- const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
- try {
- renderPanel({ servers: [SERVER_FS] });
- fireEvent.click(screen.getByRole('button', { name: /Download the manifest/ }));
- expect(createObjectURL).toHaveBeenCalledTimes(1);
- const blobArg = createObjectURL.mock.calls[0][0] as Blob;
- expect(blobArg.type).toBe('application/json');
- expect(clickSpy).toHaveBeenCalledTimes(1);
- // handleDownload defers revokeObjectURL via setTimeout(..., 0); flush.
- await new Promise(resolve => setTimeout(resolve, 0));
- expect(revokeObjectURL).toHaveBeenCalledWith('blob:fake-url-123');
- } finally {
- URL.createObjectURL = originalCreate;
- URL.revokeObjectURL = originalRevoke;
- clickSpy.mockRestore();
- }
- });
-
- it('Copy button writes the serialized manifest to the clipboard', async () => {
- const writeText = vi.fn().mockResolvedValue(undefined);
- const originalClipboard = (navigator as { clipboard?: unknown }).clipboard;
- Object.defineProperty(navigator, 'clipboard', {
- writable: true,
- configurable: true,
- value: { writeText },
- });
- try {
- renderPanel({ servers: [SERVER_FS] });
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: /Copy the manifest JSON/ }));
- });
- expect(writeText).toHaveBeenCalledTimes(1);
- const arg = writeText.mock.calls[0][0] as string;
- expect(arg).toContain(`"$schema": "${CURRENT_MANIFEST_SCHEMA}"`);
- expect(arg).toContain('"qualified_name": "acme/fs-server"');
- } finally {
- if (originalClipboard === undefined) {
- delete (navigator as { clipboard?: unknown }).clipboard;
- } else {
- Object.defineProperty(navigator, 'clipboard', {
- writable: true,
- configurable: true,
- value: originalClipboard,
- });
- }
- }
- });
-});
-
-describe('McpInventoryPanel — Import tab', () => {
- beforeEach(() => {
- // Each test starts on the Export tab by default. Most Import-tab
- // tests want to jump straight to Import; the per-test setup does so.
- });
-
- const switchToImport = () => {
- // Radix `Tabs.Trigger` activates on `mousedown`, not `click`.
- fireEvent.mouseDown(screen.getByRole('tab', { name: 'Import' }));
- };
-
- it('renders the trust banner', () => {
- renderPanel();
- switchToImport();
- expect(screen.getByText('Treat imported manifests as untrusted code')).toBeInTheDocument();
- });
-
- it('Preview button is disabled until the textarea has content', () => {
- renderPanel();
- switchToImport();
- expect(screen.getByRole('button', { name: 'Preview' })).toBeDisabled();
- fireEvent.change(screen.getByLabelText('Paste manifest JSON'), { target: { value: '{}' } });
- expect(screen.getByRole('button', { name: 'Preview' })).not.toBeDisabled();
- });
-
- it('shows a role=alert with the parse-error prefix when the JSON is invalid', () => {
- renderPanel();
- switchToImport();
- fireEvent.change(screen.getByLabelText('Paste manifest JSON'), {
- target: { value: '{not valid' },
- });
- fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
- const alert = screen.getByRole('alert');
- expect(alert.textContent).toMatch(/Could not parse manifest:/);
- });
-
- it('shows a role=alert when an unknown $schema is presented', () => {
- renderPanel();
- switchToImport();
- fireEvent.change(screen.getByLabelText('Paste manifest JSON'), {
- target: {
- value: JSON.stringify({
- $schema: 'wrong',
- exported_at: '2026-05-25T00:00:00Z',
- exported_by: 'x',
- servers: [],
- }),
- },
- });
- fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
- expect(screen.getByRole('alert').textContent).toMatch(/Unsupported manifest schema/);
- });
-
- it('SECURITY: refuses a manifest that smuggles an env value map and surfaces a clear alert', () => {
- renderPanel();
- switchToImport();
- fireEvent.change(screen.getByLabelText('Paste manifest JSON'), {
- target: {
- value: JSON.stringify({
- $schema: CURRENT_MANIFEST_SCHEMA,
- exported_at: '2026-05-25T00:00:00Z',
- exported_by: 'attacker',
- servers: [
- {
- qualified_name: 'evil/server',
- display_name: 'Evil',
- env_keys: ['SECRET'],
- env: { SECRET: 'attacker-value' },
- },
- ],
- }),
- },
- });
- fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
- expect(screen.getByRole('alert').textContent).toMatch(/secret values/i);
- // Critically: no Install button should have been rendered for the rejected entry.
- expect(screen.queryByRole('button', { name: /Install Evil/ })).not.toBeInTheDocument();
- });
-
- it('previews a valid manifest with a per-entry status row', () => {
- const valid = serializeManifest(buildManifest([SERVER_FS, SERVER_DB]));
- renderPanel({ servers: [SERVER_FS] }); // SERVER_FS already installed; SERVER_DB is new
- switchToImport();
- fireEvent.change(screen.getByLabelText('Paste manifest JSON'), { target: { value: valid } });
- fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
-
- // Heading + counts live region
- expect(screen.getByRole('heading', { name: 'Preview' })).toBeInTheDocument();
- const status = screen.getByRole('status', { hidden: true });
- // The summary should mention 2 total — 1 new, 1 already installed.
- expect(status.textContent).toMatch(/2 servers/);
- expect(status.textContent).toMatch(/1 new/);
- expect(status.textContent).toMatch(/1 already installed/);
-
- // SERVER_DB row has an Install button; SERVER_FS row is skipped.
- expect(
- screen.getByRole('button', { name: 'Install DB Server from this manifest' })
- ).toBeInTheDocument();
- expect(screen.queryByRole('button', { name: /Install File Server/ })).not.toBeInTheDocument();
- });
-
- it('clicking Install hands the qualified_name + empty env prefill to onInstallServer', () => {
- const onInstallServer = vi.fn();
- const valid = serializeManifest(buildManifest([SERVER_DB]));
- renderPanel({ servers: [], onInstallServer });
- switchToImport();
- fireEvent.change(screen.getByLabelText('Paste manifest JSON'), { target: { value: valid } });
- fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
-
- fireEvent.click(screen.getByRole('button', { name: 'Install DB Server from this manifest' }));
- expect(onInstallServer).toHaveBeenCalledTimes(1);
- expect(onInstallServer).toHaveBeenCalledWith('acme/db-server', { DB_URL: '' });
- });
-
- it('clicking Install also closes the panel (handoff to the existing InstallDialog flow)', () => {
- const onClose = vi.fn();
- const valid = serializeManifest(buildManifest([SERVER_DB]));
- renderPanel({ servers: [], onClose });
- switchToImport();
- fireEvent.change(screen.getByLabelText('Paste manifest JSON'), { target: { value: valid } });
- fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
- fireEvent.click(screen.getByRole('button', { name: 'Install DB Server from this manifest' }));
- expect(onClose).toHaveBeenCalledTimes(1);
- });
-
- it('Clear button resets the textarea, preview, and any parse error', () => {
- renderPanel();
- switchToImport();
- const textarea = screen.getByLabelText('Paste manifest JSON');
- fireEvent.change(textarea, { target: { value: '{bad' } });
- fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
- expect(screen.getByRole('alert')).toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { name: 'Clear' }));
- expect(textarea).toHaveValue('');
- expect(screen.queryByRole('alert')).not.toBeInTheDocument();
- });
-
- it('typing in the textarea live-clears a stale parse error', () => {
- renderPanel();
- switchToImport();
- const textarea = screen.getByLabelText('Paste manifest JSON');
- fireEvent.change(textarea, { target: { value: '{bad' } });
- fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
- expect(screen.getByRole('alert')).toBeInTheDocument();
- fireEvent.change(textarea, { target: { value: '{better-typing' } });
- expect(screen.queryByRole('alert')).not.toBeInTheDocument();
- });
-
- it('the empty-manifest case shows a helpful message and no Install buttons', () => {
- const emptyManifest = serializeManifest(buildManifest([]));
- renderPanel();
- switchToImport();
- fireEvent.change(screen.getByLabelText('Paste manifest JSON'), {
- target: { value: emptyManifest },
- });
- fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
- expect(screen.getByText('Manifest contains no servers.')).toBeInTheDocument();
- expect(screen.queryByRole('button', { name: /Install/ })).not.toBeInTheDocument();
- });
-
- it('shows env_keys for each preview row when present', () => {
- const valid = serializeManifest(buildManifest([SERVER_FS]));
- renderPanel({ servers: [] });
- switchToImport();
- fireEvent.change(screen.getByLabelText('Paste manifest JSON'), { target: { value: valid } });
- fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
- // The env_keys for SERVER_FS is just ['ROOT_DIR']
- const previewSection = screen.getByRole('heading', { name: 'Preview' }).closest('section')!;
- expect(within(previewSection).getByText(/ROOT_DIR/)).toBeInTheDocument();
- });
-
- // The file-upload paths are tested via a controllable FileReader stub so
- // we can drive onload/onerror deterministically; jsdom's built-in
- // FileReader works on File but doesn't fire events synchronously in a
- // way that aligns with the synchronous fireEvent/expect cycle here.
- it('uploading a valid JSON file populates the textarea and previews it', async () => {
- const valid = serializeManifest(buildManifest([SERVER_DB]));
- const OriginalFileReader = window.FileReader;
- class StubReader {
- onload: ((this: FileReader, ev: ProgressEvent<FileReader>) => unknown) | null = null;
- onerror: ((this: FileReader, ev: ProgressEvent<FileReader>) => unknown) | null = null;
- result: string | ArrayBuffer | null = null;
- readAsText(_: Blob) {
- this.result = valid;
- if (this.onload)
- this.onload.call(this as unknown as FileReader, {} as ProgressEvent<FileReader>);
- }
- }
- (window as unknown as { FileReader: unknown }).FileReader = StubReader;
- try {
- renderPanel({ servers: [] });
- switchToImport();
- const fileInput = screen.getByLabelText('Upload a manifest .json file') as HTMLInputElement;
- const file = new File([valid], 'manifest.json', { type: 'application/json' });
- await act(async () => {
- fireEvent.change(fileInput, { target: { files: [file] } });
- });
- expect(screen.getByLabelText('Paste manifest JSON')).toHaveValue(valid);
- // Preview was rendered automatically by the onload's parseManifest call.
- expect(screen.getByRole('heading', { name: 'Preview' })).toBeInTheDocument();
- expect(
- screen.getByRole('button', { name: 'Install DB Server from this manifest' })
- ).toBeInTheDocument();
- } finally {
- (window as unknown as { FileReader: unknown }).FileReader = OriginalFileReader;
- }
- });
-
- it('uploading a file larger than 1 MB is refused with a file-error alert and clears any prior preview', () => {
- renderPanel({ servers: [] });
- switchToImport();
- // Stage a valid preview first so we can assert that the refused upload
- // clears it (per the stale-state-clearing contract in handleFileChange).
- const valid = serializeManifest(buildManifest([SERVER_DB]));
- fireEvent.change(screen.getByLabelText('Paste manifest JSON'), { target: { value: valid } });
- fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
- expect(screen.getByRole('heading', { name: 'Preview' })).toBeInTheDocument();
-
- const fileInput = screen.getByLabelText('Upload a manifest .json file') as HTMLInputElement;
- // 1.5 MB sparse File — `size` is what handleFileChange gates on.
- const big = new File([new Uint8Array(1_500_000)], 'big.json', { type: 'application/json' });
- fireEvent.change(fileInput, { target: { files: [big] } });
- const alert = screen.getByRole('alert');
- expect(alert.textContent).toMatch(/too large/i);
- // Stale preview is gone.
- expect(screen.queryByRole('heading', { name: 'Preview' })).not.toBeInTheDocument();
- });
-
- it('FileReader onerror surfaces a file-read-failed alert and clears any prior preview', async () => {
- const OriginalFileReader = window.FileReader;
- class FailingReader {
- onload: ((this: FileReader, ev: ProgressEvent<FileReader>) => unknown) | null = null;
- onerror: ((this: FileReader, ev: ProgressEvent<FileReader>) => unknown) | null = null;
- readAsText(_: Blob) {
- if (this.onerror)
- this.onerror.call(this as unknown as FileReader, {} as ProgressEvent<FileReader>);
- }
- }
- (window as unknown as { FileReader: unknown }).FileReader = FailingReader;
- try {
- renderPanel({ servers: [] });
- switchToImport();
- // Stage a valid preview to confirm it's wiped on read failure.
- const valid = serializeManifest(buildManifest([SERVER_DB]));
- fireEvent.change(screen.getByLabelText('Paste manifest JSON'), { target: { value: valid } });
- fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
- expect(screen.getByRole('heading', { name: 'Preview' })).toBeInTheDocument();
-
- const fileInput = screen.getByLabelText('Upload a manifest .json file') as HTMLInputElement;
- const file = new File(['anything'], 'broken.json', { type: 'application/json' });
- await act(async () => {
- fireEvent.change(fileInput, { target: { files: [file] } });
- });
- const alert = screen.getByRole('alert');
- expect(alert.textContent).toMatch(/Could not read file/i);
- expect(screen.queryByRole('heading', { name: 'Preview' })).not.toBeInTheDocument();
- } finally {
- (window as unknown as { FileReader: unknown }).FileReader = OriginalFileReader;
- }
- });
-});
diff --git a/app/src/components/channels/mcp/McpInventoryPanel.tsx b/app/src/components/channels/mcp/McpInventoryPanel.tsx
deleted file mode 100644
index 3bd63ff58a..0000000000
--- a/app/src/components/channels/mcp/McpInventoryPanel.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * Sharable MCP Inventory — top-level modal hosting Export / Import tabs.
- *
- * The parent (`McpServersTab`) holds the open/close state and the
- * current `servers` array; this component owns the tab navigation and
- * dispatches the install-via-existing-dialog flow back upward.
- *
- * Why a single modal with tabs (rather than two separate modals):
- * - The user often flips between "let me see what I have" (Export)
- * and "let me apply what someone sent" (Import) in the same
- * session — tabbing is faster than re-opening.
- * - The dialog focus contract (`role="dialog" aria-modal`) is
- * simpler to maintain on a single mount.
- *
- * Esc closes the modal; backdrop mousedown closes; clicks inside the
- * card do not.
- */
-import { useId, useState } from 'react';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import ChipTabs from '../../layout/ChipTabs';
-import { ModalShell } from '../../ui/ModalShell';
-import McpInventoryExportTab from './McpInventoryExportTab';
-import McpInventoryImportTab from './McpInventoryImportTab';
-import type { InstalledServer } from './types';
-
-interface McpInventoryPanelProps {
- /** Current installed servers — drives the Export tab and the
- * "already installed" detection in the Import tab. */
- servers: InstalledServer[];
- /**
- * Called when the user clicks "Install" on an entry in the Import
- * preview. Parent wires this to its existing install-dialog flow
- * (`setRightPane({ mode: 'install', qualifiedName, prefillEnv })`)
- * so the proven InstallDialog handles env-value collection — we
- * never re-implement that critical surface here.
- */
- onInstallServer: (qualifiedName: string, prefillEnv: Record<string, string>) => void;
- onClose: () => void;
-}
-
-type Tab = 'export' | 'import';
-
-const McpInventoryPanel = ({ servers, onInstallServer, onClose }: McpInventoryPanelProps) => {
- const { t } = useT();
- const [tab, setTab] = useState<Tab>('export');
- const titleId = useId();
-
- return (
- <ModalShell
- onClose={onClose}
- titleId={titleId}
- title={t('mcp.inventory.title')}
- subtitle={t('mcp.inventory.subtitle')}
- maxWidthClassName="max-w-3xl"
- contentClassName="max-h-full overflow-y-auto p-5">
- {/* `ChipTabs` brings its own `TabsRoot` (as `display: contents`), so the
- panels cannot be Radix `TabsContent` — that would nest a second Tabs
- root and orphan them. A plain conditional is what the other ChipTabs
- hosts in this area already do. The row keeps `role="tab"` /
- `aria-selected` and Radix's roving focus; only the underline paint
- becomes the app's chip grammar. */}
- <ChipTabs<Tab>
- as="tab"
- ariaLabel={t('mcp.inventory.tablistAria')}
- className="mb-4 flex flex-wrap gap-1.5"
- items={[
- { id: 'export', label: t('mcp.inventory.tab.export') },
- { id: 'import', label: t('mcp.inventory.tab.import') },
- ]}
- value={tab}
- onChange={setTab}
- />
-
- {tab === 'export' ? (
- <McpInventoryExportTab servers={servers} />
- ) : (
- <McpInventoryImportTab
- installedServers={servers}
- onInstallServer={(qualifiedName, prefillEnv) => {
- // The parent's install flow lives outside this modal — close
- // the inventory panel so the InstallDialog has room to render
- // in the main right pane.
- onInstallServer(qualifiedName, prefillEnv);
- onClose();
- }}
- />
- )}
- </ModalShell>
- );
-};
-
-export default McpInventoryPanel;
diff --git a/app/src/components/channels/mcp/McpServerSearch.test.tsx b/app/src/components/channels/mcp/McpServerSearch.test.tsx
deleted file mode 100644
index 926de0820f..0000000000
--- a/app/src/components/channels/mcp/McpServerSearch.test.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * Tests for McpServerSearch — controlled filter input with clear button.
- */
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import McpServerSearch from './McpServerSearch';
-
-describe('McpServerSearch', () => {
- it('renders the search landmark with an accessible label', () => {
- render(<McpServerSearch value="" onChange={() => {}} />);
- const landmark = screen.getByRole('search', { name: 'Search installed MCP servers' });
- expect(landmark).toBeInTheDocument();
- });
-
- it('renders a search-type input with placeholder and aria-label', () => {
- render(<McpServerSearch value="" onChange={() => {}} />);
- const input = screen.getByRole('searchbox', { name: 'Filter installed MCP servers by name' });
- expect(input).toHaveAttribute('type', 'search');
- expect(input).toHaveAttribute('placeholder', 'Filter servers…');
- });
-
- it('does not render the clear button when value is empty', () => {
- render(<McpServerSearch value="" onChange={() => {}} />);
- expect(screen.queryByRole('button', { name: 'Clear filter' })).not.toBeInTheDocument();
- });
-
- it('renders the clear button when value is non-empty', () => {
- render(<McpServerSearch value="redis" onChange={() => {}} />);
- expect(screen.getByRole('button', { name: 'Clear filter' })).toBeInTheDocument();
- });
-
- it('reflects the current value as the input value', () => {
- render(<McpServerSearch value="redis" onChange={() => {}} />);
- expect(
- screen.getByRole('searchbox', { name: 'Filter installed MCP servers by name' })
- ).toHaveValue('redis');
- });
-
- it('fires onChange with the new value on typing', () => {
- const onChange = vi.fn();
- render(<McpServerSearch value="" onChange={onChange} />);
- const input = screen.getByRole('searchbox', { name: 'Filter installed MCP servers by name' });
- fireEvent.change(input, { target: { value: 'gh' } });
- expect(onChange).toHaveBeenCalledWith('gh');
- });
-
- it('fires onChange with an empty string when the clear button is clicked', () => {
- const onChange = vi.fn();
- render(<McpServerSearch value="redis" onChange={onChange} />);
- fireEvent.click(screen.getByRole('button', { name: 'Clear filter' }));
- expect(onChange).toHaveBeenCalledWith('');
- });
-
- it('renders the clear icon as decorative (aria-hidden)', () => {
- const { container } = render(<McpServerSearch value="x" onChange={() => {}} />);
- // The svg inside the clear button must be aria-hidden so the button's
- // own aria-label is the sole accessible name.
- const svg = container.querySelector('button[aria-label="Clear filter"] svg');
- expect(svg).not.toBeNull();
- expect(svg).toHaveAttribute('aria-hidden', 'true');
- });
-});
diff --git a/app/src/components/channels/mcp/McpServerSearch.tsx b/app/src/components/channels/mcp/McpServerSearch.tsx
deleted file mode 100644
index 630aebf165..0000000000
--- a/app/src/components/channels/mcp/McpServerSearch.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * Filter input for the installed MCP server list.
- *
- * Controlled component — the parent (`McpServersTab`) owns the value
- * and pushes it into `InstalledServerList` as the `filter` prop. The
- * input exposes a clear button when non-empty and announces itself
- * as a `role="search"` landmark so assistive tech can jump to it.
- *
- * Intentionally has NO global keyboard shortcut binding (e.g. Cmd/Ctrl+K)
- * to avoid clashing with the app-wide CommandProvider in `App.tsx`.
- * Users focus the input by clicking or tabbing.
- */
-import { useT } from '../../../lib/i18n/I18nContext';
-import Button from '../../ui/Button';
-import TextField from '../../ui/TextField';
-
-interface McpServerSearchProps {
- value: string;
- onChange: (next: string) => void;
-}
-
-const McpServerSearch = ({ value, onChange }: McpServerSearchProps) => {
- const { t } = useT();
- const hasValue = value.length > 0;
- return (
- <div role="search" aria-label={t('mcp.installed.search.landmarkAria')} className="relative">
- <TextField
- type="search"
- inputSize="sm"
- value={value}
- onChange={e => onChange(e.target.value)}
- placeholder={t('mcp.installed.search.placeholder')}
- aria-label={t('mcp.installed.search.inputAria')}
- className="w-full pr-7 text-xs"
- />
- {hasValue && (
- <Button
- iconOnly
- variant="tertiary"
- size="xs"
- onClick={() => onChange('')}
- aria-label={t('mcp.installed.search.clearAria')}
- className="absolute right-1.5 top-1/2 -translate-y-1/2 h-auto w-auto rounded p-0.5 text-content-faint hover:bg-transparent hover:text-content-secondary">
- <svg
- className="w-3 h-3"
- fill="none"
- viewBox="0 0 24 24"
- stroke="currentColor"
- strokeWidth={2.5}
- aria-hidden="true">
- <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
- </svg>
- </Button>
- )}
- </div>
- );
-};
-
-export default McpServerSearch;
diff --git a/app/src/components/mcp-setup/SecretPromptDialog.test.tsx b/app/src/components/mcp-setup/SecretPromptDialog.test.tsx
deleted file mode 100644
index a1be581943..0000000000
--- a/app/src/components/mcp-setup/SecretPromptDialog.test.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import SecretPromptDialog from './SecretPromptDialog';
-
-const callCoreRpc = vi.fn();
-vi.mock('../../services/coreRpcClient', () => ({
- callCoreRpc: (...args: unknown[]) => callCoreRpc(...args),
-}));
-
-function dispatchRequest(detail: { refId: string; keyName: string; prompt: string }) {
- window.dispatchEvent(new CustomEvent('openhuman:mcp-setup-secret-requested', { detail }));
-}
-
-describe('SecretPromptDialog', () => {
- beforeEach(() => {
- callCoreRpc.mockReset();
- callCoreRpc.mockResolvedValue(undefined);
- });
-
- afterEach(() => {
- // The component cleans up its own listener on unmount via useEffect;
- // we don't need to remove the event listener manually here.
- });
-
- it('is hidden until an event is dispatched', () => {
- render(<SecretPromptDialog />);
- expect(screen.queryByRole('dialog')).toBeNull();
- });
-
- it('renders the prompt + key name when an event arrives', async () => {
- render(<SecretPromptDialog />);
- dispatchRequest({
- refId: 'secret://abc123',
- keyName: 'NOTION_API_KEY',
- prompt: 'Paste your Notion integration token.',
- });
- await screen.findByRole('dialog');
- expect(screen.getByText('NOTION_API_KEY')).toBeTruthy();
- expect(screen.getByText('Paste your Notion integration token.')).toBeTruthy();
- });
-
- it('submits the value via mcp_setup_submit_secret and dismisses', async () => {
- render(<SecretPromptDialog />);
- dispatchRequest({ refId: 'secret://abc123', keyName: 'TOKEN', prompt: '' });
- await screen.findByRole('dialog');
-
- const input = screen.getByLabelText(/^Value$/i);
- fireEvent.change(input, { target: { value: 'super-secret-value' } });
-
- const submit = screen.getByText(/^Submit$/);
- fireEvent.click(submit);
-
- await waitFor(() => {
- expect(callCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.mcp_setup_submit_secret',
- params: { ref_id: 'secret://abc123', value: 'super-secret-value' },
- });
- });
- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
- });
-
- it('renders input as type=password by default and toggles on Show/Hide', async () => {
- render(<SecretPromptDialog />);
- dispatchRequest({ refId: 'secret://abc', keyName: 'K', prompt: '' });
- await screen.findByRole('dialog');
-
- const input = screen.getByLabelText(/^Value$/i) as HTMLInputElement;
- expect(input.type).toBe('password');
-
- fireEvent.click(screen.getByText(/^Show$/));
- expect((screen.getByLabelText(/^Value$/i) as HTMLInputElement).type).toBe('text');
-
- fireEvent.click(screen.getByText(/^Hide$/));
- expect((screen.getByLabelText(/^Value$/i) as HTMLInputElement).type).toBe('password');
- });
-
- it('cancel does not call mcp_setup_submit_secret', async () => {
- render(<SecretPromptDialog />);
- dispatchRequest({ refId: 'secret://abc', keyName: 'K', prompt: '' });
- await screen.findByRole('dialog');
-
- fireEvent.click(screen.getByText(/^Cancel$/));
- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
- expect(callCoreRpc).not.toHaveBeenCalled();
- });
-
- it('submit button disabled when value is empty', async () => {
- render(<SecretPromptDialog />);
- dispatchRequest({ refId: 'secret://abc', keyName: 'K', prompt: '' });
- await screen.findByRole('dialog');
-
- const submit = screen.getByText(/^Submit$/) as HTMLButtonElement;
- expect(submit.disabled).toBe(true);
-
- const input = screen.getByLabelText(/^Value$/i);
- fireEvent.change(input, { target: { value: 'x' } });
- expect(submit.disabled).toBe(false);
- });
-
- it('surfaces submit errors without dismissing', async () => {
- callCoreRpc.mockRejectedValueOnce(new Error('boom'));
- render(<SecretPromptDialog />);
- dispatchRequest({ refId: 'secret://abc', keyName: 'K', prompt: '' });
- await screen.findByRole('dialog');
-
- const input = screen.getByLabelText(/^Value$/i);
- fireEvent.change(input, { target: { value: 'v' } });
- fireEvent.click(screen.getByText(/^Submit$/));
-
- await waitFor(() => expect(screen.getByText(/boom/)).toBeTruthy());
- // Dialog still open
- expect(screen.queryByRole('dialog')).not.toBeNull();
- });
-});
diff --git a/app/src/components/mcp-setup/SecretPromptDialog.tsx b/app/src/components/mcp-setup/SecretPromptDialog.tsx
deleted file mode 100644
index 5ab56f5d98..0000000000
--- a/app/src/components/mcp-setup/SecretPromptDialog.tsx
+++ /dev/null
@@ -1,170 +0,0 @@
-// Listens for `openhuman:mcp-setup-secret-requested` window events dispatched
-// by `socketService` and renders a native input dialog so the user can hand
-// the core a secret value out-of-band.
-//
-// The dialog deliberately uses `<input type="password">` so the value isn't
-// echoed in the UI by default and never lands in clipboard history via
-// triple-click. On submit, the value is POSTed straight to
-// `openhuman.mcp_setup_submit_secret` and immediately cleared from React
-// state — no logging, no Redux, no persistence on this side. The MCP setup
-// agent only sees the opaque `ref://<hex>` ref returned by
-// `mcp_setup_request_secret`; the raw value never enters the LLM context.
-import { useCallback, useEffect, useId, useState } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import { callCoreRpc } from '../../services/coreRpcClient';
-import { Button, ModalShell, TextField } from '../ui';
-
-type Request = { refId: string; keyName: string; prompt: string };
-
-function SecretPromptDialog() {
- const { t } = useT();
- const titleId = useId();
- const inputId = useId();
- const [request, setRequest] = useState<Request | null>(null);
- const [value, setValue] = useState('');
- const [reveal, setReveal] = useState(false);
- const [submitting, setSubmitting] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- useEffect(() => {
- const onRequest = (event: Event) => {
- const detail = (event as CustomEvent).detail as Request | undefined;
- if (!detail?.refId || !detail.keyName) return;
- setRequest(detail);
- setValue('');
- setReveal(false);
- setError(null);
- setSubmitting(false);
- };
- window.addEventListener('openhuman:mcp-setup-secret-requested', onRequest);
- return () => {
- window.removeEventListener('openhuman:mcp-setup-secret-requested', onRequest);
- };
- }, []);
-
- const reset = useCallback(() => {
- setRequest(null);
- setValue('');
- setReveal(false);
- setError(null);
- setSubmitting(false);
- }, []);
-
- const handleSubmit = useCallback(
- async (e: React.FormEvent) => {
- e.preventDefault();
- if (!request || submitting || value.length === 0) return;
- setSubmitting(true);
- setError(null);
- try {
- await callCoreRpc({
- method: 'openhuman.mcp_setup_submit_secret',
- params: { ref_id: request.refId, value },
- });
- // Wipe local state on success — the value has now moved into the
- // core's process-local SETUP_SECRETS map; React doesn't need a
- // copy. Closing the dialog also drops the React-tree reference.
- reset();
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- setError(msg);
- setSubmitting(false);
- }
- },
- [request, submitting, value, reset]
- );
-
- // Cancel: do NOT call mcp_setup_submit_secret. The agent-side
- // `request_secret` will hit its 5-minute timeout and return an error
- // the agent can surface to the user, which is the right outcome here.
- const handleCancel = useCallback(() => {
- if (submitting) return;
- reset();
- }, [submitting, reset]);
-
- if (!request) return null;
-
- return (
- <ModalShell
- onClose={handleCancel}
- title={t('mcp.setup.secretDialog.title')}
- titleId={titleId}
- closePolicy={{ escape: !submitting, backdrop: !submitting, button: !submitting }}
- contentClassName="px-0 py-0"
- footer={
- <div className="flex items-center justify-end gap-3">
- <Button variant="tertiary" onClick={handleCancel} disabled={submitting}>
- {t('mcp.setup.secretDialog.cancel')}
- </Button>
- <Button
- type="submit"
- form="mcp-setup-secret-form"
- disabled={submitting || value.length === 0}>
- {submitting
- ? t('mcp.setup.secretDialog.submitting')
- : t('mcp.setup.secretDialog.submit')}
- </Button>
- </div>
- }>
- <form id="mcp-setup-secret-form" onSubmit={handleSubmit}>
- <div className="px-6 pt-2 pb-4">
- <p className="text-sm text-content-secondary">
- {t('mcp.setup.secretDialog.bodyPrefix')}{' '}
- <code className="px-1.5 py-0.5 rounded bg-surface-subtle text-content font-mono text-xs">
- {request.keyName}
- </code>
- {t('mcp.setup.secretDialog.bodySuffix')}
- </p>
- {request.prompt && (
- <p className="text-sm text-content-secondary mt-3 whitespace-pre-wrap">
- {request.prompt}
- </p>
- )}
- </div>
-
- <div className="px-6 pb-2">
- <label
- htmlFor={inputId}
- className="block text-xs font-medium text-content-secondary mb-1">
- {t('mcp.setup.secretDialog.inputLabel')}
- </label>
- <div className="flex items-stretch gap-2">
- <TextField
- id={inputId}
- type={reveal ? 'text' : 'password'}
- autoComplete="off"
- autoCorrect="off"
- spellCheck={false}
- value={value}
- onChange={e => setValue(e.target.value)}
- placeholder={t('mcp.setup.secretDialog.inputPlaceholder')}
- mono
- className="flex-1"
- autoFocus
- disabled={submitting}
- />
- <Button
- type="button"
- variant="secondary"
- size="sm"
- onClick={() => setReveal(v => !v)}
- disabled={submitting}>
- {reveal ? t('mcp.setup.secretDialog.hide') : t('mcp.setup.secretDialog.show')}
- </Button>
- </div>
- <p className="text-[11px] text-content-muted mt-2">
- {t('mcp.setup.secretDialog.privacyNote')}
- </p>
- {error && (
- <p className="text-xs text-coral-500 mt-2">
- {t('mcp.setup.secretDialog.errorPrefix')} {error}
- </p>
- )}
- </div>
- </form>
- </ModalShell>
- );
-}
-
-export default SecretPromptDialog;
diff --git a/app/src/services/socketService.ts b/app/src/services/socketService.ts
index ebe7eea482..c3df5746d6 100644
--- a/app/src/services/socketService.ts
+++ b/app/src/services/socketService.ts
@@ -320,36 +320,6 @@ class SocketService {
this.socket.on('auth:session_expired', handleSessionExpired);
this.socket.on('auth_session_expired', handleSessionExpired);
- // MCP setup agent: server-side `request_secret` blocks until the
- // user submits a value. Dispatch a window event so a singleton React
- // dialog can render a native input and POST back via
- // openhuman.mcp_setup_submit_secret. Raw secret values never travel
- // through the socket — only the opaque ref + safe display fields.
- const handleSecretRequested = (data: unknown) => {
- const obj = data as Record<string, unknown> | null;
- if (!obj || typeof obj !== 'object') {
- socketWarn('mcp_setup:secret_requested dropped — invalid payload');
- return;
- }
- const refId = typeof obj.ref_id === 'string' ? obj.ref_id : null;
- const keyName = typeof obj.key_name === 'string' ? obj.key_name : null;
- const prompt = typeof obj.prompt === 'string' ? obj.prompt : '';
- if (!refId || !keyName) {
- socketWarn('mcp_setup:secret_requested missing ref_id or key_name');
- return;
- }
- socketLog('mcp_setup:secret_requested', { refId, keyName });
- if (typeof window !== 'undefined') {
- window.dispatchEvent(
- new CustomEvent('openhuman:mcp-setup-secret-requested', {
- detail: { refId, keyName, prompt },
- })
- );
- }
- };
- this.socket.on('mcp_setup:secret_requested', handleSecretRequested);
- this.socket.on('mcp_setup_secret_requested', handleSecretRequested);
-
this.socket.on('memory:sync_stage', (data: unknown) => {
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('openhuman:memory-sync-stage', { detail: data }));
diff --git a/app/src/utils/toolTimelineFormatting.ts b/app/src/utils/toolTimelineFormatting.ts
index 86fc4166b6..a10cc5d5ea 100644
--- a/app/src/utils/toolTimelineFormatting.ts
+++ b/app/src/utils/toolTimelineFormatting.ts
@@ -64,11 +64,6 @@ const TOOL_DISPLAY_NAMES: Record<string, string> = {
mcp_list_servers: 'Listing MCP servers',
mcp_list_tools: 'Listing MCP tools',
mcp_call_tool: 'Calling MCP tool',
- mcp_setup_search: 'Searching MCP tools',
- mcp_setup_get: 'Getting MCP tool',
- mcp_setup_install_and_connect: 'Installing MCP server',
- mcp_setup_request_secret: 'Requesting secret',
- mcp_setup_test_connection: 'Testing connection',
gmail_unsubscribe: 'Unsubscribing',
gitbooks_get_page: 'Reading docs page',
audio_generate_podcast: 'Generating podcast',