Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(connectors): add and manage custom MCP connectors from the Connectors page
trohitg0a288241cbe9
diff --git a/CLAUDE.md b/CLAUDE.mdindex a6da4318..d24b2bc3 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -33,6 +33,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Email Service](./docs-internal/email_service.md)** | IMAP/SMTP integration via Himalaya CLI with EmailService orchestrator, provider presets, custom credential fallback, and polling triggers || **[Browser](./docs-internal/browser.md)** | Current `browser` node: installed Chrome/Edge/Chromium in a dedicated profile rendered inside the workspace by default (`BROWSER_RUNTIME=system`, `BROWSER_HEADLESS=true`) and pinned browser-use CLI. Chrome for Testing requires explicit `BROWSER_RUNTIME=testing`. System mode retains the native user agent and OS password-store/keychain integration; basic/mock keychain flags are restricted to testing mode. Includes persistent employee/shared profiles (the Credentials / Connectors "Web browser" panel adds, deletes and imports logins from a session file; the node's profile dropdown lists only the caller's profiles, via `current_load_options_principal()`), session leases, agent/user handoff, network policy, screenshots as workspace FileRefs and authenticated `/ws/browser` live viewing. Plugin-owned installation is lazy (`_install_chrome.py`, `_install_bu.py`); importing or shutting down the plugin never installs it. Replaces the former agent-browser and separate `browserHarness` implementations. || **[Browser Workspace](./docs-internal/browser_workspace.md)** | Home and Dev share `WorkspaceTabs` and `BrowserWorkspace`: Browser / Canvas / Mobile, capability-based discovery, binary JPEG frames, bounded frame credit and decoding, Take control / Hand back, the agent's cursor (`agent_action`: where each click, hover, type or select happened, beside the agent's result and never during a protected login), visibility cleanup and payload-free opt-in diagnostics. The Browser node's parameter panel shows the same viewer, and the Dev dock opens on its Browser tab when an agent in the open workflow asks for help (`browser_updated`). Mobile shows the managed local Android phone. |+| **[MCP Connectors](./docs-internal/mcp_connectors.md)** | Custom connectors: the owner adds an outside MCP server from Connectors → Add (URL, name, sign-in: none, bearer or one header), and OpenCompany is its MCP *client* (`server/nodes/mcp/`, official `mcp` SDK; unrelated to the CLI agents' `/mcp/ide` server). The server reads the tools before keeping anything: streamable HTTP, then SSE; our own httpx client with redirects off; host and resolved addresses checked against `services/netpolicy.py` (shared with the Browser node: never cloud metadata or OpenCompany's own ports, plain http only on the owner's network), within `DISCOVER_S` (45 s, under the app's 60 s probe wait). Kept as `mcp:<slug>` (sign-in, encrypted; plain `model_params._mcp`: tools as accepted, per-tool `{enabled, ask}`, a waiting refresh) and `mcp:<slug>_proxy` (URL). A tool no model could call is kept with the reason, never renamed. Each connector is its own card through the generic `Credential.catalogue_entries` hook and the `_mcp_connector` template. Commands `mcp_connector_add` / `_test` / `_refresh` / `_review` / `_set_tool` / `_remove`; Refresh holds every change for Accept. Client: `AddConnectorForm.tsx` and `panels/McpConnectorPanel.tsx`. || **[WhatsApp Business Service](./docs-internal/whatsapp_business_service.md)** | Official Meta Cloud API plugin in [`server/nodes/whatsapp_business/`](./server/nodes/whatsapp_business/) — **distinct from `nodes/whatsapp/`**, which is a personal account over an unofficial Go bridge; they share no node type, credential or palette group. Four nodes: `whatsappBusinessSend` (10 ops — Meta models message type as a *field* on one `/messages` endpoint, so text / media / template / interactive are operations, not nodes), `whatsappBusinessMedia` (the one genuinely separate endpoint family), and the `Receive` / `Status` triggers (kept separate because a canary trigger registers exactly one CloudEvents type). `phone_number_id` is deliberately **absent from Params** and comes from the credential only, because it selects the sending identity — `server_controlled_fields` would keep a model-set value out on every tool path, but an ActionNode's tool schema is its whole `Params` (`ToolInput` is ToolNode-only), so a declared field would still appear in the schema the model sees. Webhook via `register_webhook_source` on the shared catch-all, `X-Hub-Signature-256` HMAC failing closed, composite `wamid:status` dedup ids so `sent→delivered→read` don't collapse. || **[Stripe Service](./docs-internal/stripe_service.md)** | Stripe CLI integration — `stripeAction` (CLI pass-through) + `stripeReceive` (signed-webhook trigger, on a canvas Run and deployed: every Stripe event travels under one CloudEvents type, `com.opencompany.stripe.event.received`, with the Stripe type in `subject` and `data.event_type`, where the node's own `build_filter` reads it; the source shapes the payload once, wakes the in-process waiter through `WebhookSource.handle` and reaches deployed listeners through `dispatch.emit`; deploying starts `stripe listen` through the generic `TriggerNode.prepare_deployment` hook, at Start and at the boot re-arm). Reference plugin for the Wave 12 event framework AND the **CLI-managed-auth pattern**: browser OAuth via `stripe login --non-interactive` + `--complete <url>` (URL extracted from `next_step` shell command via `shlex.split`) + auto-installed binary (`ensure_stripe_cli` from GitHub releases) + marker-token reuse of `auth_service.store_oauth_tokens` + CloudEvents-shaped `broadcast_credential_event("credential.oauth.connected" \| ".disconnected", provider=...)` — zero per-provider hardcoding in the frontend. Daemon stdout/stderr ingested via `ProcessService`'s `line_handler` callback (no log-file tailing); credential gate routed through `await self.has_credential()` so non-api-key auth (`is_logged_in()`) plugs in via subclass override. || **[Vercel Service](./docs-internal/vercel_service.md)** | Vercel CLI integration — `vercelAction` (deploy / inspect / list + `custom` CLI passthrough; AI tool `vercel`). Second reference for the CLI-managed-auth pattern: the **device-flow variant** (`vercel login` is one blocking process — no two-step `--complete`; direct `create_subprocess_exec` + chunk-based banner read for the code-embedding URL, pumps drain pipes for the process lifetime, success gate = auth.json mtime advance + sniff). Dual auth: optional `vercel_token` field (injected as `VERCEL_TOKEN` env, never argv) OR CLI login with marker tokens. All invocations pin `--global-config <DATA_DIR>/vercel/` (the `CLAUDE_CONFIG_DIR` isolation idiom). `bun add` into the shared packages tree (pinned version, via `core/js_runtime.add_package`; the CLI runs on bun). First-deploy project guard raises `NodeUserError` instead of letting Vercel derive an invalid name from the workspace dir. Shipped with the generic OAuthConnect change: Login gates on **required** fields only, so optional fields never block CLI login. |diff --git a/client/src/components/credentials/AddConnectorForm.tsx b/client/src/components/credentials/AddConnectorForm.tsxnew file mode 100644index 00000000..505bef12--- /dev/null+++ b/client/src/components/credentials/AddConnectorForm.tsx@@ -0,0 +1,159 @@+/**+ * The Connectors page's form for a custom connector: an MCP server's URL, a+ * name, and how it signs in (none, a bearer token, or one header). The+ * server reads the server's tools before keeping anything+ * (`mcp_connector_add`, nodes/mcp/_handlers.py), so a wrong URL or a refused+ * sign-in comes back here in the server's words and nothing is saved.+ */++import { useId, useState, type FormEvent } from 'react';+import { ActionButton } from '@/components/ui/action-button';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';+import { CREDENTIAL_PROBE_REQUEST_TIMEOUT, useWebSocketActions } from '@/contexts/WebSocketContext';++type SignInKind = 'none' | 'bearer' | 'header';++const FIELD = 'h-9.5 rounded-lg bg-bg-app text-row font-normal md:text-row dark:bg-bg-app';+const FAILED = "Couldn't add that connector. Try again.";++export interface AddConnectorFormProps {+ close: () => void;+ /** The connector was saved; `ref` is its card's id (`mcp:<slug>`). */+ onAdded: (ref: string) => void;+}++export function AddConnectorForm({ close, onAdded }: AddConnectorFormProps) {+ const { sendRequest, isReady } = useWebSocketActions();+ const signInLabel = useId();+ const [url, setUrl] = useState('');+ const [name, setName] = useState('');+ const [signIn, setSignIn] = useState<SignInKind>('none');+ const [token, setToken] = useState('');+ const [header, setHeader] = useState('');+ const [value, setValue] = useState('');+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState('');++ const signedIn = signIn === 'none' || (signIn === 'bearer' ? token.trim() !== '' : header.trim() !== '' && value.trim() !== '');+ const ready = isReady && !saving && url.trim() !== '' && signedIn;++ const submit = async (event: FormEvent) => {+ event.preventDefault();+ if (!ready) return;+ setSaving(true);+ setError('');+ try {+ const result = await sendRequest<{ success?: boolean; error?: string; ref?: string }>(+ 'mcp_connector_add',+ {+ name,+ url,+ sign_in: signIn === 'bearer' ? { kind: 'bearer', token } : signIn === 'header' ? { kind: 'header', header, value } : { kind: 'none' },+ },+ CREDENTIAL_PROBE_REQUEST_TIMEOUT,+ );+ if (result.success === false || !result.ref) throw new Error(result.error || FAILED);+ close();+ onAdded(result.ref);+ } catch (cause) {+ setError(cause instanceof Error && cause.message ? cause.message : FAILED);+ setSaving(false);+ }+ };++ return (+ <form onSubmit={(event) => void submit(event)} aria-label="Custom connector" className="flex flex-col gap-2.5">+ <span className="text-base font-semibold text-fg-default">Custom connector</span>+ <Input+ value={url}+ onChange={(event) => setUrl(event.target.value)}+ placeholder="https://mcp.example.com/mcp"+ aria-label="Server URL"+ inputMode="url"+ autoComplete="off"+ spellCheck={false}+ className={FIELD}+ />+ <Input+ value={name}+ onChange={(event) => setName(event.target.value)}+ placeholder="Name it (optional), e.g. Orders"+ aria-label="Name"+ maxLength={60}+ className={FIELD}+ />+ <div className="flex flex-wrap items-center gap-2.5">+ <span id={signInLabel} className="text-sm text-fg-muted">+ Sign-in+ </span>+ <ToggleGroup+ type="single"+ variant="segmented"+ aria-labelledby={signInLabel}+ value={signIn}+ onValueChange={(next) => next && setSignIn(next as SignInKind)}+ >+ <ToggleGroupItem value="none" className="px-3 text-sm">+ None+ </ToggleGroupItem>+ <ToggleGroupItem value="bearer" className="px-3 text-sm">+ Token+ </ToggleGroupItem>+ <ToggleGroupItem value="header" className="px-3 text-sm">+ Header+ </ToggleGroupItem>+ </ToggleGroup>+ </div>+ {signIn === 'bearer' && (+ <Input+ type="password"+ value={token}+ onChange={(event) => setToken(event.target.value)}+ placeholder="The token the server gave you"+ aria-label="Token"+ autoComplete="off"+ className={FIELD}+ />+ )}+ {signIn === 'header' && (+ <div className="flex flex-wrap gap-2.5">+ <Input+ value={header}+ onChange={(event) => setHeader(event.target.value)}+ placeholder="Header, e.g. X-API-Key"+ aria-label="Header name"+ autoComplete="off"+ spellCheck={false}+ className={`flex-[1_1_180px] ${FIELD}`}+ />+ <Input+ type="password"+ value={value}+ onChange={(event) => setValue(event.target.value)}+ placeholder="Its value"+ aria-label="Header value"+ autoComplete="off"+ className={`flex-[2_1_220px] ${FIELD}`}+ />+ </div>+ )}+ {error && (+ <p role="alert" className="m-0 text-sm text-destructive">+ {error}+ </p>+ )}+ <div className="flex justify-end gap-2">+ <Button type="button" variant="quiet" size="sm" onClick={close}>+ Cancel+ </Button>+ <ActionButton intent="run" type="submit" disabled={!ready} className="h-7.5 rounded-lg px-3.5 text-meta">+ {saving ? 'Reading its tools…' : 'Add'}+ </ActionButton>+ </div>+ </form>+ );+}++export default AddConnectorForm;diff --git a/client/src/components/credentials/CredentialsBrowser.tsx b/client/src/components/credentials/CredentialsBrowser.tsxindex e10b585e..9f240508 100644--- a/client/src/components/credentials/CredentialsBrowser.tsx+++ b/client/src/components/credentials/CredentialsBrowser.tsx@@ -3,12 +3,12 @@* visible provider, apps before AI models; Yours lists connected ones.** Connect and Manage open the shared host with the corresponding intent.- * Disconnect removes what the panel would remove for API-key and signed-in- * providers, after a confirmation; for the rest (a paired phone, an email- * account) it opens the panel, which owns those steps. A card glows when- * it turns connected. Connection-success feedback belongs to the host.- * There is no custom connector:- * nothing serves one yet, so the page has no Add button.+ * Disconnect removes what the panel would remove for API-key, signed-in and+ * custom (MCP) providers, after a confirmation; for the rest (a paired+ * phone, an email account) it opens the panel, which owns those steps. A+ * card glows when it turns connected. Connection-success feedback belongs+ * to the host. Add opens the custom connector form (AddConnectorForm); a+ * saved connector opens on its own page once the catalogue holds it.*/import { useMemo, useState } from 'react';@@ -26,6 +26,7 @@ import {import { useWebSocketActions } from '@/contexts/WebSocketContext';import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';import { Button } from '@/components/ui/button';+import { AddConnectorForm } from './AddConnectorForm';import { isConnected, useCredentialsCatalogue, type ConsumerProvider, type CredentialsCatalogue } from './catalogue';import type { CatalogItem } from '@/components/catalog/catalog';import { CatalogLayout } from '@/components/catalog/CatalogLayout';@@ -50,6 +51,11 @@ async function disconnect(await sendRequest(provider.ws.logout, {});return true;}+ if (provider.kind === 'mcp') {+ const result = await sendRequest<{ success?: boolean; error?: string }>('mcp_connector_remove', { ref: provider.id });+ if (result.success === false) throw new Error(result.error || `Couldn't remove ${provider.name}`);+ return true;+ }return false;}@@ -104,6 +110,9 @@ export interface CredentialsBrowserProps {discoverLimit?: number | null;/** A provider on screen turned connected (after its card's glow starts). */onItemAdded?: (providerId: string) => void;+ /** Offer Add for a custom connector (default). The Welcome guide's AI+ * model step turns it off. */+ customConnectors?: boolean;}export function CredentialsBrowser(props: CredentialsBrowserProps) {@@ -125,6 +134,7 @@ function CredentialsBrowserContent({variant,discoverLimit,onItemAdded,+ customConnectors = true,}: CredentialsBrowserProps & { catalogue: CredentialsCatalogue }) {const { providers, categories, isLoading, isError, refetch } = catalogue;const { sendRequest } = useWebSocketActions();@@ -146,6 +156,12 @@ function CredentialsBrowserContent({}};+ // Its page opens once the refetched catalogue holds it.+ const openAdded = async (ref: string) => {+ await refetch();+ onConnect(ref, 'manage');+ };+if (isError && !catalogue.catalogue.data) {return (<Alert variant="destructive" className="m-8 w-auto">@@ -174,6 +190,11 @@ function CredentialsBrowserContent({onManage={(item) => onConnect(item.id, 'manage')}onRemove={(item) => setConfirming(byId.get(item.id) ?? null)}onItemAdded={onItemAdded && ((item) => onItemAdded(item.id))}+ primaryAction={+ customConnectors+ ? { label: 'Add', form: (close) => <AddConnectorForm close={close} onAdded={(ref) => void openAdded(ref)} /> }+ : undefined+ }/><AlertDialog open={confirming !== null} onOpenChange={(open) => !open && setConfirming(null)}>diff --git a/client/src/components/credentials/PanelRenderer.tsx b/client/src/components/credentials/PanelRenderer.tsxindex 1a001494..e70c1ca4 100644--- a/client/src/components/credentials/PanelRenderer.tsx+++ b/client/src/components/credentials/PanelRenderer.tsx@@ -24,6 +24,7 @@ const PANEL_LOADERS: Record<PanelKind, () => Promise<{ default: React.ComponentTqrPairing: () => import('./panels/QrPairingPanel'),email: () => import('./panels/EmailPanel'),browserProfiles: () => import('./panels/BrowserProfilesPanel'),+ mcp: () => import('./panels/McpConnectorPanel'),};// Memoize the lazy wrappers at module scope so switching providers of@@ -36,6 +37,7 @@ const LAZY_PANELS: Record<PanelKind, React.LazyExoticComponent<React.ComponentTyqrPairing: React.lazy(PANEL_LOADERS.qrPairing),email: React.lazy(PANEL_LOADERS.email),browserProfiles: React.lazy(PANEL_LOADERS.browserProfiles),+ mcp: React.lazy(PANEL_LOADERS.mcp),};export interface CredentialPanelProps {@@ -43,6 +45,8 @@ export interface CredentialPanelProps {visible: boolean;/** Set by the shared host from shell mode; connection inputs stay available in both modes. */showTechnicalSections?: boolean;+ /** Leave this provider's page: the panel removed the provider itself. */+ onLeave?: () => void;}interface Props extends Omit<CredentialPanelProps, 'config'> {@@ -62,7 +66,7 @@ const EmptyState: React.FC<{ icon: React.ReactNode; message: string }> = ({ icon</div>);-const PanelRenderer: React.FC<Props> = ({ config, visible, showTechnicalSections = false }) => {+const PanelRenderer: React.FC<Props> = ({ config, visible, showTechnicalSections = false, onLeave }) => {const Lazy = useMemo(() => {if (!config) return null;return LAZY_PANELS[config.kind] ?? null;@@ -93,7 +97,7 @@ const PanelRenderer: React.FC<Props> = ({ config, visible, showTechnicalSections<Suspense fallback={<PanelFallback />}>{/* Provider identity resets transient errors/reveal state. Mode changeskeep the same panel mounted and preserve the active connection draft. */}- <Lazy key={config.id} config={config} visible={visible} showTechnicalSections={showTechnicalSections} />+ <Lazy key={config.id} config={config} visible={visible} showTechnicalSections={showTechnicalSections} onLeave={onLeave} /></Suspense>);};diff --git a/client/src/components/credentials/ProviderPage.tsx b/client/src/components/credentials/ProviderPage.tsxindex 5d85d4f6..3afce0e3 100644--- a/client/src/components/credentials/ProviderPage.tsx+++ b/client/src/components/credentials/ProviderPage.tsx@@ -106,7 +106,7 @@ export function ProviderPage({ view, selection, backLabel, onBack, visible, show{provider.runs_locally && <span>Runs on this computer</span>}</div></div>- <PanelRenderer config={config} visible={visible} showTechnicalSections={showTechnicalSections} />+ <PanelRenderer config={config} visible={visible} showTechnicalSections={showTechnicalSections} onLeave={onBack} /></>)}</>diff --git a/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsx b/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsxindex 89d34caa..e11b67f9 100644--- a/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsx+++ b/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsx@@ -1,5 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { toast } from 'sonner';import { ThemeProvider } from '@/contexts/ThemeContext';import type { CredentialsCatalogue, ConsumerProvider } from '../catalogue';@@ -7,6 +8,7 @@ const sendRequest = vi.fn();const useCatalogue = vi.fn();vi.mock('@/contexts/WebSocketContext', () => ({useWebSocketActions: () => ({ sendRequest, isReady: true }),+ CREDENTIAL_PROBE_REQUEST_TIMEOUT: 60_000,}));vi.mock('../catalogue', async (importOriginal) => ({...(await importOriginal<typeof import('../catalogue')>()),@@ -16,6 +18,11 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), info: vi.fn(), error: vi.fimport { CredentialsBrowser } from '../CredentialsBrowser';+const CONNECTOR: ConsumerProvider = {+ id: 'mcp:orders', name: 'Orders', category: 'custom', category_label: 'Custom',+ consumer_category: 'custom', color: '', kind: 'mcp', connected: true, publisher: 'you', verified: false,+};+const ENDPOINT: ConsumerProvider = {id: 'openai_compatible', name: 'Model server', category: 'ai', category_label: 'AI',consumer_category: 'ai', color: '', kind: 'apiKey', connected: true,@@ -54,6 +61,65 @@ describe('CredentialsBrowser', () => {expect(sendRequest).not.toHaveBeenCalled();});+ it('adds a custom connector, then opens its page once the catalogue holds it', async () => {+ const steps: string[] = [];+ const onConnect = vi.fn(() => steps.push('open'));+ const state = catalogue();+ vi.mocked(state.refetch).mockImplementation(async () => {+ steps.push('refetch');+ return undefined as never;+ });+ sendRequest.mockResolvedValue({ success: true, ref: 'mcp:orders', tools: 2 });+ render(<ThemeProvider><CredentialsBrowser catalogue={state} onConnect={onConnect} /></ThemeProvider>);+ fireEvent.click(screen.getByRole('button', { name: 'Add' }));+ const form = within(screen.getByRole('form', { name: 'Custom connector' }));+ expect(form.getByRole('button', { name: 'Add' })).toBeDisabled();+ fireEvent.change(form.getByLabelText('Server URL'), { target: { value: 'https://orders.example.com/mcp' } });+ fireEvent.click(form.getByRole('radio', { name: 'Token' }));+ expect(form.getByRole('button', { name: 'Add' })).toBeDisabled();+ fireEvent.change(form.getByLabelText('Token'), { target: { value: 's3cret' } });+ fireEvent.click(form.getByRole('button', { name: 'Add' }));+ await waitFor(() => expect(onConnect).toHaveBeenCalledWith('mcp:orders', 'manage'));+ expect(steps).toEqual(['refetch', 'open']);+ expect(sendRequest).toHaveBeenCalledWith(+ 'mcp_connector_add',+ { name: '', url: 'https://orders.example.com/mcp', sign_in: { kind: 'bearer', token: 's3cret' } },+ 60_000,+ );+ expect(screen.queryByRole('form', { name: 'Custom connector' })).not.toBeInTheDocument();+ });++ it('keeps the form and shows the server words when a connector cannot be added', async () => {+ sendRequest.mockResolvedValue({ success: false, error: "Couldn't connect to orders.example.com. Check that the server is running." });+ const onConnect = vi.fn();+ render(<ThemeProvider><CredentialsBrowser catalogue={catalogue()} onConnect={onConnect} /></ThemeProvider>);+ fireEvent.click(screen.getByRole('button', { name: 'Add' }));+ const form = within(screen.getByRole('form', { name: 'Custom connector' }));+ fireEvent.change(form.getByLabelText('Server URL'), { target: { value: 'https://orders.example.com/mcp' } });+ fireEvent.click(form.getByRole('button', { name: 'Add' }));+ expect(await form.findByRole('alert')).toHaveTextContent("Couldn't connect to orders.example.com.");+ expect(form.getByLabelText('Server URL')).toHaveValue('https://orders.example.com/mcp');+ expect(onConnect).not.toHaveBeenCalled();+ });++ it('has no Add where the host turns custom connectors off', () => {+ render(<ThemeProvider><CredentialsBrowser catalogue={catalogue()} onConnect={vi.fn()} customConnectors={false} /></ThemeProvider>);+ expect(screen.queryByRole('button', { name: 'Add' })).not.toBeInTheDocument();+ });++ it('removes a custom connector on Disconnect, and says why when the server refuses', async () => {+ render(<ThemeProvider><CredentialsBrowser catalogue={catalogue([CONNECTOR])} onConnect={vi.fn()} /></ThemeProvider>);+ fireEvent.click(screen.getByRole('button', { name: 'Disconnect Orders' }));+ fireEvent.click(screen.getByRole('button', { name: 'Disconnect' }));+ await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('mcp_connector_remove', { ref: 'mcp:orders' }));+ await waitFor(() => expect(toast.info).toHaveBeenCalledWith('Orders disconnected'));++ sendRequest.mockResolvedValue({ success: false, error: 'There is no such connector.' });+ fireEvent.click(screen.getByRole('button', { name: 'Disconnect Orders' }));+ fireEvent.click(screen.getByRole('button', { name: 'Disconnect' }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('There is no such connector.'));+ });+it('offers a retry when no catalogue could be loaded', () => {const state = catalogue([]);state.catalogue = { ...state.catalogue, data: undefined } as CredentialsCatalogue['catalogue'];diff --git a/client/src/components/credentials/catalogueAdapter.ts b/client/src/components/credentials/catalogueAdapter.tsindex ecc14d3e..96c7b602 100644--- a/client/src/components/credentials/catalogueAdapter.ts+++ b/client/src/components/credentials/catalogueAdapter.ts@@ -177,6 +177,7 @@ export function rehydrateProvider(entry: ServerProviderConfig): ProviderConfig {stored: entry.stored,account_label: entry.account_label ?? null,endpoints: entry.endpoints,+ mcp: entry.mcp,sourceSupported: entry.sourceSupported,sourceRequired: entry.sourceRequired,unsupportedReason: entry.unsupported_reason,diff --git a/client/src/components/credentials/panels/McpConnectorPanel.tsx b/client/src/components/credentials/panels/McpConnectorPanel.tsxnew file mode 100644index 00000000..21077ab4--- /dev/null+++ b/client/src/components/credentials/panels/McpConnectorPanel.tsx@@ -0,0 +1,268 @@+/**+ * McpConnectorPanel — a custom MCP connector (kind `mcp`): the server it+ * reaches and how it signs in; Test, which asks the server again; Refresh,+ * which reads its tools again and holds any change for Accept or Discard,+ * since a server can change what a tool says it does; Remove; and its tools,+ * each on or off for employees and set to ask first or not.+ *+ * Everything shown is the connector's card (`config.mcp`). Every change is+ * the server's (nodes/mcp/_handlers.py): a command waits for the refetched+ * card, so the panel never shows a state the server does not hold.+ */++import { useId, useState } from 'react';+import { useQueryClient } from '@tanstack/react-query';+import { toast } from 'sonner';+import { ActionButton } from '@/components/ui/action-button';+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from '@/components/ui/alert-dialog';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Label } from '@/components/ui/label';+import { Switch } from '@/components/ui/switch';+import { CREDENTIAL_PROBE_REQUEST_TIMEOUT, useWebSocketActions } from '@/contexts/WebSocketContext';+import { CATALOGUE_QUERY_KEY, type ServerMcpConnector, type ServerMcpTool } from '@/hooks/useCatalogueQuery';+import { cn } from '@/lib/utils';+import { formatTimestamp } from '@/utils/formatters';+import type { CredentialPanelProps } from '../PanelRenderer';++interface Result {+ success?: boolean;+ error?: string;+}++type ToolChange = { enabled?: boolean; ask?: boolean };++const FAILED = "That didn't work. Try again.";++function signInText(signIn: ServerMcpConnector['sign_in']): string {+ if (signIn.kind === 'bearer') return 'Bearer token';+ if (signIn.kind === 'header') return `Header ${signIn.header ?? ''}`.trim();+ return 'None';+}++function pendingLines(pending: NonNullable<ServerMcpConnector['pending']>): string[] {+ return [+ pending.added.length > 0 ? `New: ${pending.added.join(', ')}` : null,+ pending.removed.length > 0 ? `Gone: ${pending.removed.join(', ')}` : null,+ pending.changed.length > 0 ? `Changed: ${pending.changed.join(', ')}` : null,+ pending.instructions ? "The server's instructions changed." : null,+ ].filter((line): line is string => line !== null);+}++export default function McpConnectorPanel({ config, showTechnicalSections = false, onLeave }: CredentialPanelProps) {+ const { sendRequest, isReady } = useWebSocketActions();+ const queryClient = useQueryClient();+ const headingId = useId();+ const [busy, setBusy] = useState<string | null>(null);+ const [error, setError] = useState('');+ const [notice, setNotice] = useState<{ ok: boolean; text: string } | null>(null);+ // The switch being changed shows its new position until the card does.+ const [changing, setChanging] = useState<({ tool: string } & ToolChange) | null>(null);+ const [removing, setRemoving] = useState(false);+ const mcp = config.mcp;+ if (!mcp) return null;++ /** Sends one command for this connector, then waits for the refetched card. */+ const run = async <T extends Result>(key: string, command: string, data: Record<string, unknown> = {}): Promise<T | null> => {+ setBusy(key);+ setError('');+ setNotice(null);+ try {+ const result = await sendRequest<T>(command, { ref: config.id, ...data }, CREDENTIAL_PROBE_REQUEST_TIMEOUT);+ if (result.success === false) throw new Error(result.error || FAILED);+ await queryClient.invalidateQueries({ queryKey: CATALOGUE_QUERY_KEY });+ return result;+ } catch (cause) {+ setError(cause instanceof Error && cause.message ? cause.message : FAILED);+ return null;+ } finally {+ setBusy(null);+ }+ };++ const test = async () => {+ const result = await run<Result & { ok?: boolean; message?: string }>('test', 'mcp_connector_test');+ if (result) setNotice({ ok: result.ok === true, text: result.message ?? '' });+ };++ const refresh = async () => {+ const result = await run<Result & { changes?: unknown }>('refresh', 'mcp_connector_refresh');+ if (result && !result.changes) setNotice({ ok: true, text: 'Nothing changed: the tools are as you accepted them.' });+ };++ const setTool = async (tool: string, change: ToolChange) => {+ setChanging({ tool, ...change });+ await run('tool', 'mcp_connector_set_tool', { tool, ...change });+ setChanging(null);+ };++ const remove = async () => {+ setRemoving(false);+ if (await run('remove', 'mcp_connector_remove')) {+ toast.info(`${config.name} removed`);+ onLeave?.();+ }+ };++ const shown = (tool: ServerMcpTool): ServerMcpTool =>+ changing?.tool === tool.name ? { ...tool, enabled: changing.enabled ?? tool.enabled, ask: changing.ask ?? tool.ask } : tool;+ const server = [mcp.server.title || mcp.server.name, mcp.server.version].filter(Boolean).join(' ');+ const locked = !isReady || busy !== null;++ return (+ <div className="flex flex-col gap-4 p-5">+ {config.instructions && <p className="m-0 text-sm text-muted-foreground">{config.instructions}</p>}++ <dl className="m-0 grid grid-cols-[max-content_minmax(0,1fr)] gap-x-4 gap-y-1.5 text-sm">+ <dt className="text-muted-foreground">Server</dt>+ <dd className="m-0 truncate">{server || 'No name given'}</dd>+ <dt className="text-muted-foreground">Address</dt>+ <dd className="m-0 truncate font-mono text-xs leading-5">{mcp.address}</dd>+ <dt className="text-muted-foreground">Sign-in</dt>+ <dd className="m-0">{signInText(mcp.sign_in)}</dd>+ {showTechnicalSections && (+ <>+ <dt className="text-muted-foreground">Transport</dt>+ <dd className="m-0">{mcp.transport === 'sse' ? 'SSE' : 'Streamable HTTP'}</dd>+ </>+ )}+ <dt className="text-muted-foreground">Tools read</dt>+ <dd className="m-0">{formatTimestamp(mcp.read_at)}</dd>+ </dl>++ <div className="flex flex-wrap items-center gap-2">+ <ActionButton intent="run" disabled={locked} onClick={() => void test()}>+ {busy === 'test' ? 'Testing…' : 'Test'}+ </ActionButton>+ <ActionButton intent="config" disabled={locked} onClick={() => void refresh()}>+ {busy === 'refresh' ? 'Reading tools…' : 'Refresh tools'}+ </ActionButton>+ <ActionButton intent="stop" disabled={locked} onClick={() => setRemoving(true)} className="ml-auto">+ Remove+ </ActionButton>+ </div>+ {notice && (+ <p role="status" className={cn('m-0 text-sm', notice.ok ? 'text-success' : 'text-destructive')}>+ {notice.text}+ </p>+ )}+ {error && (+ <p role="alert" className="m-0 text-sm text-destructive">+ {error}+ </p>+ )}++ {mcp.pending && (+ <Alert variant="warning">+ <AlertTitle>The server changed its tools</AlertTitle>+ <AlertDescription className="flex flex-col gap-2">+ <ul className="m-0 list-none p-0">+ {pendingLines(mcp.pending).map((line) => (+ <li key={line}>{line}</li>+ ))}+ </ul>+ <p className="m-0">Employees keep the tools you accepted until you accept this change.</p>+ <div className="flex gap-2">+ <ActionButton intent="run" disabled={locked} onClick={() => void run('accept', 'mcp_connector_review', { accept: true })}>+ Accept+ </ActionButton>+ <Button variant="ghost" size="sm" disabled={locked} onClick={() => void run('discard', 'mcp_connector_review', { accept: false })}>+ Discard+ </Button>+ </div>+ </AlertDescription>+ </Alert>+ )}++ <section aria-labelledby={headingId} className="flex flex-col gap-2">+ <div className="flex items-baseline gap-2">+ <h3 id={headingId} className="m-0 text-sm font-medium">+ Tools+ </h3>+ <span className="font-mono text-xs text-muted-foreground">{mcp.tools.length}</span>+ </div>+ <p className="m-0 text-xs text-muted-foreground">+ While an employee asks first, a tool set to Ask first waits for your OK before it runs.+ </p>+ {mcp.tools.length === 0 ? (+ <p className="m-0 text-sm text-muted-foreground">The server offers no tools.</p>+ ) : (+ <ul className="m-0 flex list-none flex-col gap-2 p-0">+ {mcp.tools.map((tool) => (+ <ToolRow key={tool.name} tool={shown(tool)} disabled={locked} onChange={(change) => void setTool(tool.name, change)} />+ ))}+ </ul>+ )}+ </section>++ <AlertDialog open={removing} onOpenChange={setRemoving}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Remove {config.name}?</AlertDialogTitle>+ <AlertDialogDescription>+ Employees stop using its tools. You can add it again from its address.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Keep it</AlertDialogCancel>+ <AlertDialogAction onClick={() => void remove()}>Remove</AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}++function ToolRow({ tool, disabled, onChange }: { tool: ServerMcpTool; disabled: boolean; onChange: (change: ToolChange) => void }) {+ const id = useId();+ const label = tool.title || tool.name;+ return (+ <li className="flex items-start gap-3 rounded-md border border-border bg-card p-3">+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <div className="flex min-w-0 items-center gap-2">+ <span className="truncate text-sm font-medium">{label}</span>+ {tool.read_only && <Badge variant="secondary">Read-only</Badge>}+ </div>+ {tool.title && <span className="truncate font-mono text-xs text-muted-foreground">{tool.name}</span>}+ {tool.description && <p className="m-0 line-clamp-2 text-xs text-muted-foreground">{tool.description}</p>}+ {!tool.usable && <p className="m-0 text-xs text-warning">Can't be used. {tool.reason}</p>}+ </div>+ {tool.usable && (+ <div className="grid shrink-0 grid-cols-[auto_auto] items-center gap-x-2 gap-y-1.5 text-xs">+ <Label htmlFor={`${id}-use`} className="text-xs font-normal">+ Use+ </Label>+ <Switch+ id={`${id}-use`}+ size="sm"+ checked={tool.enabled}+ disabled={disabled}+ aria-label={`Let employees use ${label}`}+ onCheckedChange={(enabled) => onChange({ enabled })}+ />+ <Label htmlFor={`${id}-ask`} className="text-xs font-normal">+ Ask first+ </Label>+ <Switch+ id={`${id}-ask`}+ size="sm"+ checked={tool.ask}+ disabled={disabled || !tool.enabled}+ aria-label={`Ask first before ${label}`}+ onCheckedChange={(ask) => onChange({ ask })}+ />+ </div>+ )}+ </li>+ );+}diff --git a/client/src/components/credentials/panels/__tests__/McpConnectorPanel.test.tsx b/client/src/components/credentials/panels/__tests__/McpConnectorPanel.test.tsxnew file mode 100644index 00000000..a45c90fb--- /dev/null+++ b/client/src/components/credentials/panels/__tests__/McpConnectorPanel.test.tsx@@ -0,0 +1,121 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { ServerMcpConnector } from '@/hooks/useCatalogueQuery';+import type { ProviderConfig } from '../../types';++const mocks = vi.hoisted(() => ({ sendRequest: vi.fn() }));+vi.mock('@/contexts/WebSocketContext', () => ({+ useWebSocketActions: () => ({ sendRequest: mocks.sendRequest, isReady: true }),+ CREDENTIAL_PROBE_REQUEST_TIMEOUT: 60_000,+}));+vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }));++import McpConnectorPanel from '../McpConnectorPanel';++const MCP: ServerMcpConnector = {+ slug: 'orders',+ address: 'https://orders.example.com/mcp',+ transport: 'streamable_http',+ sign_in: { kind: 'header', header: 'X-API-Key' },+ server: { name: 'orders', title: 'Orders', version: '1.2.0' },+ tools: [+ { name: 'lookup_order', title: 'Look up an order', description: 'What an order holds.', read_only: true, usable: true, reason: null, enabled: true, ask: false },+ { name: 'send_reply', title: null, description: 'Reply to a customer.', read_only: false, usable: true, reason: null, enabled: true, ask: true },+ { name: 'listing', title: null, description: '', read_only: false, usable: false, reason: "Its inputs aren't described as an object.", enabled: false, ask: true },+ ],+ pending: null,+ read_at: '2026-10-09T10:00:00+00:00',+};++function config(mcp: Partial<ServerMcpConnector>): ProviderConfig {+ return { id: 'mcp:orders', name: 'Orders', category: 'custom', categoryLabel: 'Custom', color: '', kind: 'mcp', iconRef: 'lucide:Plug', mcp: { ...MCP, ...mcp } };+}++function mount({ mcp = {}, onLeave }: { mcp?: Partial<ServerMcpConnector>; onLeave?: () => void } = {}) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const invalidate = vi.spyOn(client, 'invalidateQueries');+ render(+ <QueryClientProvider client={client}>+ <McpConnectorPanel config={config(mcp)} visible onLeave={onLeave} />+ </QueryClientProvider>,+ );+ return { invalidate };+}++beforeEach(() => {+ mocks.sendRequest.mockReset().mockResolvedValue({ success: true });+});++describe('McpConnectorPanel', () => {+ it('shows the server, how it signs in, and each tool as the server describes it', () => {+ mount();+ expect(screen.getByText('Orders 1.2.0')).toBeInTheDocument();+ expect(screen.getByText('https://orders.example.com/mcp')).toBeInTheDocument();+ expect(screen.getByText('Header X-API-Key')).toBeInTheDocument();+ expect(screen.getByText('Look up an order')).toBeInTheDocument();+ expect(screen.getByText('Read-only')).toBeInTheDocument();+ expect(screen.getByText("Can't be used. Its inputs aren't described as an object.")).toBeInTheDocument();+ // A tool no model could call has no switches.+ expect(screen.queryByRole('switch', { name: 'Let employees use listing' })).not.toBeInTheDocument();+ expect(screen.getByRole('switch', { name: 'Ask first before Look up an order' })).not.toBeChecked();+ expect(screen.getByRole('switch', { name: 'Ask first before send_reply' })).toBeChecked();+ });++ it('tests the connection and says what the server answered', async () => {+ mocks.sendRequest.mockResolvedValue({ success: true, ok: false, message: "Couldn't connect to orders.example.com. Check that the server is running." });+ const user = userEvent.setup();+ mount();+ await user.click(screen.getByRole('button', { name: 'Test' }));+ expect(mocks.sendRequest).toHaveBeenCalledWith('mcp_connector_test', { ref: 'mcp:orders' }, 60_000);+ expect(await screen.findByRole('status')).toHaveTextContent("Couldn't connect to orders.example.com.");+ });++ it('says so when a refresh found nothing new, and shows a refusal in the server words', async () => {+ mocks.sendRequest.mockResolvedValueOnce({ success: true, changes: null });+ const user = userEvent.setup();+ mount();+ await user.click(screen.getByRole('button', { name: 'Refresh tools' }));+ expect(await screen.findByRole('status')).toHaveTextContent('Nothing changed');+ mocks.sendRequest.mockResolvedValueOnce({ success: false, error: 'orders.example.com refused the sign-in (HTTP 401). Check the token or header.' });+ await user.click(screen.getByRole('button', { name: 'Refresh tools' }));+ expect(await screen.findByText('orders.example.com refused the sign-in (HTTP 401). Check the token or header.')).toHaveAttribute('role', 'alert');+ });++ it('holds what a refresh found until the owner accepts it', async () => {+ const user = userEvent.setup();+ const { invalidate } = mount({ mcp: { pending: { added: ['refund_order'], removed: [], changed: ['send_reply'], instructions: true, read_at: MCP.read_at } } });+ expect(screen.getByText('The server changed its tools')).toBeInTheDocument();+ expect(screen.getByText('New: refund_order')).toBeInTheDocument();+ expect(screen.getByText('Changed: send_reply')).toBeInTheDocument();+ expect(screen.getByText("The server's instructions changed.")).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Accept' }));+ expect(mocks.sendRequest).toHaveBeenCalledWith('mcp_connector_review', { ref: 'mcp:orders', accept: true }, 60_000);+ await waitFor(() => expect(invalidate).toHaveBeenCalledWith({ queryKey: ['credentialCatalogue'] }));+ });++ it('turns a tool off, showing the new position while the server saves it', async () => {+ let answer: (value: unknown) => void = () => undefined;+ mocks.sendRequest.mockImplementation(() => new Promise((resolve) => (answer = resolve)));+ const user = userEvent.setup();+ const { invalidate } = mount();+ const use = screen.getByRole('switch', { name: 'Let employees use send_reply' });+ await user.click(use);+ expect(mocks.sendRequest).toHaveBeenCalledWith('mcp_connector_set_tool', { ref: 'mcp:orders', tool: 'send_reply', enabled: false }, 60_000);+ expect(use).not.toBeChecked();+ answer({ success: true, tool: 'send_reply', enabled: false, ask: true });+ await waitFor(() => expect(invalidate).toHaveBeenCalledWith({ queryKey: ['credentialCatalogue'] }));+ });++ it('removes the connector only after a confirmation, then leaves its page', async () => {+ const onLeave = vi.fn();+ const user = userEvent.setup();+ mount({ onLeave });+ await user.click(screen.getByRole('button', { name: 'Remove' }));+ expect(mocks.sendRequest).not.toHaveBeenCalled();+ await user.click(within(screen.getByRole('alertdialog')).getByRole('button', { name: 'Remove' }));+ await waitFor(() => expect(onLeave).toHaveBeenCalledTimes(1));+ expect(mocks.sendRequest).toHaveBeenCalledWith('mcp_connector_remove', { ref: 'mcp:orders' }, 60_000);+ });+});diff --git a/client/src/components/credentials/types.ts b/client/src/components/credentials/types.tsindex 3a8f675e..7e10d602 100644--- a/client/src/components/credentials/types.ts+++ b/client/src/components/credentials/types.ts@@ -5,14 +5,14 @@*/import type { ActionButtonIntent } from '@/components/ui/action-button';-import type { ServerEndpointSummary } from '@/hooks/useCatalogueQuery';+import type { ServerEndpointSummary, ServerMcpConnector } from '@/hooks/useCatalogueQuery';export type { ActionButtonIntent };// ============================================================================// Panel kinds — one renderer branch per kind// ============================================================================-export type PanelKind = 'apiKey' | 'oauth' | 'qrPairing' | 'email' | 'browserProfiles';+export type PanelKind = 'apiKey' | 'oauth' | 'qrPairing' | 'email' | 'browserProfiles' | 'mcp';// ============================================================================// Field schema — drives antd Form.Item rendering via FieldRenderer@@ -132,6 +132,8 @@ export interface ProviderConfig {* endpoints). Present only for such providers; the panel then adds rows* instead of storing one value. */endpoints?: ServerEndpointSummary[];+ /** A custom MCP connector's server and tools (kind `mcp`). */+ mcp?: ServerMcpConnector;/** Server capability, never inferred from a provider name. */sourceSupported?: boolean;sourceRequired?: boolean;diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex 6bc65d37..9af5b2a0 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -82,6 +82,8 @@ export const WORKFLOW_CONTROL_REQUEST_TIMEOUT = 5 * 60 * 1000;// URL, detects the server's kind and lists its models. The backend bounds// each step (nodes/model/_local_validator.py); this stays above their sum, so// a slow save is not cut off here and then completes behind the user's back.+// A custom MCP connector's add, test and refresh read its server within the+// backend's DISCOVER_S (nodes/mcp/_client.py), also below this.export const CREDENTIAL_PROBE_REQUEST_TIMEOUT = 60 * 1000;// Maximum queued sends before backpressure kicks in (FIFO eviction of oldest)diff --git a/client/src/features/home/onboarding/steps/ConnectStep.tsx b/client/src/features/home/onboarding/steps/ConnectStep.tsxindex 429a589f..67a31d20 100644--- a/client/src/features/home/onboarding/steps/ConnectStep.tsx+++ b/client/src/features/home/onboarding/steps/ConnectStep.tsx@@ -69,6 +69,7 @@ export function ConnectStep({ onFinish }: { onFinish: () => void }) {variant="embedded"discoverLimit={null}onItemAdded={onItemAdded}+ customConnectors={false}/></div>{selection && (diff --git a/client/src/hooks/useCatalogueQuery.ts b/client/src/hooks/useCatalogueQuery.tsindex b33675fa..b6104d5d 100644--- a/client/src/hooks/useCatalogueQuery.ts+++ b/client/src/hooks/useCatalogueQuery.ts@@ -103,6 +103,38 @@ export interface ServerEndpointSummary {model_count: number;}+/** One tool of a custom MCP connector, with the owner's settings for it. */+export interface ServerMcpTool {+ name: string;+ title: string | null;+ description: string;+ /** The server says the tool only reads; Ask first starts off for it. */+ read_only: boolean;+ /** False when no model could call the tool; `reason` says why. */+ usable: boolean;+ reason: string | null;+ /** Employees may use it. */+ enabled: boolean;+ /** A call waits for the owner while they ask first. */+ ask: boolean;+}++/** A custom MCP connector on its card (`kind: 'mcp'`, nodes/mcp/_credentials.py). */+export interface ServerMcpConnector {+ slug: string;+ /** The server's URL, without credentials. */+ address: string;+ transport: 'streamable_http' | 'sse';+ /** How it signs in; never the token or header value. */+ sign_in: { kind: 'none' | 'bearer' | 'header'; header?: string };+ server: { name?: string; title?: string | null; version?: string };+ tools: ServerMcpTool[];+ /** What a refresh found, waiting for the owner to accept or discard. */+ pending: { added: string[]; removed: string[]; changed: string[]; instructions: boolean; read_at: string } | null;+ /** When the tools were last read. */+ read_at: string;+}+/** One entry as it appears in the `providers` array of the catalogue response. */export interface ServerProviderConfig {id: string;@@ -112,7 +144,7 @@ export interface ServerProviderConfig {category: string;category_label: string;color: string;- kind: 'apiKey' | 'oauth' | 'qrPairing' | 'email' | 'browserProfiles';+ kind: 'apiKey' | 'oauth' | 'qrPairing' | 'email' | 'browserProfiles' | 'mcp';icon_ref?: string;fields?: ServerFieldDef[];ws?: { login: string; logout: string; status: string };@@ -149,6 +181,8 @@ export interface ServerProviderConfig {verified?: boolean;/** The provider runs on this computer (Ollama, LM Studio). */runs_locally?: boolean;+ /** A custom MCP connector's server and tools (`kind: 'mcp'`). */+ mcp?: ServerMcpConnector;}export interface CatalogueResponse {diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.mdindex 2931fd77..56c46cdc 100644--- a/docs-internal/frontend_architecture.md+++ b/docs-internal/frontend_architecture.md@@ -112,6 +112,7 @@ client/src/│ ├── credentials/ # EXEMPLAR SUBSYSTEM — see "Credentials" section below│ │ ├── CredentialsModal.tsx # Shared app-level browser + provider dialogs│ │ ├── CredentialsBrowser.tsx # Connector cards; also embedded in Home Settings and the Welcome guide+│ │ ├── AddConnectorForm.tsx # The page's Add form: a custom MCP connector's URL, name and sign-in│ │ ├── ProviderPage.tsx # One provider's page: back, key link, PanelRenderer (dialog + guide)│ │ ├── aiProviderLinks.ts # Where to get each AI provider's key│ │ ├── catalogue.ts # Shared catalogue ordering + category visibility@@ -126,6 +127,7 @@ client/src/│ │ │ ├── QrPairingPanel.tsx # WhatsApp / Android│ │ │ ├── EmailPanel.tsx # IMAP/SMTP (RHF + zod)│ │ │ ├── BrowserProfilesPanel.tsx # Web browser login profiles: list / add / delete, session-file import+│ │ │ ├── McpConnectorPanel.tsx # A custom MCP connector: Test, Refresh (a change waits for Accept), Remove, each tool's Use / Ask first│ │ │ └── schemas/email.ts # Email zod schema w/ superRefine│ │ ├── sections/│ │ │ ├── ApiUsageSection.tsx # Per-service usage/cost@@ -408,7 +410,7 @@ components/credentials/catalogueAdapter.ts (hydrate JSON -> ProviderConfig)components/credentials/CredentialsModal.tsx (one AppShell host)├─ CredentialsBrowser.tsx (shared cards, also embedded in Home Settings and the Welcome guide)└─ ProviderPage.tsx (one provider; the Welcome guide shows it inline)- └─ PanelRenderer.tsx (lazy: ApiKey/OAuth/QrPairing/Email/BrowserProfiles)+ └─ PanelRenderer.tsx (lazy: ApiKey/OAuth/QrPairing/Email/BrowserProfiles/McpConnector)```**State rules:**@@ -434,6 +436,7 @@ components/credentials/CredentialsModal.tsx (one AppShell host)- `PanelRenderer` lazy-loads each panel type so the initial JS payload doesn't grow linearly with provider count.- Panels are config-driven: `StatusCard`, `ActionBar`, `FieldRenderer`, `OAuthConnect` consume `ProviderConfig` fields rather than hand-coding per-provider JSX.- Exception: EmailPanel has conditional `custom` IMAP/SMTP fields that the simple schema can't express — it gets a dedicated zod schema and RHF form. That's the boundary where config-driven hands off to hand-written.+- Custom MCP connectors are cards the server builds, one per saved connector (`kind: 'mcp'`, with an `mcp` block: server, address, sign-in kind, tools, pending change). The browser's Add (`CatalogLayout.primaryAction`, off in the Welcome guide via `customConnectors={false}`) opens `AddConnectorForm`; after `mcp_connector_add` it refetches the catalogue, then opens the new card's page. `McpConnectorPanel` sends each command with `CREDENTIAL_PROBE_REQUEST_TIMEOUT` and waits for the refetched catalogue before re-enabling, so it shows only what the server holds; Remove leaves the page through the panel's `onLeave` (ProviderPage's Back). See [MCP Connectors](./mcp_connectors.md).## ParameterRenderer (pending Phase 6)diff --git a/docs-internal/mcp_connectors.md b/docs-internal/mcp_connectors.mdnew file mode 100644index 00000000..eb79a151--- /dev/null+++ b/docs-internal/mcp_connectors.md@@ -0,0 +1,148 @@+# MCP Connectors++The owner connects OpenCompany to an outside MCP server from Connectors →+**Add**: its URL, a name, and how it signs in. Each saved connector is its own+card on the Connectors page, and its tools are what that server offers.++Here OpenCompany is the MCP **client**. The opposite direction, where CLI+agents call into OpenCompany's own MCP server (`/mcp/ide`), is a separate+thing: see [CLI Agent Framework](./cli_agent_framework.md).++## Where it lives++| Part | Path |+|---|---|+| Talking to a server (official `mcp` SDK), where a connector may connect | `server/nodes/mcp/_client.py` |+| What is kept (two credential rows) | `server/nodes/mcp/_store.py` |+| One catalogue card per connector | `server/nodes/mcp/_credentials.py` |+| The Connectors page's commands | `server/nodes/mcp/_handlers.py` |+| The outbound address rules, shared with the Browser node | `server/services/netpolicy.py` |+| The cards' shared fields, and the `custom` categories | `server/config/credential_providers.json` (`_mcp_connector`) |+| The Add form | `client/src/components/credentials/AddConnectorForm.tsx` |+| A connector's page | `client/src/components/credentials/panels/McpConnectorPanel.tsx` |+| The card's wire type | `ServerMcpConnector` in `client/src/hooks/useCatalogueQuery.ts` |++## Adding a connector++`mcp_connector_add {name?, url, sign_in: {kind, token?, header?, value?}}`+reads the server first and saves the connector only when it answered, so a+wrong URL or a refused sign-in comes back in words for the owner and nothing+is kept.++- **Sign-in**: none, a bearer token, or one header of the owner's choosing.+ It is sent as a header. A header the transport sets itself (`Host`,+ `Content-Type`, `Mcp-Session-Id`, `Mcp-Protocol-Version` and the like) is+ refused, as is a line break in a value.+- **Where it may connect** (`check_server`):+ - The URL must be http or https and carry no user or password.+ - The host and every address it resolves to are checked against+ `services/netpolicy.py`. Cloud metadata, link-local addresses and+ OpenCompany's own ports are never reached. The owner's own network is+ allowed, so a local MCP server works.+ - Plain http is allowed only to this machine or the owner's network: over+ the internet it would carry the sign-in in clear.+ - The addresses are checked when connecting, not pinned for the connection.+- **The connection**: our own httpx client with redirects off, so a server+ cannot bounce the sign-in to another host. The transport is streamable+ HTTP, then the older SSE transport for a server that refuses it (the MCP+ spec's fallback); the one that answered is kept.+- **Time**: reading a server, every transport included, takes at most+ `DISCOVER_S` (45 s). The app waits 60 s for these commands+ (`CREDENTIAL_PROBE_REQUEST_TIMEOUT`), so a slow read never finishes after+ the app gave up on it.+- **Its name**: the slug comes from the name, or else from the host+ (python-slugify, at most 20 characters). A second connector needs its own+ name.++## What is kept++Two rows through `AuthService`, the way named OpenAI-compatible endpoints are+kept:++- `mcp:<slug>`: the sign-in, encrypted. Its `model_params["_mcp"]` holds the+ rest in plain text, so no secret ever goes there:+ - the name and host;+ - the address, without credentials;+ - the transport;+ - the sign-in's kind, and its header name;+ - the server's name, title and version;+ - its instructions;+ - the tools as last accepted, with the owner's settings for them;+ - a refresh waiting to be accepted;+ - when the tools were read.+- `mcp:<slug>_proxy`: the URL, encrypted, since it may carry a key.++**Tools.** Up to 500. Each is kept as the server described it: name, title,+description (up to 4,000 characters), input schema, and the read-only hint.+A tool no model could call is kept with the reason and never renamed:+- its name repeats another;+- `<slug>__<tool>` breaks the strictest provider's rule,+ `^[A-Za-z0-9_-]{1,64}$`;+- its input schema is not an object, or is not valid JSON Schema.++**Settings.** Each usable tool has `{enabled, ask}`. It starts on, and asks+first unless the server marks it read-only. The owner changes both per tool.++## The card++`Credential.catalogue_entries` (`services/plugin/credential.py`) is a+generic hook: `handle_get_credential_catalogue` appends what every credential+class returns from it. `McpConnectorCredential.catalogue_entries` builds one+card per saved connector from the `_mcp_connector` template+(`CredentialRegistry.get_template`). Each card has:+- `id` `mcp:<slug>` and `kind` `mcp`;+- `consumer_category` `custom`, publisher "you", not verified;+- the description "Custom connection · {host}";+- `stored` and `connected` true;+- an `mcp` block: slug, address, transport, sign-in kind, server, tools with+ their settings, the waiting change, and when the tools were read.++No secret is ever on the card.++## Commands++All are `@ws_response`. They are refused from `/ws/internal`. Each change is+announced as `credential.api_key.saved` or `credential.api_key.deleted` for+the connector, and `AuthService` bumps the catalogue version, so every open+page refetches.++| Command | Sends | Returns |+|---|---|---|+| `mcp_connector_add` | `{name?, url, sign_in}` | `{ref, tools}` |+| `mcp_connector_test` | `{ref}` | `{ok, message}`; saves nothing |+| `mcp_connector_refresh` | `{ref}` | `{changes}`, null when nothing changed |+| `mcp_connector_review` | `{ref, accept}` | `{accepted}` |+| `mcp_connector_set_tool` | `{ref, tool, enabled?, ask?}` | `{tool, enabled, ask}` |+| `mcp_connector_remove` | `{ref}` | `{ref}` |++**Refresh holds changes.** A server can change what a tool says it does, so+Refresh never adopts what it read. Tools added, removed or changed in any+way, or new instructions, wait as `pending` until the owner takes or drops+them with `mcp_connector_review`. Until then, the tools the owner accepted+stay as they were. Accepting keeps the owner's settings for tools already+set; new usable tools get the defaults.++## The page++- **Add** on the Connectors page (`CatalogLayout.primaryAction`) opens+ `AddConnectorForm`. After a save, the catalogue is refetched, then the new+ connector's page opens. The Welcome guide's AI model step has no Add+ (`customConnectors={false}`).+- **`McpConnectorPanel`** shows:+ - the server, its address, how it signs in (and, in Dev, the transport),+ and when its tools were read;+ - Test, Refresh tools and Remove;+ - a waiting change, with Accept and Discard;+ - each tool with its Use and Ask first switches. A tool no model could call+ shows why, and has no switches.++ Each command waits for the refetched catalogue, so the page shows only what+ the server holds. Remove asks first, then goes back to the list.+- **Disconnect** on a connector's card removes it too.++## Known gaps++- No employee uses a connector's tools yet.+- No OAuth sign-in.+- A host's addresses are checked when connecting, not pinned for the+ connection.diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.mdindex 12072c1e..c3ec5599 100644--- a/docs-internal/normal_mode.md+++ b/docs-internal/normal_mode.md@@ -962,9 +962,10 @@ changing page clears it.`tests/test_home_catalog_contract.py` holds the bundles and the Discoverfolder to each other and to the app registry.- **Connectors**: every provider in `config/credential_providers.json`, the- same set as the editor's Credentials modal. Each declares a+ same set as the editor's Credentials modal, plus one card for each custom+ connector the owner added. Each declares a`consumer_category` (`messages`, `organize`, `business`, `research`,- `language`, `developer`, `devices`, `ai`), a short `description`, a+ `language`, `developer`, `devices`, `custom`, `ai`), a short `description`, a`publisher` (the card's "by …" line) and `verified`, and`test_credential_catalogue_consumer_fields.py` fails when one does not, orwhen a plugin credential has no catalogue entry at all, so a new connector@@ -972,7 +973,14 @@ changing page clears it.come before AI models. The catalogue adds `connected`, which differs from`stored` for providers with a `connected_check` (WhatsApp's live pairing,the IMAP/SMTP account's keys; `builtin`, always connected, for the Web- browser, whose panel manages optional login profiles).+ browser, whose panel manages optional login profiles). **Add** opens the+ custom connector form (`components/credentials/AddConnectorForm.tsx`): an+ MCP server's URL, a name, and how it signs in. The server reads the+ server's tools before it keeps anything, and the new connector's page opens+ once the catalogue holds it. That page tests the connection, refreshes the+ tools (a change waits for Accept), sets each tool on or off and to ask+ first, and removes the connector. See [MCP Connectors](./mcp_connectors.md).+ The Welcome guide's AI model step has no Add.**The catalog page** ([settings/CatalogLayout.tsx](../client/src/features/home/settings/CatalogLayout.tsx)).The implementation is shared in `components/catalog/`; Home paths are compatibility exports.@@ -1086,7 +1094,9 @@ chat's rollback), `lib/__tests__/workflowOps.test.ts` and- Billing has no plans, payment method or invoices: no billing account sitsbehind OpenCompany. A deleted employee's runs leave the month's count,because deleting a workflow deletes its run records.-- Connectors has no custom (MCP) connector.+- A custom (MCP) connector's tools reach no employee yet: the connector is+ kept, tested and refreshed, and its tools set, but no hire or agent uses+ them.- Skill library changes reach only new hires: an employee keeps the skills itwas hired with, and one hired before the library existed has none, untilthe owner asks them in Talk to add one. The library is shared across usersdiff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.mdindex cb0651f2..5df9c94b 100644--- a/docs-internal/plugin_system.md+++ b/docs-internal/plugin_system.md@@ -396,6 +396,16 @@ double-imported. Contract invariant`test_credentials_are_registered` ensures every declared credentialon a plugin resolves to a registered class.+**Cards built from what was saved**: a credential whose cards are the+owner's own entries, not one fixed provider, overrides the async+classmethod `catalogue_entries(*, principal=None)` (default `[]`).+`get_credential_catalogue` appends what every registered class returns,+after the static providers, and those cards carry their own `stored` /+`connected`. Shared card fields come from an `_abstract` template in+`credential_providers.json`, read with `CredentialRegistry.get_template`.+`nodes/mcp/_credentials.py` is the one user: one card per custom MCP+connector ([MCP Connectors](./mcp_connectors.md)).+**Shipped credentials** (Wave 11.E → E.1):| File | Class(es) | Auth | Covers |diff --git a/server/nodes/mcp/_client.py b/server/nodes/mcp/_client.pyindex b341156c..8a6cf499 100644--- a/server/nodes/mcp/_client.py+++ b/server/nodes/mcp/_client.py@@ -51,8 +51,11 @@ TRANSPORTS: Tuple[Transport, ...] = ("streamable_http", "sse")#: A connect, the opening handshake, or one listing of tools.TIMEOUT_S = 30.0-#: Reading the server's tools, from connecting to the last page.-DISCOVER_S = 60.0+#: Reading the server's tools, from connecting to the last page, with every+#: transport tried. The app waits 60 s for a credential probe+#: (CREDENTIAL_PROBE_REQUEST_TIMEOUT in WebSocketContext.tsx), so a slow read+#: is never still saving after the app gave up on it.+DISCOVER_S = 45.0#: The longest a tool call may take to answer.CALL_TIMEOUT_S = 300.0#: The most tools one connector reads.@@ -252,9 +255,8 @@ async def read_server(url: str, sign_in: SignIn, transport: Transport, *, http_transport: Optional[httpx.AsyncBaseTransport] = None) -> Discovery:"""Connect over ``transport`` and read what the server offers."""- async with asyncio.timeout(DISCOVER_S):- async with open_session(url, sign_in, transport, http_transport=http_transport) as (session, init):- tools = await list_tools(session)+ async with open_session(url, sign_in, transport, http_transport=http_transport) as (session, init):+ tools = await list_tools(session)server = init.serverInforeturn Discovery(transport=transport,@@ -266,24 +268,31 @@ async def read_server(async def discover(url: str, sign_in: SignIn, *, http_transport: Optional[httpx.AsyncBaseTransport] = None) -> Discovery:"""A new connector's first read: streamable HTTP, else the older SSE- transport. Raises ``ConnectorError`` with the first transport's failure."""+ transport, within ``DISCOVER_S`` in all. Raises ``ConnectorError`` with+ the first transport's failure."""host = await check_server(url)first: Optional[BaseException] = None- for transport in TRANSPORTS:- try:- return await read_server(url, sign_in, transport, http_transport=http_transport)- except Exception as exc: # noqa: BLE001 - described below, in words for the owner- first = first or exc+ try:+ async with asyncio.timeout(DISCOVER_S):+ for transport in TRANSPORTS:+ try:+ return await read_server(url, sign_in, transport, http_transport=http_transport)+ except Exception as exc: # noqa: BLE001 - described below, in words for the owner+ first = first or exc+ except TimeoutError as exc:+ first = first or excraise ConnectorError(describe(first, host))async def read_again(url: str, sign_in: SignIn, transport: Transport, *, http_transport: Optional[httpx.AsyncBaseTransport] = None) -> Discovery:- """Read a saved connector's server again (Test, Refresh)."""+ """Read a saved connector's server again (Test, Refresh), within+ ``DISCOVER_S``."""host = await check_server(url)try:- return await read_server(url, sign_in, transport, http_transport=http_transport)+ async with asyncio.timeout(DISCOVER_S):+ return await read_server(url, sign_in, transport, http_transport=http_transport)except Exception as exc: # noqa: BLE001 - described below, in words for the ownerraise ConnectorError(describe(exc, host)) from Nonediff --git a/server/nodes/mcp/_handlers.py b/server/nodes/mcp/_handlers.pyindex a570d8e7..f015b61a 100644--- a/server/nodes/mcp/_handlers.py+++ b/server/nodes/mcp/_handlers.py@@ -10,6 +10,9 @@``pending`` for the owner, since a server can change what a tool says itdoes; ``{changes}``, null when nothing changed.- ``mcp_connector_review`` ``{ref, accept}``: takes or drops that change.+- ``mcp_connector_set_tool`` ``{ref, tool, enabled?, ask?}``: whether+ employees may use one of its tools, and whether that tool asks the owner+ first; ``{tool, enabled, ask}``.- ``mcp_connector_remove`` ``{ref}``.``@ws_response``: a failure the owner can fix (a wrong URL, a refused@@ -152,6 +155,27 @@ async def handle_mcp_connector_review(data: Dict[str, Any], websocket: WebSocketreturn {"success": True, "accepted": accept}+@ws_response+async def handle_mcp_connector_set_tool(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ if refused := _refused(websocket):+ return refused+ name = str(data.get("tool") or "")+ try:+ connector = await get_connector(str(data.get("ref") or ""), principal=_principal(websocket))+ tool = next((tool for tool in connector.tools if tool["name"] == name), None)+ if tool is None:+ raise ConnectorError("This connector has no such tool.")+ if not tool["usable"]:+ raise ConnectorError(f"{name} can't be used. {tool['reason']}")+ setting = dict(default_settings([tool], kept=connector.settings)[name])+ setting.update({key: data[key] for key in ("enabled", "ask") if isinstance(data.get(key), bool)})+ await save_meta(connector, dict(connector.meta, settings={**connector.settings, name: setting}))+ except ConnectorError as exc:+ raise NodeUserError(str(exc)) from None+ await _announce(connector.ref, "saved")+ return {"success": True, "tool": name, **setting}++@ws_responseasync def handle_mcp_connector_remove(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:if refused := _refused(websocket):@@ -169,6 +193,7 @@ WS_HANDLERS = {"mcp_connector_test": handle_mcp_connector_test,"mcp_connector_refresh": handle_mcp_connector_refresh,"mcp_connector_review": handle_mcp_connector_review,+ "mcp_connector_set_tool": handle_mcp_connector_set_tool,"mcp_connector_remove": handle_mcp_connector_remove,}diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex e2cee1c2..c9f7de3a 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -391,10 +391,12 @@ async def handle_get_node_groups(data: Dict[str, Any], websocket: WebSocket) ->async def handle_get_credential_catalogue(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:"""Return the full credential provider catalogue with live stored-key status.- Response shape: {providers, categories, version}. Each provider includes- a `stored: boolean` field indicating whether a key/token is present in the- encrypted credentials database. The frontend renders this directly — no- client-side credential checks needed.+ Response shape: {providers, categories, consumer_categories, version}.+ Each provider includes a `stored: boolean` field indicating whether a+ key/token is present in the encrypted credentials database. The frontend+ renders this directly — no client-side credential checks needed. Cards a+ plugin builds from what was saved (`Credential.catalogue_entries`, one+ per custom MCP connector) follow the static providers."""from services.credential_registry import get_credential_registry, provider_connection_statediff --git a/server/tests/nodes/test_mcp_connector.py b/server/tests/nodes/test_mcp_connector.pyindex f60c1f76..f365b322 100644--- a/server/tests/nodes/test_mcp_connector.py+++ b/server/tests/nodes/test_mcp_connector.py@@ -299,6 +299,41 @@ class TestTheConnectorsPage:meta = auth.meta("mcp:orders")assert meta["instructions"] == "Look an order up before replying." and meta["pending"] is None+ async def test_each_tool_can_be_turned_off_or_set_to_ask_first(self, auth, monkeypatch):+ async with serving(monkeypatch, orders_server()):+ await add()+ set_tool = _handlers.handle_mcp_connector_set_tool+ assert await set_tool({"ref": "mcp:orders", "tool": "lookup_order", "ask": True}, SOCKET) == {+ "success": True,+ "tool": "lookup_order",+ "enabled": True,+ "ask": True,+ }+ await set_tool({"ref": "mcp:orders", "tool": "send_reply", "enabled": False}, SOCKET)+ assert auth.meta("mcp:orders")["settings"] == {+ "lookup_order": {"enabled": True, "ask": True},+ "send_reply": {"enabled": False, "ask": True},+ }+ # A change the owner accepts later keeps what they chose.+ async with serving(monkeypatch, orders_server(refund=True)):+ await _handlers.handle_mcp_connector_refresh({"ref": "mcp:orders"}, SOCKET)+ await _handlers.handle_mcp_connector_review({"ref": "mcp:orders", "accept": True}, SOCKET)+ assert auth.meta("mcp:orders")["settings"]["send_reply"] == {"enabled": False, "ask": True}++ async def test_a_tool_no_model_could_call_cannot_be_turned_on(self, auth, monkeypatch):+ async with serving(monkeypatch, orders_server()):+ await add()+ auth.meta("mcp:orders")["tools"][0].update(usable=False, reason="Its inputs aren't valid JSON Schema.")+ set_tool = _handlers.handle_mcp_connector_set_tool+ assert await set_tool({"ref": "mcp:orders", "tool": "lookup_order", "enabled": True}, SOCKET) == {+ "success": False,+ "error": "lookup_order can't be used. Its inputs aren't valid JSON Schema.",+ }+ assert await set_tool({"ref": "mcp:orders", "tool": "refund_order"}, SOCKET) == {+ "success": False,+ "error": "This connector has no such tool.",+ }+async def test_remove_forgets_both_rows(self, auth, monkeypatch):async with serving(monkeypatch, orders_server()):await add()