Skip to content

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

feat(mcp): add hosted servers from the Registry in one click (#7194)

oxoxDev89627141d597
diff --git a/app/src/components/channels/mcp/McpRegistryBrowser.test.tsx b/app/src/components/channels/mcp/McpRegistryBrowser.test.tsx
index 4f7101e233..072b24490b 100644
--- a/app/src/components/channels/mcp/McpRegistryBrowser.test.tsx
+++ b/app/src/components/channels/mcp/McpRegistryBrowser.test.tsx
@@ -1,19 +1,56 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { useState } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import McpRegistryBrowser, { deriveRepoUrl, serverPageUrl } from './McpRegistryBrowser';
+import type { InstalledServer } from './types';
const mockRegistrySearch = vi.fn();
+const mockRegistryGet = vi.fn();
+const mockConfigGet = vi.fn();
+const mockConfigSet = vi.fn();
+const mockInstalledList = vi.fn();
+const mockDetectAuth = vi.fn();
+const mockConnect = vi.fn();
const mockOpenUrl = vi.fn();
vi.mock('../../../services/api/mcpClientsApi', () => ({
- mcpClientsApi: { registrySearch: (...args: unknown[]) => mockRegistrySearch(...args) },
+ mcpClientsApi: {
+ registrySearch: (...args: unknown[]) => mockRegistrySearch(...args),
+ registryGet: (...args: unknown[]) => mockRegistryGet(...args),
+ configGet: (...args: unknown[]) => mockConfigGet(...args),
+ configSet: (...args: unknown[]) => mockConfigSet(...args),
+ installedList: (...args: unknown[]) => mockInstalledList(...args),
+ detectAuth: (...args: unknown[]) => mockDetectAuth(...args),
+ connect: (...args: unknown[]) => mockConnect(...args),
+ },
}));
vi.mock('../../../utils/openUrl', () => ({
openUrl: (...args: unknown[]) => mockOpenUrl(...args),
}));
+vi.mock('./ConnectAuthModal', () => ({
+ default: ({
+ server,
+ onClose,
+ onConnected,
+ }: {
+ server: InstalledServer;
+ onClose: () => void;
+ onConnected: (tools: unknown[]) => void;
+ }) => (
+ <div role="dialog" aria-label={`Sign in to ${server.display_name}`}>
+ <button type="button" onClick={() => onConnected([])}>
+ stub-connected
+ </button>
+ <button type="button" onClick={onClose}>
+ stub-close
+ </button>
+ </div>
+ ),
+}));
+
const SERVERS = [
{
qualified_name: 'io.github.acme/echo',
@@ -29,14 +66,70 @@ const SERVERS = [
website_url: 'https://hosted.example',
source: 'mcp_official',
},
+ {
+ qualified_name: 'vendor/keyed',
+ display_name: 'Keyed',
+ is_deployed: true,
+ source: 'mcp_official',
+ auth_kind: 'api_key',
+ },
+ {
+ qualified_name: 'smithery/hosted',
+ display_name: 'Smithery Hosted',
+ is_deployed: true,
+ source: 'smithery',
+ },
{ qualified_name: 'installed/already', display_name: 'Already Declared', source: 'smithery' },
];
+const HOSTED_NAME = 'vendor/hosted-thing';
+
+const installedRow = (qualified_name: string): InstalledServer => ({
+ server_id: `srv-${qualified_name}`,
+ qualified_name,
+ display_name: qualified_name,
+ command_kind: 'node',
+ command: '',
+ args: [],
+ env_keys: [],
+ installed_at: 1,
+ transport: { kind: 'http_remote', url: 'https://hosted.example/mcp' },
+ enabled: true,
+});
+
+const hostedDetail = (deployment_url = 'https://hosted.example/mcp') => ({
+ ...SERVERS[1],
+ connections: [{ type: 'http', deployment_url }],
+ required_env_keys: [],
+});
+
+const onDeclaredSpy = vi.fn();
+
+/** Mirrors the tab: re-reading the installed list marks the row declared. */
+const Harness = ({ initial = ['installed/already'] }: { initial?: string[] }) => {
+ const [names, setNames] = useState<ReadonlySet<string>>(() => new Set(initial));
+ return (
+ <McpRegistryBrowser
+ installedNames={names}
+ onDeclared={async () => {
+ onDeclaredSpy();
+ const rows = (await mockInstalledList()) as InstalledServer[];
+ setNames(new Set(rows.map(r => r.qualified_name)));
+ }}
+ />
+ );
+};
+
+const rowFor = (name: string) =>
+ screen
+ .getAllByTestId('mcp-registry-row')
+ .find(row => within(row).queryByText(name, { exact: true })) as HTMLElement;
+
describe('serverPageUrl', () => {
it('prefers the declared website, then the repository, then the directory listing', () => {
expect(serverPageUrl(SERVERS[1])).toBe('https://hosted.example');
expect(serverPageUrl(SERVERS[0])).toBe('https://github.com/acme/echo');
- expect(serverPageUrl(SERVERS[2])).toBe('https://smithery.ai/server/installed/already');
+ expect(serverPageUrl(SERVERS[4])).toBe('https://smithery.ai/server/installed/already');
expect(serverPageUrl({ qualified_name: 'com.vendor/x', display_name: 'X' })).toBe(
'https://registry.modelcontextprotocol.io/?search=com.vendor%2Fx'
);
@@ -51,27 +144,193 @@ describe('serverPageUrl', () => {
describe('McpRegistryBrowser', () => {
beforeEach(() => {
- mockRegistrySearch.mockReset();
- mockOpenUrl.mockReset();
+ for (const mock of [
+ mockRegistrySearch,
+ mockRegistryGet,
+ mockConfigGet,
+ mockConfigSet,
+ mockInstalledList,
+ mockDetectAuth,
+ mockConnect,
+ mockOpenUrl,
+ onDeclaredSpy,
+ ]) {
+ mock.mockReset();
+ }
mockOpenUrl.mockResolvedValue(undefined);
mockRegistrySearch.mockResolvedValue({ servers: SERVERS, page: 1, total_pages: 1 });
+ mockRegistryGet.mockResolvedValue(hostedDetail());
+ mockConfigGet.mockResolvedValue({ mcpServers: { 'installed/already': { command: 'npx' } } });
+ mockConfigSet.mockResolvedValue({ mcpServers: {}, added: [], updated: [], removed: [] });
+ mockInstalledList.mockResolvedValue([
+ installedRow('installed/already'),
+ installedRow(HOSTED_NAME),
+ ]);
+ mockDetectAuth.mockResolvedValue({ kind: 'none', grant_types: [] });
+ mockConnect.mockResolvedValue({
+ server_id: `srv-${HOSTED_NAME}`,
+ status: 'connected',
+ tools: [],
+ });
});
- it('lists the directory minus already-declared servers, and opens a row in the browser', async () => {
- render(<McpRegistryBrowser installedNames={new Set(['installed/already'])} />);
+ it('offers Add for open hosted rows, Added for declared ones and Open page for the rest', async () => {
+ render(<Harness />);
const rows = await screen.findAllByTestId('mcp-registry-row');
- expect(rows).toHaveLength(2);
- expect(screen.queryByText('Already Declared')).not.toBeInTheDocument();
- // No install control anywhere: the row's action is to open the page.
- expect(screen.queryByText('Install')).not.toBeInTheDocument();
- expect(screen.getAllByText(/Open page/)).toHaveLength(2);
+ expect(rows).toHaveLength(5);
+
+ expect(
+ within(rowFor('Hosted Thing')).getByRole('button', { name: 'Add Hosted Thing' })
+ ).toBeEnabled();
+ expect(
+ within(rowFor('Already Declared')).getByRole('button', { name: /Added/ })
+ ).toBeDisabled();
+ for (const name of ['Echo', 'Keyed', 'Smithery Hosted']) {
+ expect(
+ within(rowFor(name)).getByRole('button', { name: `Open the page for ${name}` })
+ ).toBeInTheDocument();
+ }
fireEvent.click(screen.getByRole('button', { name: 'Open the page for Echo' }));
expect(mockOpenUrl).toHaveBeenCalledWith('https://github.com/acme/echo');
});
+ it('declares an open hosted server, re-reads the rows, connects it and shows Added', async () => {
+ render(<Harness />);
+ await screen.findAllByTestId('mcp-registry-row');
+ fireEvent.click(screen.getByRole('button', { name: 'Add Hosted Thing' }));
+
+ await waitFor(() => expect(mockConnect).toHaveBeenCalledWith(`srv-${HOSTED_NAME}`));
+ expect(mockRegistryGet).toHaveBeenCalledWith(HOSTED_NAME);
+ expect(mockConfigSet).toHaveBeenCalledWith({
+ mcpServers: {
+ 'installed/already': { command: 'npx' },
+ [HOSTED_NAME]: { url: 'https://hosted.example/mcp' },
+ },
+ });
+ expect(onDeclaredSpy).toHaveBeenCalledTimes(1);
+ expect(mockDetectAuth).toHaveBeenCalledWith(`srv-${HOSTED_NAME}`);
+ await waitFor(() =>
+ expect(within(rowFor('Hosted Thing')).getByRole('button', { name: /Added/ })).toBeDisabled()
+ );
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ });
+
+ it('opens the sign-in dialog when the server asks for OAuth', async () => {
+ mockDetectAuth.mockResolvedValue({ kind: 'oauth', grant_types: ['authorization_code'] });
+ render(<Harness />);
+ await screen.findAllByTestId('mcp-registry-row');
+ fireEvent.click(screen.getByRole('button', { name: 'Add Hosted Thing' }));
+
+ expect(
+ await screen.findByRole('dialog', { name: `Sign in to ${HOSTED_NAME}` })
+ ).toBeInTheDocument();
+ expect(mockConnect).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'stub-connected' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ expect(onDeclaredSpy).toHaveBeenCalledTimes(2);
+ });
+
+ it('opens the sign-in dialog when the auth probe fails', async () => {
+ mockDetectAuth.mockRejectedValue(new Error('probe failed'));
+ render(<Harness />);
+ await screen.findAllByTestId('mcp-registry-row');
+ fireEvent.click(screen.getByRole('button', { name: 'Add Hosted Thing' }));
+
+ await screen.findByRole('dialog');
+ fireEvent.click(screen.getByRole('button', { name: 'stub-close' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ expect(mockConnect).not.toHaveBeenCalled();
+ });
+
+ it('shows a refused write inline, and Retry repeats only the write', async () => {
+ mockConfigSet.mockRejectedValueOnce(new Error('mcp.json refused the entry'));
+ render(<Harness />);
+ await screen.findAllByTestId('mcp-registry-row');
+ fireEvent.click(screen.getByRole('button', { name: 'Add Hosted Thing' }));
+
+ const error = await screen.findByTestId('mcp-registry-row-error');
+ expect(error).toHaveTextContent("Couldn't add this server.");
+ expect(error).toHaveTextContent('mcp.json refused the entry');
+ expect(onDeclaredSpy).not.toHaveBeenCalled();
+
+ fireEvent.click(within(error).getByRole('button', { name: 'Try again' }));
+ await waitFor(() => expect(mockConnect).toHaveBeenCalledTimes(1));
+ expect(mockRegistryGet).toHaveBeenCalledTimes(1);
+ expect(mockConfigSet).toHaveBeenCalledTimes(2);
+ await waitFor(() =>
+ expect(screen.queryByTestId('mcp-registry-row-error')).not.toBeInTheDocument()
+ );
+ });
+
+ it('shows a failed connect inline, and Retry reconnects without rewriting', async () => {
+ mockConnect.mockRejectedValueOnce(new Error('connection refused'));
+ render(<Harness />);
+ await screen.findAllByTestId('mcp-registry-row');
+ fireEvent.click(screen.getByRole('button', { name: 'Add Hosted Thing' }));
+
+ const error = await screen.findByTestId('mcp-registry-row-error');
+ expect(error).toHaveTextContent("Added, but the server didn't connect.");
+ expect(error).toHaveTextContent('connection refused');
+ expect(within(rowFor('Hosted Thing')).getByRole('button', { name: /Added/ })).toBeDisabled();
+
+ fireEvent.click(within(error).getByRole('button', { name: 'Try again' }));
+ await waitFor(() => expect(mockConnect).toHaveBeenCalledTimes(2));
+ expect(mockConfigSet).toHaveBeenCalledTimes(1);
+ expect(mockInstalledList).toHaveBeenCalledTimes(2);
+ await waitFor(() =>
+ expect(screen.queryByTestId('mcp-registry-row-error')).not.toBeInTheDocument()
+ );
+ });
+
+ it('writes nothing for a server that needs setup and falls back to its page', async () => {
+ mockRegistryGet.mockResolvedValue(hostedDetail('https://{tenant}.hosted.example/mcp'));
+ render(<Harness />);
+ await screen.findAllByTestId('mcp-registry-row');
+ fireEvent.click(screen.getByRole('button', { name: 'Add Hosted Thing' }));
+
+ expect(await screen.findByTestId('mcp-registry-needs-setup')).toBeInTheDocument();
+ expect(mockConfigGet).not.toHaveBeenCalled();
+ expect(mockConfigSet).not.toHaveBeenCalled();
+ expect(onDeclaredSpy).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Open the page for Hosted Thing' }));
+ expect(mockOpenUrl).toHaveBeenCalledWith('https://hosted.example');
+ });
+
+ it('reports a failed detail lookup with a Retry that starts over', async () => {
+ mockRegistryGet.mockRejectedValueOnce(new Error('registry down'));
+ render(<Harness />);
+ await screen.findAllByTestId('mcp-registry-row');
+ fireEvent.click(screen.getByRole('button', { name: 'Add Hosted Thing' }));
+
+ const error = await screen.findByTestId('mcp-registry-row-error');
+ expect(error).toHaveTextContent('registry down');
+ fireEvent.click(within(error).getByRole('button', { name: 'Try again' }));
+ await waitFor(() => expect(mockConnect).toHaveBeenCalledTimes(1));
+ expect(mockRegistryGet).toHaveBeenCalledTimes(2);
+ });
+
+ it('reports a declared server that the installed list does not return', async () => {
+ mockInstalledList.mockResolvedValue([installedRow('installed/already')]);
+ render(<Harness />);
+ await screen.findAllByTestId('mcp-registry-row');
+ fireEvent.click(screen.getByRole('button', { name: 'Add Hosted Thing' }));
+
+ const error = await screen.findByTestId('mcp-registry-row-error');
+ expect(error).toHaveTextContent("Couldn't add this server.");
+ expect(mockDetectAuth).not.toHaveBeenCalled();
+ });
+
+ it('lists declared rows instead of hiding them', async () => {
+ mockRegistrySearch.mockResolvedValue({ servers: [SERVERS[4]], page: 1, total_pages: 1 });
+ render(<Harness />);
+ await screen.findAllByTestId('mcp-registry-row');
+ expect(screen.queryByTestId('mcp-catalog-empty')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Added/ })).toBeDisabled();
+ });
+
it('a nested link opens its own target only, not the row page as well', async () => {
- render(<McpRegistryBrowser installedNames={new Set()} />);
+ render(<Harness initial={[]} />);
await screen.findAllByTestId('mcp-registry-row');
fireEvent.click(screen.getByRole('button', { name: 'Repository' }));
expect(mockOpenUrl).toHaveBeenCalledTimes(1);
@@ -80,15 +339,15 @@ describe('McpRegistryBrowser', () => {
it('shows a directory outage with retry instead of an empty result', async () => {
mockRegistrySearch.mockRejectedValueOnce(new Error('registry down'));
- render(<McpRegistryBrowser installedNames={new Set()} />);
+ render(<Harness initial={[]} />);
await screen.findByTestId('mcp-catalog-error');
expect(screen.queryByTestId('mcp-catalog-empty')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Try again' }));
- await waitFor(() => expect(screen.getAllByTestId('mcp-registry-row')).toHaveLength(3));
+ await waitFor(() => expect(screen.getAllByTestId('mcp-registry-row')).toHaveLength(5));
});
it('re-queries the directory with the transport filter', async () => {
- render(<McpRegistryBrowser installedNames={new Set()} />);
+ render(<Harness initial={[]} />);
await screen.findAllByTestId('mcp-registry-row');
fireEvent.click(screen.getByRole('button', { name: 'Hosted' }));
await waitFor(() =>
diff --git a/app/src/components/channels/mcp/McpRegistryBrowser.tsx b/app/src/components/channels/mcp/McpRegistryBrowser.tsx
index c04a868db2..f77c2b4820 100644
--- a/app/src/components/channels/mcp/McpRegistryBrowser.tsx
+++ b/app/src/components/channels/mcp/McpRegistryBrowser.tsx
@@ -1,21 +1,22 @@
/**
* Registry — browse the upstream MCP directories.
*
- * The third tab of the MCP page. It is a *directory*, not a store: nothing
- * here installs. A row opens the server's own page in the browser — its
- * website, or its source repository — where the install instructions live;
- * the user then declares the server in the **mcp.json** tab. That keeps one
- * install path (the document) instead of a form here that would have to guess
- * at each server's launch command and credentials.
+ * The third tab of the MCP page. A hosted server that can be dialled as
+ * listed (one http(s) endpoint, nothing to fill in) is added in one step: it
+ * is declared in **mcp.json** under its registry name, then connected, or the
+ * sign-in dialog opens when the server asks for credentials. Every other row
+ * opens the server's own page — its website, or its source repository — where
+ * the install instructions live, and the user declares it in the **mcp.json**
+ * tab. Rows already declared show as added.
*
* Everything here is fenced inside this component's own state. The directories
* are a network hop away and can be down; that is rendered as a notice inside
* this panel with a retry, while the user's installed servers in the other
- * tabs go on rendering. A dead directory is not a broken page.
+ * tabs go on rendering. A failed add is reported on its own row.
*/
import debug from 'debug';
-import { ExternalLink as ExternalLinkIcon, Loader2, Search } from 'lucide-react';
-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { Check, ExternalLink as ExternalLinkIcon, Loader2, Plus, Search } from 'lucide-react';
+import { memo, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useDebouncedValue } from '../../../hooks/useDebouncedValue';
import { useT } from '../../../lib/i18n/I18nContext';
@@ -25,8 +26,10 @@ import Badge from '../../ui/Badge';
import Button from '../../ui/Button';
import Card from '../../ui/Card';
import TextField from '../../ui/TextField';
+import ConnectAuthModal from './ConnectAuthModal';
import { mcpRegistryErrorMessage } from './mcpRegistryErrorMessage';
-import type { SmitheryServer } from './types';
+import { declareServer, type HostedEntry, isAddCandidate, resolveHostedEntry } from './registryAdd';
+import type { InstalledServer, SmitheryServer } from './types';
const log = debug('mcp-clients:registry');
const DEBOUNCE_MS = 300;
@@ -35,6 +38,13 @@ const PAGE_SIZE = 30;
/** Transport classification a catalog row can be filtered by. */
export type Transport = 'hosted' | 'stdio';
+type AddStep = 'resolve' | 'declare' | 'connect';
+type RowPhase = 'adding' | 'connecting' | 'needsSetup' | 'error';
+type RowState = { phase: RowPhase; message?: string; retryStep?: AddStep };
+type PendingAdd = { entry?: HostedEntry; installed?: InstalledServer; retryStep?: AddStep };
+
+const errorText = (err: unknown): string => (err instanceof Error ? err.message : String(err));
+
/**
* Classify a catalog row by how it runs: `hosted` = reachable over an HTTP
* endpoint; `stdio` = run on-device as a subprocess. `is_deployed` is set by
@@ -119,14 +129,83 @@ const ExternalLink = ({ href, label }: { href: string; label: string }) => (
/**
* One catalog row. Memoized so a parent re-render (the installed list's status
- * poll) doesn't re-render the potentially large catalog: the data and the open
- * handler are stable, so memo skips every row.
+ * poll) doesn't re-render the potentially large catalog: the data, the row's
+ * add state and the handlers are stable or primitive, so memo skips every row
+ * whose state did not change.
*/
const CatalogRow = memo(
- ({ server, onOpen }: { server: SmitheryServer; onOpen: (server: SmitheryServer) => void }) => {
+ ({
+ server,
+ declared,
+ phase,
+ message,
+ onOpen,
+ onAdd,
+ onRetry,
+ }: {
+ server: SmitheryServer;
+ declared: boolean;
+ phase?: RowPhase;
+ message?: string;
+ onOpen: (server: SmitheryServer) => void;
+ onAdd: (server: SmitheryServer) => void;
+ onRetry: (server: SmitheryServer) => void;
+ }) => {
const { t } = useT();
const repoUrl = deriveRepoUrl(server.qualified_name);
const hosted = transportOf(server) === 'hosted';
+ const busy = phase === 'adding' || phase === 'connecting';
+ const canAdd = isAddCandidate(server) && phase !== 'needsSetup';
+
+ let action: ReactNode;
+ if (busy) {
+ action = (
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled
+ leadingIcon={<Loader2 className="size-3.5 animate-spin" aria-hidden="true" />}
+ className="shrink-0">
+ {t('mcp.registry.action.adding')}
+ </Button>
+ );
+ } else if (declared) {
+ action = (
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled
+ leadingIcon={<Check className="size-3.5" aria-hidden="true" />}
+ className="shrink-0">
+ {t('mcp.registry.action.added')}
+ </Button>
+ );
+ } else if (canAdd) {
+ action = (
+ <Button
+ variant="primary"
+ size="sm"
+ aria-label={t('mcp.registry.aria.add').replace('{name}', server.display_name)}
+ onClick={() => onAdd(server)}
+ leadingIcon={<Plus className="size-3.5" aria-hidden="true" />}
+ className="shrink-0">
+ {t('mcp.registry.action.add')}
+ </Button>
+ );
+ } else {
+ action = (
+ <Button
+ variant="secondary"
+ size="sm"
+ aria-label={t('mcp.tab.aria.openServerPage').replace('{name}', server.display_name)}
+ onClick={() => onOpen(server)}
+ trailingIcon={<ExternalLinkIcon className="size-3.5" aria-hidden="true" />}
+ className="shrink-0">
+ {t('mcp.tab.action.openPage')}
+ </Button>
+ );
+ }
+
return (
<li className="space-y-2 py-3 first:pt-0 last:pb-0" data-testid="mcp-registry-row">
<div className="flex items-start gap-3">
@@ -166,16 +245,28 @@ const CatalogRow = memo(
{repoUrl && <ExternalLink href={repoUrl} label={t('mcp.tab.link.repo')} />}
</p>
)}
+ {phase === 'needsSetup' && (
+ <p className="text-xs text-content-muted" data-testid="mcp-registry-needs-setup">
+ {t('mcp.registry.needsSetup')}
+ </p>
+ )}
+ {phase === 'error' && (
+ <div
+ role="alert"
+ data-testid="mcp-registry-row-error"
+ className="space-y-1 text-xs text-coral-700 dark:text-coral-300">
+ <p>{message}</p>
+ <Button
+ variant="tertiary"
+ size="xs"
+ onClick={() => onRetry(server)}
+ className="h-auto p-0 text-primary-600 hover:underline dark:text-primary-400">
+ {t('common.retry')}
+ </Button>
+ </div>
+ )}
</div>
- <Button
- variant="secondary"
- size="sm"
- aria-label={t('mcp.tab.aria.openServerPage').replace('{name}', server.display_name)}
- onClick={() => onOpen(server)}
- trailingIcon={<ExternalLinkIcon className="size-3.5" aria-hidden="true" />}
- className="shrink-0">
- {t('mcp.tab.action.openPage')}
- </Button>
+ {action}
</div>
</li>
);
@@ -184,11 +275,13 @@ const CatalogRow = memo(
CatalogRow.displayName = 'CatalogRow';
interface McpRegistryBrowserProps {
- /** Names already declared, so the directory does not list what is installed. */
+ /** Names already declared in mcp.json; those rows show as added. */
installedNames: ReadonlySet<string>;
+ /** Re-reads the installed servers after a row was declared. */
+ onDeclared: () => Promise<void>;
}
-const McpRegistryBrowser = ({ installedNames }: McpRegistryBrowserProps) => {
+const McpRegistryBrowser = ({ installedNames, onDeclared }: McpRegistryBrowserProps) => {
const { t } = useT();
const [searchQuery, setSearchQuery] = useState('');
const [transportFilter, setTransportFilter] = useState<'all' | Transport>('all');
@@ -250,18 +343,118 @@ const McpRegistryBrowser = ({ installedNames }: McpRegistryBrowserProps) => {
void openUrl(url).catch(() => {});
}, []);
- // Catalog rows minus already-declared servers.
- const availableCatalog = useMemo(
- () => catalogServers.filter(s => !installedNames.has(s.qualified_name)),
- [catalogServers, installedNames]
+ const [rowStates, setRowStates] = useState<ReadonlyMap<string, RowState>>(() => new Map());
+ const pendingRef = useRef(new Map<string, PendingAdd>());
+ const [authFor, setAuthFor] = useState<InstalledServer | null>(null);
+
+ const setRowState = useCallback((name: string, state: RowState | null) => {
+ setRowStates(prev => {
+ const next = new Map(prev);
+ if (state) next.set(name, state);
+ else next.delete(name);
+ return next;
+ });
+ }, []);
+
+ const runAdd = useCallback(
+ async (server: SmitheryServer, from: AddStep) => {
+ const name = server.qualified_name;
+ const pending = pendingRef.current.get(name) ?? {};
+ pendingRef.current.set(name, pending);
+ let step: AddStep = from;
+ log('add %s from step=%s', name, step);
+ try {
+ if (step === 'resolve') {
+ setRowState(name, { phase: 'adding' });
+ const detail = await mcpClientsApi.registryGet(name);
+ const resolved = resolveHostedEntry(detail, server);
+ if (!resolved.ok) {
+ setRowState(name, { phase: 'needsSetup' });
+ return;
+ }
+ pending.entry = resolved.entry;
+ step = 'declare';
+ }
+ if (step === 'declare') {
+ setRowState(name, { phase: 'adding' });
+ if (!pending.entry) throw new Error(t('mcp.registry.addFailed'));
+ const outcome = await declareServer(name, pending.entry);
+ log('add %s declare=%s', name, outcome);
+ await onDeclared();
+ const installed = await mcpClientsApi.installedList();
+ const row = installed.find(s => s.qualified_name === name);
+ if (!row) throw new Error(t('mcp.registry.addFailed'));
+ pending.installed = row;
+ step = 'connect';
+ }
+ const row = pending.installed;
+ if (!row) throw new Error(t('mcp.registry.connectFailed'));
+ setRowState(name, { phase: 'connecting' });
+ let kind: 'none' | 'token' | 'oauth';
+ try {
+ kind = (await mcpClientsApi.detectAuth(row.server_id)).kind;
+ } catch (err) {
+ log('add %s detect_auth failed: %s', name, errorText(err));
+ kind = 'token';
+ }
+ log('add %s auth=%s', name, kind);
+ if (kind !== 'none') {
+ setRowState(name, null);
+ setAuthFor(row);
+ return;
+ }
+ await mcpClientsApi.connect(row.server_id);
+ log('add %s connected', name);
+ pendingRef.current.delete(name);
+ setRowState(name, null);
+ } catch (err) {
+ const reason = errorText(err);
+ log('add %s failed at step=%s: %s', name, step, reason);
+ pending.retryStep = step;
+ const headline = t(
+ step === 'connect' ? 'mcp.registry.connectFailed' : 'mcp.registry.addFailed'
+ );
+ setRowState(name, {
+ phase: 'error',
+ message: reason && reason !== headline ? `${headline} ${reason}` : headline,
+ retryStep: step,
+ });
+ }
+ },
+ [onDeclared, setRowState, t]
+ );
+
+ const handleAdd = useCallback(
+ (server: SmitheryServer) => void runAdd(server, 'resolve'),
+ [runAdd]
+ );
+
+ const handleRetry = useCallback(
+ (server: SmitheryServer) => {
+ const retryStep = pendingRef.current.get(server.qualified_name)?.retryStep ?? 'resolve';
+ void runAdd(server, retryStep);
+ },
+ [runAdd]
);
const catalogRows = useMemo(
() =>
- availableCatalog.map(server => (
- <CatalogRow key={`catalog-${server.qualified_name}`} server={server} onOpen={handleOpen} />
- )),
- [availableCatalog, handleOpen]
+ catalogServers.map(server => {
+ const state = rowStates.get(server.qualified_name);
+ return (
+ <CatalogRow
+ key={`catalog-${server.qualified_name}`}
+ server={server}
+ declared={installedNames.has(server.qualified_name)}
+ phase={state?.phase}
+ message={state?.message}
+ onOpen={handleOpen}
+ onAdd={handleAdd}
+ onRetry={handleRetry}
+ />
+ );
+ }),
+ [catalogServers, rowStates, installedNames, handleOpen, handleAdd, handleRetry]
);
return (
@@ -318,12 +511,12 @@ const McpRegistryBrowser = ({ installedNames }: McpRegistryBrowserProps) => {
</div>
) : (
<Card padded divided={false}>
- {catalogLoading && availableCatalog.length === 0 ? (
+ {catalogLoading && catalogServers.length === 0 ? (
<p className="flex items-center gap-1.5 text-xs text-content-muted">
<Loader2 className="size-3 animate-spin" aria-hidden="true" />
{t('common.loading')}
</p>
- ) : availableCatalog.length === 0 ? (
+ ) : catalogServers.length === 0 ? (
<p className="text-sm text-content-muted" data-testid="mcp-catalog-empty">
{searchQuery
? t('mcp.catalog.noResultsFor').replace('{query}', searchQuery)
@@ -361,6 +554,17 @@ const McpRegistryBrowser = ({ installedNames }: McpRegistryBrowserProps) => {
)}
</Card>
)}
+
+ {authFor && (
+ <ConnectAuthModal
+ server={authFor}
+ onClose={() => setAuthFor(null)}
+ onConnected={() => {
+ setAuthFor(null);
+ void onDeclared();
+ }}
+ />
+ )}
</section>
);
};