Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(control-ui): add remote MCP server install wizard (C5)

Diego Zacarias804cf48e8804
diff --git a/control-ui/app/constants/routes.ts b/control-ui/app/constants/routes.ts
index c7ff329aa..18d1aa1c3 100644
--- a/control-ui/app/constants/routes.ts
+++ b/control-ui/app/constants/routes.ts
@@ -35,6 +35,7 @@ export const CONTROL_ROUTES = {
connectors: {
root: '/connectors',
new: '/connectors/new',
+ remoteNew: '/connectors/remote/new',
edit: (name: string) => `/connectors/${segment(name)}/edit`,
editTab: (name: string, tab: string) => `/connectors/${segment(name)}/edit/${segment(tab)}`,
},
diff --git a/control-ui/app/mcp-servers/page.tsx b/control-ui/app/mcp-servers/page.tsx
index 1e6eab8a7..da5a0fc04 100644
--- a/control-ui/app/mcp-servers/page.tsx
+++ b/control-ui/app/mcp-servers/page.tsx
@@ -418,6 +418,7 @@ export default function McpServersPage() {
deletingKey={deletingKey}
onRefresh={loadAll}
onCreate={() => router.push(CONTROL_ROUTES.connectors.new)}
+ onAddRemote={() => router.push(CONTROL_ROUTES.connectors.remoteNew)}
onInstallFromRegistry={() => router.push(CONTROL_ROUTES.marketplace.root)}
refreshing={loading}
loading={loading && mcpServers.length === 0}
diff --git a/control-ui/app/mcp-servers/remote/new/page.tsx b/control-ui/app/mcp-servers/remote/new/page.tsx
new file mode 100644
index 000000000..496a0904a
--- /dev/null
+++ b/control-ui/app/mcp-servers/remote/new/page.tsx
@@ -0,0 +1,34 @@
+'use client'
+
+import React from 'react'
+import { useRouter } from 'next/navigation'
+import { AddRemoteServerWizard } from '@components/AddRemoteServerWizard'
+import { AuthGate } from '@components/AuthGate'
+import { CreatePageHeader } from '@components/CreatePageHeader'
+import { DashboardLayout } from '@components/DashboardLayout'
+import { IconServer } from '@components/Sidebar/icons'
+import { CONTROL_ROUTES } from '@constants/routes'
+
+export default function AddRemoteServerPage() {
+ const router = useRouter()
+
+ return (
+ <AuthGate>
+ <DashboardLayout isDetailPage>
+ <AddRemoteServerWizard
+ onInstalled={() => router.push(CONTROL_ROUTES.connectors.root)}
+ onCancel={() => router.push(CONTROL_ROUTES.connectors.root)}
+ pageHeader={
+ <CreatePageHeader
+ icon={<IconServer />}
+ title="Add remote server"
+ subtitle="Discover a remote MCP server by URL and install it as an OAuth connector."
+ backLabel="Back to connectors"
+ onBack={() => router.push(CONTROL_ROUTES.connectors.root)}
+ />
+ }
+ />
+ </DashboardLayout>
+ </AuthGate>
+ )
+}
diff --git a/control-ui/components/AddRemoteServerWizard/constants.ts b/control-ui/components/AddRemoteServerWizard/constants.ts
new file mode 100644
index 000000000..939700a1a
--- /dev/null
+++ b/control-ui/components/AddRemoteServerWizard/constants.ts
@@ -0,0 +1,50 @@
+import type { RemoteDiscoverRegistrationMode } from '../../lib/remoteMcp.types'
+import type { GrantScopeOption } from './types'
+
+export const REMOTE_WIZARD_STEPS = ['Identify', 'Configure', 'Confirm'] as const
+
+export const REMOTE_WIZARD_STEP_DETAILS = [
+ {
+ description: 'URL, name, and agent context',
+ title: 'Identify the remote server',
+ subtitle: 'Enter the remote MCP server URL, name it, and pick the context to attach it to.',
+ },
+ {
+ description: 'Detected OAuth configuration',
+ title: 'Configure OAuth',
+ subtitle: 'Review what discovery detected and provide any credentials the server requires.',
+ },
+ {
+ description: 'Review and install',
+ title: 'Confirm and install',
+ subtitle: 'Review the pinned configuration, then install the remote connector.',
+ },
+] as const
+
+export const GRANT_SCOPE_OPTIONS: readonly GrantScopeOption[] = [
+ {
+ value: 'user',
+ label: 'Per user',
+ description: 'Each user authorizes and holds their own token (recommended).',
+ },
+ {
+ value: 'context',
+ label: 'Per context',
+ description: 'One shared token for everyone using this context.',
+ },
+]
+
+/** Short, operator-facing label for each detected registration mode. */
+export const REGISTRATION_MODE_LABEL: Record<RemoteDiscoverRegistrationMode, string> = {
+ cimd: 'Client ID Metadata Document (public client)',
+ dcr: 'Dynamic Client Registration',
+ manual: 'Pre-registered client required',
+}
+
+/** One-line explanation shown under the detected mode. */
+export const REGISTRATION_MODE_HINT: Record<RemoteDiscoverRegistrationMode, string> = {
+ cimd: 'This platform registers as a public client automatically — no credentials needed.',
+ dcr: 'This platform registers a client dynamically and manages its credentials for you.',
+ manual:
+ 'The server offers neither CIMD nor dynamic registration, so you must supply a pre-registered client_id and client_secret.',
+}
diff --git a/control-ui/components/AddRemoteServerWizard/index.tsx b/control-ui/components/AddRemoteServerWizard/index.tsx
new file mode 100644
index 000000000..10c5fe174
--- /dev/null
+++ b/control-ui/components/AddRemoteServerWizard/index.tsx
@@ -0,0 +1,469 @@
+'use client'
+
+import React, { useEffect, useMemo, useState } from 'react'
+import { CreateFlowPanel } from '@components/CreateFlowPanel'
+import { CreateStepFlow } from '@components/CreateStepFlow'
+import { useToast } from '@components/Toast'
+import { Button, Field, SelectInput, TextInput } from '@components/ui'
+import { getContexts, isSilentApiError } from '@lib/api'
+import type { ContextResource } from '@lib/api'
+import { contextResourceName } from '@lib/contextIdentity'
+import {
+ buildRemoteInstallRequest,
+ discoverRemoteServer,
+ displayClientMode,
+ getRemoteServerNameError,
+ installModeForRegistration,
+ installRemoteServer,
+ mapRemoteDiscoverError,
+ mapRemoteInstallError,
+ requiresPreRegisteredCredentials,
+ shouldWarnNoRefresh,
+} from '@lib/remoteMcp'
+import type { RemoteDetected, RemoteGrantScope } from '@lib/remoteMcp.types'
+import {
+ GRANT_SCOPE_OPTIONS,
+ REGISTRATION_MODE_HINT,
+ REGISTRATION_MODE_LABEL,
+ REMOTE_WIZARD_STEPS,
+ REMOTE_WIZARD_STEP_DETAILS,
+} from './constants'
+import type { AddRemoteServerWizardProps } from './types'
+
+const STEP_TITLE_ID = 'add-remote-server-step-title'
+
+export function AddRemoteServerWizard({
+ pageHeader,
+ onInstalled,
+ onCancel,
+}: AddRemoteServerWizardProps) {
+ const { showToast } = useToast()
+
+ const [step, setStep] = useState(0)
+
+ // Step 0 — identity
+ const [baseUrl, setBaseUrl] = useState('')
+ const [serverName, setServerName] = useState('')
+ const [contextRef, setContextRef] = useState('')
+ const [contexts, setContexts] = useState<ContextResource[]>([])
+ const [contextsError, setContextsError] = useState('')
+
+ // Detection. Editing the URL clears `detected` (see the baseUrl onChange), so
+ // a present `detected` always corresponds to the current URL (D-4: the pinned
+ // config is authoritative — a re-detect is forced whenever the URL changes).
+ const [detecting, setDetecting] = useState(false)
+ const [discoverError, setDiscoverError] = useState('')
+ const [detected, setDetected] = useState<RemoteDetected | null>(null)
+
+ // Step 1 — configuration
+ const [clientId, setClientId] = useState('')
+ const [clientSecret, setClientSecret] = useState('')
+ const [grantScope, setGrantScope] = useState<RemoteGrantScope>('user')
+
+ // Step 2 — install
+ const [installing, setInstalling] = useState(false)
+ const [installError, setInstallError] = useState('')
+
+ useEffect(() => {
+ let cancelled = false
+ ;(async () => {
+ try {
+ const res = await getContexts()
+ if (!cancelled) setContexts(res.items ?? [])
+ } catch (e) {
+ if (isSilentApiError(e)) return
+ if (!cancelled) {
+ setContextsError(e instanceof Error ? e.message : 'Failed to load contexts')
+ }
+ }
+ })()
+ return () => {
+ cancelled = true
+ }
+ }, [])
+
+ const serverNameError = serverName.length > 0 ? getRemoteServerNameError(serverName) : ''
+ const trimmedBaseUrl = baseUrl.trim()
+ const identifiersValid =
+ trimmedBaseUrl.length > 0 && getRemoteServerNameError(serverName) === '' && contextRef !== ''
+
+ const installMode = detected ? installModeForRegistration(detected.registrationMode) : null
+ const needsCredentials = installMode ? requiresPreRegisteredCredentials(installMode) : false
+ const noRefresh = detected ? shouldWarnNoRefresh(detected) : false
+
+ const credentialsComplete =
+ !needsCredentials || (clientId.trim().length > 0 && clientSecret.length > 0)
+ const step1Valid = Boolean(detected) && identifiersValid && credentialsComplete
+
+ function canSelectStep(target: number): boolean {
+ if (target === 0) return true
+ if (target === 1) return Boolean(detected) && identifiersValid
+ return step1Valid
+ }
+
+ const contextOptions = useMemo(
+ () =>
+ contexts
+ .map(context => contextResourceName(context))
+ .filter(name => name.length > 0)
+ .sort((left, right) => left.localeCompare(right)),
+ [contexts]
+ )
+
+ function resetDetection() {
+ setDetected(null)
+ setDiscoverError('')
+ }
+
+ async function runDetect() {
+ setDetecting(true)
+ setDiscoverError('')
+ try {
+ const result = await discoverRemoteServer(trimmedBaseUrl)
+ setDetected(result)
+ setStep(1)
+ } catch (e) {
+ if (isSilentApiError(e)) return
+ setDetected(null)
+ setDiscoverError(mapRemoteDiscoverError(e))
+ } finally {
+ setDetecting(false)
+ }
+ }
+
+ async function runInstall() {
+ if (!detected || !installMode) return
+ setInstalling(true)
+ setInstallError('')
+ try {
+ const body = buildRemoteInstallRequest({
+ serverName,
+ contextRef,
+ baseUrl: trimmedBaseUrl,
+ mode: installMode,
+ grantScope,
+ clientId: needsCredentials ? clientId : undefined,
+ clientSecret: needsCredentials ? clientSecret : undefined,
+ })
+ const res = await installRemoteServer(body)
+ showToast(`Remote server ${res.serverName} installed.`, { tone: 'success' })
+ onInstalled()
+ } catch (e) {
+ if (isSilentApiError(e)) return
+ setInstallError(mapRemoteInstallError(e))
+ } finally {
+ setInstalling(false)
+ }
+ }
+
+ const clientModeLabel = detected ? displayClientMode(detected) : null
+
+ return (
+ <CreateFlowPanel header={pageHeader}>
+ <form
+ onSubmit={event => {
+ event.preventDefault()
+ if (step === 2) void runInstall()
+ }}
+ >
+ <CreateStepFlow
+ ariaLabel="Add remote server steps"
+ className="cu-create-step-flow--3"
+ currentStep={step}
+ onStepChange={target => {
+ if (canSelectStep(target)) setStep(target)
+ }}
+ canSelectStep={canSelectStep}
+ steps={REMOTE_WIZARD_STEP_DETAILS}
+ stepLabels={REMOTE_WIZARD_STEPS}
+ titleId={STEP_TITLE_ID}
+ >
+ {step === 0 ? (
+ <div className="cu-form-stack cu-agent-form-stack">
+ <Field
+ description="The base URL of the remote MCP server (its OAuth metadata is discovered from here)."
+ label="Remote server URL"
+ htmlFor="remote-base-url"
+ required
+ >
+ <TextInput
+ id="remote-base-url"
+ monospace
+ onChange={event => {
+ setBaseUrl(event.target.value)
+ // Editing the URL invalidates a prior detection.
+ if (detected) resetDetection()
+ }}
+ placeholder="https://mcp.example.com/mcp"
+ disabled={detecting}
+ autoFocus
+ value={baseUrl}
+ />
+ </Field>
+
+ <Field
+ description="Kubernetes resource name: lowercase alphanumeric and hyphens, max 63 chars."
+ error={serverNameError || undefined}
+ label="Server name"
+ htmlFor="remote-server-name"
+ required
+ >
+ <TextInput
+ id="remote-server-name"
+ invalid={Boolean(serverNameError)}
+ monospace
+ onChange={event =>
+ setServerName(event.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))
+ }
+ placeholder="example-remote"
+ disabled={detecting}
+ value={serverName}
+ />
+ </Field>
+
+ <Field
+ description="The context this connector is attached to. Agents using this context can call it."
+ error={contextsError || undefined}
+ label="Context"
+ htmlFor="remote-context-ref"
+ required
+ >
+ <SelectInput
+ id="remote-context-ref"
+ onChange={event => setContextRef(event.target.value)}
+ disabled={detecting || contextOptions.length === 0}
+ value={contextRef}
+ >
+ <option value="">Select a context…</option>
+ {contextOptions.map(name => (
+ <option key={name} value={name}>
+ {name}
+ </option>
+ ))}
+ </SelectInput>
+ </Field>
+
+ {discoverError ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ {discoverError}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+
+ {step === 1 && detected ? (
+ <div className="cu-form-stack cu-agent-form-stack">
+ {noRefresh ? (
+ <div className="cu-banner cu-banner--warning" role="status">
+ This authorization server does not support token refresh, so users will have to
+ re-authorize periodically to keep this connector working.
+ </div>
+ ) : null}
+
+ <section className="cu-summary-list" aria-label="Detected OAuth configuration">
+ <div className="cu-summary-list__row">
+ <span>Registration mode</span>
+ <strong>{REGISTRATION_MODE_LABEL[detected.registrationMode]}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Client mode</span>
+ <strong>{clientModeLabel}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Issuer</span>
+ <strong>{detected.issuer}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Resource</span>
+ <strong>{detected.resource}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Authorization endpoint</span>
+ <strong>{detected.endpoints.authorization}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Token endpoint</span>
+ <strong>{detected.endpoints.token}</strong>
+ </div>
+ {detected.endpoints.registration ? (
+ <div className="cu-summary-list__row">
+ <span>Registration endpoint</span>
+ <strong>{detected.endpoints.registration}</strong>
+ </div>
+ ) : null}
+ <div className="cu-summary-list__row">
+ <span>Scopes</span>
+ <strong>{detected.scopes.join(' ') || '—'}</strong>
+ </div>
+ {detected.quirks.bearerInBody ? (
+ <div className="cu-summary-list__row">
+ <span>Token transport</span>
+ <strong>Sent in the request body</strong>
+ </div>
+ ) : null}
+ </section>
+
+ <p className="cu-field__hint">{REGISTRATION_MODE_HINT[detected.registrationMode]}</p>
+
+ {needsCredentials ? (
+ <div className="cu-form-grid">
+ <Field
+ description="The client_id of the pre-registered OAuth client for this server."
+ label="Client ID"
+ htmlFor="remote-client-id"
+ required
+ >
+ <TextInput
+ id="remote-client-id"
+ monospace
+ onChange={event => setClientId(event.target.value)}
+ placeholder="pre-registered client_id"
+ value={clientId}
+ />
+ </Field>
+ <Field
+ description="Stored as a Kubernetes Secret and only ever sent to the pinned token endpoint."
+ label="Client secret"
+ htmlFor="remote-client-secret"
+ required
+ >
+ <TextInput
+ id="remote-client-secret"
+ type="password"
+ autoComplete="off"
+ onChange={event => setClientSecret(event.target.value)}
+ placeholder="pre-registered client_secret"
+ value={clientSecret}
+ />
+ </Field>
+ </div>
+ ) : null}
+
+ <Field
+ description="Whether each user authorizes their own token or the context shares one."
+ label="Grant scope"
+ htmlFor="remote-grant-scope"
+ >
+ <SelectInput
+ id="remote-grant-scope"
+ onChange={event => setGrantScope(event.target.value as RemoteGrantScope)}
+ value={grantScope}
+ >
+ {GRANT_SCOPE_OPTIONS.map(option => (
+ <option key={option.value} value={option.value}>
+ {option.label} — {option.description}
+ </option>
+ ))}
+ </SelectInput>
+ </Field>
+ </div>
+ ) : null}
+
+ {step === 2 && detected && installMode ? (
+ <div className="cu-form-stack cu-agent-form-stack">
+ <section className="cu-summary-list" aria-label="Install summary">
+ <div className="cu-summary-list__row">
+ <span>Server name</span>
+ <strong>{serverName}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Context</span>
+ <strong>{contextRef}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Remote URL</span>
+ <strong>{trimmedBaseUrl}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Registration mode</span>
+ <strong>{REGISTRATION_MODE_LABEL[detected.registrationMode]}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Client mode</span>
+ <strong>{clientModeLabel}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Grant scope</span>
+ <strong>{grantScope === 'user' ? 'Per user' : 'Per context'}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Authorization endpoint</span>
+ <strong>{detected.endpoints.authorization}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Token endpoint</span>
+ <strong>{detected.endpoints.token}</strong>
+ </div>
+ </section>
+
+ {noRefresh ? (
+ <div className="cu-banner cu-banner--warning" role="status">
+ Reminder: this server does not support token refresh — users will re-authorize
+ periodically.
+ </div>
+ ) : null}
+
+ {installError ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ {installError}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+
+ <div className="cu-create-actions">
+ <Button
+ disabled={detecting || installing}
+ onClick={() => (step === 0 ? onCancel() : setStep(current => current - 1))}
+ size="sm"
+ variant="ghost"
+ >
+ {step === 0 ? 'Cancel' : 'Back'}
+ </Button>
+
+ {step === 0 ? (
+ detected ? (
+ <Button
+ disabled={!identifiersValid}
+ onClick={() => setStep(1)}
+ size="sm"
+ variant="primary"
+ >
+ Continue
+ </Button>
+ ) : (
+ <Button
+ disabled={!identifiersValid || detecting}
+ loading={detecting}
+ onClick={() => void runDetect()}
+ size="sm"
+ variant="primary"
+ >
+ {detecting ? 'Detecting…' : 'Detect'}
+ </Button>
+ )
+ ) : null}
+
+ {step === 1 ? (
+ <Button disabled={!step1Valid} onClick={() => setStep(2)} size="sm" variant="primary">
+ Continue
+ </Button>
+ ) : null}
+
+ {step === 2 ? (
+ <Button
+ disabled={!step1Valid || installing}
+ loading={installing}
+ size="sm"
+ type="submit"
+ variant="primary"
+ >
+ {installing ? 'Installing…' : 'Install remote server'}
+ </Button>
+ ) : null}
+ </div>
+ </CreateStepFlow>
+ </form>
+ </CreateFlowPanel>
+ )
+}
diff --git a/control-ui/components/AddRemoteServerWizard/types.ts b/control-ui/components/AddRemoteServerWizard/types.ts
new file mode 100644
index 000000000..9ec15e980
--- /dev/null
+++ b/control-ui/components/AddRemoteServerWizard/types.ts
@@ -0,0 +1,17 @@
+import type { ReactNode } from 'react'
+import type { RemoteGrantScope } from '../../lib/remoteMcp.types'
+
+export type AddRemoteServerWizardProps = {
+ /** Rendered create-page header (icon, title, back). */
+ pageHeader: ReactNode
+ /** Called after a successful install (201). Redirects to the connectors list. */
+ onInstalled: () => void
+ /** Called when the operator cancels from the first step. */
+ onCancel: () => void
+}
+
+export type GrantScopeOption = {
+ value: RemoteGrantScope
+ label: string
+ description: string
+}
diff --git a/control-ui/components/McpServerTable.tsx b/control-ui/components/McpServerTable.tsx
index 3166b136f..a1f9f11ce 100644
--- a/control-ui/components/McpServerTable.tsx
+++ b/control-ui/components/McpServerTable.tsx
@@ -99,6 +99,7 @@ export function McpServerTable({
deletingKey,
onRefresh,
onCreate,
+ onAddRemote,
onInstallFromRegistry,
detailContent,
refreshing,
@@ -272,17 +273,31 @@ export function McpServerTable({
</>
}
titleActions={
- onCreate ? (
+ onCreate || onAddRemote ? (
<RowActionsMenu
ariaLabel="Connector actions"
horizontalTrigger
actions={[
- {
- key: 'create',
- label: 'Create connector',
- onClick: onCreate,
- disabled: isInitialLoad,
- },
+ ...(onCreate
+ ? [
+ {
+ key: 'create',
+ label: 'Create connector',
+ onClick: onCreate,
+ disabled: isInitialLoad,
+ },
+ ]
+ : []),
+ ...(onAddRemote
+ ? [
+ {
+ key: 'add-remote',
+ label: 'Add remote server',
+ onClick: onAddRemote,
+ disabled: isInitialLoad,
+ },
+ ]
+ : []),
]}
/>
) : null
diff --git a/control-ui/components/McpServerTable.types.ts b/control-ui/components/McpServerTable.types.ts
index 2cfa81679..43f413cd9 100644
--- a/control-ui/components/McpServerTable.types.ts
+++ b/control-ui/components/McpServerTable.types.ts
@@ -83,6 +83,7 @@ export type McpServerTableProps = {
deletingKey?: string | null
onRefresh?: () => void
onCreate?: () => void
+ onAddRemote?: () => void
onInstallFromRegistry?: () => void
detailContent?: ReactNode
refreshing?: boolean
diff --git a/control-ui/components/__tests__/AddRemoteServerWizard.test.tsx b/control-ui/components/__tests__/AddRemoteServerWizard.test.tsx
new file mode 100644
index 000000000..394fc425f
--- /dev/null
+++ b/control-ui/components/__tests__/AddRemoteServerWizard.test.tsx
@@ -0,0 +1,211 @@
+import type { ReactNode } from 'react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'
+import * as api from '../../lib/api'
+import * as remoteMcp from '../../lib/remoteMcp'
+import type { RemoteDetected } from '../../lib/remoteMcp.types'
+import { buildContextResource } from '../../test/fixtures/contextResource'
+import { DCR_PUBLIC_DETECTED, NOTION_DETECTED } from '../../test/fixtures/remoteMcpDiscovery'
+import { AddRemoteServerWizard } from '../AddRemoteServerWizard'
+import { ToastProvider } from '../Toast'
+
+// Keep the real pure decision logic; only the two network calls are stubbed, so
+// the mocked responses must carry the real contract shapes (fixtures above).
+vi.mock('../../lib/remoteMcp', async importOriginal => ({
+ ...(await importOriginal<typeof import('../../lib/remoteMcp')>()),
+ discoverRemoteServer: vi.fn(),
+ installRemoteServer: vi.fn(),
+}))
+
+// Keep isSilentApiError etc.; only getContexts is stubbed. The fixture import is
+// done inside the factory because vi.mock is hoisted above top-level imports.
+vi.mock('../../lib/api', async importOriginal => {
+ const { buildContextResource } = await import('../../test/fixtures/contextResource')
+ return {
+ ...(await importOriginal<typeof import('../../lib/api')>()),
+ getContexts: vi.fn().mockResolvedValue({
+ items: [buildContextResource({ metadata: { name: 'research', resourceVersion: 'rv1' } })],
+ }),
+ }
+})
+
+const discoverMock = vi.mocked(remoteMcp.discoverRemoteServer)
+const installMock = vi.mocked(remoteMcp.installRemoteServer)
+const getContextsMock = vi.mocked(api.getContexts)
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+ // vi.clearAllMocks resets the default resolved value, so restore it.
+ getContextsMock.mockResolvedValue({
+ items: [buildContextResource({ metadata: { name: 'research', resourceVersion: 'rv1' } })],
+ })
+})
+
+function renderWizard(props?: Partial<Parameters<typeof AddRemoteServerWizard>[0]>) {
+ const onInstalled = props?.onInstalled ?? vi.fn()
+ const onCancel = props?.onCancel ?? vi.fn()
+ const utils = rtlRender(
+ <ToastProvider>
+ <AddRemoteServerWizard
+ pageHeader={<div>header</div>}
+ onInstalled={onInstalled}
+ onCancel={onCancel}
+ />
+ </ToastProvider>
+ )
+ return { ...utils, onInstalled, onCancel }
+}
+
+async function fillIdentity(baseUrl = 'https://mcp.notion.com/mcp', name = 'notion-remote') {
+ // Wait until the context select is populated from getContexts (option present).
+ await screen.findByRole('option', { name: 'research' })
+ fireEvent.change(screen.getByPlaceholderText('https://mcp.example.com/mcp'), {
+ target: { value: baseUrl },
+ })
+ fireEvent.change(screen.getByPlaceholderText('example-remote'), { target: { value: name } })
+ fireEvent.change(screen.getByRole('combobox', { name: /context/i }), {
+ target: { value: 'research' },
+ })
+}
+
+function clickDetect() {
+ fireEvent.click(screen.getByRole('button', { name: 'Detect' }))
+}
+
+describe('AddRemoteServerWizard', () => {
+ it('detects a server and advances to the configuration step showing the detected values', async () => {
+ discoverMock.mockResolvedValue(NOTION_DETECTED)
+ renderWizard()
+ await fillIdentity()
+ clickDetect()
+
+ await waitFor(() => expect(discoverMock).toHaveBeenCalledWith('https://mcp.notion.com/mcp'))
+ // Detected OAuth config is rendered on the configuration step.
+ expect(await screen.findByText('https://mcp.notion.com/authorize')).toBeInTheDocument()
+ expect(screen.getByText('https://mcp.notion.com/token')).toBeInTheDocument()
+ // Notion's issuer and resource share this value, so it appears more than once.
+ expect(screen.getAllByText('https://mcp.notion.com').length).toBeGreaterThanOrEqual(1)
+ expect(screen.getByText('default')).toBeInTheDocument()
+ })
+
+ it('D-4: editing the URL after a detect invalidates it and blocks proceeding until re-detect', async () => {
+ discoverMock.mockResolvedValue(NOTION_DETECTED)
+ renderWizard()
+ await fillIdentity()
+ clickDetect()
+ await screen.findByText('https://mcp.notion.com/authorize')
+
+ // Back to the identity step and change the URL.
+ fireEvent.click(screen.getByRole('button', { name: 'Back' }))
+ fireEvent.change(screen.getByPlaceholderText('https://mcp.example.com/mcp'), {
+ target: { value: 'https://mcp.linear.app/mcp' },
+ })
+
+ // The detection is cleared: the primary action is "Detect" again (not "Continue")…
+ expect(screen.getByRole('button', { name: 'Detect' })).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Continue' })).not.toBeInTheDocument()
+ // …and the Configure rail step can no longer be selected.
+ expect(screen.getByRole('button', { name: /Configure/ })).toBeDisabled()
+ })
+
+ it('shows client credential fields only for the manual (pre-registered) mode', async () => {
+ // manual has no real probed pilot; this is UI state, not a producer fixture.
+ const manualDetected: RemoteDetected = { ...NOTION_DETECTED, registrationMode: 'manual' }
+ discoverMock.mockResolvedValue(manualDetected)
+ renderWizard()
+ await fillIdentity()
+ clickDetect()
+
+ expect(await screen.findByLabelText(/Client ID/)).toBeInTheDocument()
+ expect(screen.getByLabelText(/Client secret/)).toBeInTheDocument()
+ // The secret field is a password input.
+ expect(screen.getByLabelText(/Client secret/)).toHaveAttribute('type', 'password')
+ })
+
+ it('does not show credential fields for cimd or dcr modes', async () => {
+ discoverMock.mockResolvedValue(NOTION_DETECTED) // cimd
+ renderWizard()
+ await fillIdentity()
+ clickDetect()
+ await screen.findByText('https://mcp.notion.com/authorize')
+ expect(screen.queryByLabelText(/Client ID/)).not.toBeInTheDocument()
+
+ cleanup()
+ discoverMock.mockResolvedValue(DCR_PUBLIC_DETECTED) // dcr
+ renderWizard()
+ await fillIdentity()
+ clickDetect()
+ await screen.findByText('https://mcp.notion.com/authorize')
+ expect(screen.queryByLabelText(/Client ID/)).not.toBeInTheDocument()
+ })
+
+ it('D-8: shows the no-refresh warning banner iff supportsRefresh is false', async () => {
+ const noRefresh: RemoteDetected = {
+ ...NOTION_DETECTED,
+ quirks: { bearerInBody: false, supportsRefresh: false },
+ }
+ discoverMock.mockResolvedValue(noRefresh)
+ renderWizard()
+ await fillIdentity()
+ clickDetect()
+ expect(await screen.findByText(/does not support token refresh/i)).toBeInTheDocument()
+
+ cleanup()
+ discoverMock.mockResolvedValue(NOTION_DETECTED) // supportsRefresh true
+ renderWizard()
+ await fillIdentity()
+ clickDetect()
+ await screen.findByText('https://mcp.notion.com/authorize')
+ expect(screen.queryByText(/does not support token refresh/i)).not.toBeInTheDocument()
+ })
+
+ it('installs successfully: sends the request, fires onInstalled, and toasts', async () => {
+ discoverMock.mockResolvedValue(NOTION_DETECTED)
+ installMock.mockResolvedValue({
+ serverName: 'notion-remote',
+ namespace: 'mcp-server',
+ contextRef: 'research',
+ contextUpdated: true,
+ clientMode: 'public',
+ registrationMode: 'cimd',
+ })
+ const { onInstalled } = renderWizard()
+ await fillIdentity()
+ clickDetect()
+ await screen.findByText('https://mcp.notion.com/authorize')
+
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' })) // → Confirm
+ fireEvent.click(await screen.findByRole('button', { name: 'Install remote server' }))
+
+ await waitFor(() => expect(installMock).toHaveBeenCalledTimes(1))
+ expect(installMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ serverName: 'notion-remote',
+ contextRef: 'research',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'cimd',
+ grantScope: 'user',
+ })
+ )
+ await waitFor(() => expect(onInstalled).toHaveBeenCalledTimes(1))
+ expect(await screen.findByText(/installed\./i)).toBeInTheDocument()
+ })
+
+ it('shows a mapped install error inline', async () => {
+ discoverMock.mockResolvedValue(NOTION_DETECTED)
+ installMock.mockRejectedValue(
+ Object.assign(new Error('503'), { code: 'callback_base_url_unconfigured', body: {} })
+ )
+ const { onInstalled } = renderWizard()
+ await fillIdentity()
+ clickDetect()
+ await screen.findByText('https://mcp.notion.com/authorize')
+
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+ fireEvent.click(await screen.findByRole('button', { name: 'Install remote server' }))
+
+ expect(await screen.findByText(/callback url is not configured/i)).toBeInTheDocument()
+ expect(onInstalled).not.toHaveBeenCalled()
+ })
+})
diff --git a/control-ui/lib/__tests__/remoteMcp.properties.test.ts b/control-ui/lib/__tests__/remoteMcp.properties.test.ts
new file mode 100644
index 000000000..fbc59fb74
--- /dev/null
+++ b/control-ui/lib/__tests__/remoteMcp.properties.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
+import {
+ installModeForRegistration,
+ requiresPreRegisteredCredentials,
+ shouldWarnNoRefresh,
+} from '../remoteMcp'
+import type { RemoteInstallMode, RemoteRegistrationMode } from '../remoteMcp.types'
+
+const REGISTRATION_MODES: RemoteRegistrationMode[] = ['cimd', 'dcr', 'manual', 'pre-registered']
+const INSTALL_MODES: RemoteInstallMode[] = ['cimd', 'pre-registered', 'dcr']
+
+describe('installModeForRegistration — property (D-3 precedence is stable and total)', () => {
+ it('returns a valid install mode for every registration mode', () => {
+ fc.assert(
+ fc.property(fc.constantFrom(...REGISTRATION_MODES), mode => {
+ expect(INSTALL_MODES).toContain(installModeForRegistration(mode))
+ })
+ )
+ })
+
+ it('is deterministic (same input → same output)', () => {
+ fc.assert(
+ fc.property(fc.constantFrom(...REGISTRATION_MODES), mode => {
+ expect(installModeForRegistration(mode)).toBe(installModeForRegistration(mode))
+ })
+ )
+ })
+
+ it('credentials are required exactly when the mode is manual or pre-registered', () => {
+ fc.assert(
+ fc.property(fc.constantFrom(...REGISTRATION_MODES), mode => {
+ const needsCreds = requiresPreRegisteredCredentials(installModeForRegistration(mode))
+ expect(needsCreds).toBe(mode === 'manual' || mode === 'pre-registered')
+ })
+ )
+ })
+
+ it('cimd/dcr never map to pre-registered; manual always does', () => {
+ fc.assert(
+ fc.property(fc.constantFrom<RemoteRegistrationMode>('cimd', 'dcr'), mode => {
+ expect(installModeForRegistration(mode)).not.toBe('pre-registered')
+ })
+ )
+ expect(installModeForRegistration('manual')).toBe('pre-registered')
+ })
+})
+
+describe('shouldWarnNoRefresh — property (D-8 warns iff no refresh)', () => {
+ it('the banner is the exact negation of supportsRefresh', () => {
+ fc.assert(
+ fc.property(fc.boolean(), fc.boolean(), (supportsRefresh, bearerInBody) => {
+ expect(shouldWarnNoRefresh({ quirks: { supportsRefresh, bearerInBody } })).toBe(
+ !supportsRefresh
+ )
+ })
+ )
+ })
+})
diff --git a/control-ui/lib/__tests__/remoteMcp.test.ts b/control-ui/lib/__tests__/remoteMcp.test.ts
new file mode 100644
index 000000000..97a624830
--- /dev/null
+++ b/control-ui/lib/__tests__/remoteMcp.test.ts
@@ -0,0 +1,224 @@
+import { describe, expect, it } from 'vitest'
+import {
+ DCR_CONFIDENTIAL_DETECTED,
+ DCR_PUBLIC_DETECTED,
+ NOTION_DETECTED,
+} from '../../test/fixtures/remoteMcpDiscovery'
+import {
+ buildRemoteInstallRequest,
+ describeDiscoveryError,
+ displayClientMode,
+ getRemoteServerNameError,
+ installModeForRegistration,
+ mapRemoteDiscoverError,
+ mapRemoteInstallError,
+ requiresPreRegisteredCredentials,
+ shouldWarnNoRefresh,
+} from '../remoteMcp'
+import type { RemoteDetected } from '../remoteMcp.types'
+
+describe('installModeForRegistration (D-3/D-7)', () => {
+ it('maps each registration mode to its install mode', () => {
+ expect(installModeForRegistration('cimd')).toBe('cimd')
+ expect(installModeForRegistration('dcr')).toBe('dcr')
+ // D-7: the only supported "manual" degradation is a pre-registered client.
+ expect(installModeForRegistration('manual')).toBe('pre-registered')
+ expect(installModeForRegistration('pre-registered')).toBe('pre-registered')
+ })
+})
+
+describe('requiresPreRegisteredCredentials (D-5)', () => {
+ it('asks for credentials only in the pre-registered mode', () => {
+ expect(requiresPreRegisteredCredentials('pre-registered')).toBe(true)
+ expect(requiresPreRegisteredCredentials('cimd')).toBe(false)
+ expect(requiresPreRegisteredCredentials('dcr')).toBe(false)
+ })
+
+ it('lines up with the mode mapping for every registration mode', () => {
+ // manual → pre-registered → needs credentials; cimd/dcr → no credentials.
+ expect(requiresPreRegisteredCredentials(installModeForRegistration('manual'))).toBe(true)
+ expect(requiresPreRegisteredCredentials(installModeForRegistration('cimd'))).toBe(false)
+ expect(requiresPreRegisteredCredentials(installModeForRegistration('dcr'))).toBe(false)
+ })
+})
+
+describe('shouldWarnNoRefresh (D-8)', () => {
+ it('warns iff supportsRefresh is false', () => {
+ expect(shouldWarnNoRefresh({ quirks: { bearerInBody: false, supportsRefresh: false } })).toBe(
+ true
+ )
+ expect(shouldWarnNoRefresh({ quirks: { bearerInBody: false, supportsRefresh: true } })).toBe(
+ false
+ )
+ })
+
+ it('does not warn for a refresh-capable real pilot', () => {
+ expect(shouldWarnNoRefresh(NOTION_DETECTED)).toBe(false)
+ })
+})
+
+describe('displayClientMode', () => {
+ it('derives the confirm-step client mode from the resolved install mode', () => {
+ expect(displayClientMode(NOTION_DETECTED)).toBe('public') // cimd
+ expect(displayClientMode(DCR_PUBLIC_DETECTED)).toBe('public')
+ expect(displayClientMode(DCR_CONFIDENTIAL_DETECTED)).toBe('confidential')
+ const manual: RemoteDetected = { ...NOTION_DETECTED, registrationMode: 'manual' }
+ expect(displayClientMode(manual)).toBe('confidential') // pre-registered
+ })
+})
+
+describe('getRemoteServerNameError', () => {
+ it('requires a name', () => {
+ expect(getRemoteServerNameError('')).toMatch(/required/i)
+ expect(getRemoteServerNameError(' ')).toMatch(/required/i)
+ })
+
+ it('accepts a valid RFC1123 label', () => {
+ expect(getRemoteServerNameError('notion-remote')).toBe('')
+ expect(getRemoteServerNameError('mcp0')).toBe('')
+ })
+
+ it('rejects invalid names', () => {
+ expect(getRemoteServerNameError('Notion_Remote')).not.toBe('')
+ expect(getRemoteServerNameError('-leading')).not.toBe('')
+ expect(getRemoteServerNameError('trailing-')).not.toBe('')
+ expect(getRemoteServerNameError('a'.repeat(64))).not.toBe('')
+ })
+})
+
+describe('buildRemoteInstallRequest', () => {
+ it('omits credentials for non-pre-registered modes and trims fields', () => {
+ const body = buildRemoteInstallRequest({
+ serverName: ' notion-remote ',
+ contextRef: 'research',
+ baseUrl: ' https://mcp.notion.com/mcp ',
+ mode: 'cimd',
+ grantScope: 'user',
+ clientId: 'should-not-be-sent',
+ clientSecret: 'should-not-be-sent',
+ })
+ expect(body).toEqual({
+ serverName: 'notion-remote',
+ contextRef: 'research',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'cimd',
+ grantScope: 'user',
+ })
+ expect(body.clientId).toBeUndefined()
+ expect(body.clientSecret).toBeUndefined()
+ })
+
+ it('includes credentials for the pre-registered mode', () => {
+ const body = buildRemoteInstallRequest({
+ serverName: 'atlassian',
+ contextRef: 'research',
+ baseUrl: 'https://mcp.atlassian.com/mcp',
+ mode: 'pre-registered',
+ grantScope: 'context',
+ clientId: ' client-abc ',
+ clientSecret: 'super-secret',
+ })
+ expect(body.mode).toBe('pre-registered')
+ expect(body.clientId).toBe('client-abc')
+ // The secret is passed through untrimmed (a secret may legitimately have edges).
+ expect(body.clientSecret).toBe('super-secret')
+ expect(body.grantScope).toBe('context')
+ })
+})
+
+describe('describeDiscoveryError', () => {
+ it('has distinct copy per kind and a fallback', () => {
+ const kinds = [
+ 'fetch_failed',
+ 'content_encoding_rejected',
+ 'kernel_rejected',
+ 'invalid_metadata',
+ 'no_s256',
+ 'no_authorization_server',
+ 'redirect_blocked',
+ 'prm_resource_mismatch',
+ 'issuer_mismatch',
+ ] as const
+ const texts = kinds.map(describeDiscoveryError)
+ expect(new Set(texts).size).toBe(kinds.length)
+ for (const t of texts) expect(t.length).toBeGreaterThan(0)
+ expect(describeDiscoveryError(undefined)).toMatch(/discovery failed/i)
+ expect(describeDiscoveryError('some-future-kind')).toMatch(/discovery failed/i)
+ })
+})
+
+describe('mapRemoteDiscoverError', () => {
+ it('maps a discovery_failed detail kind', () => {
+ const err = Object.assign(new Error('502 ...'), {
+ status: 502,
+ code: 'discovery_failed',
+ body: { error: 'discovery_failed', detail: { kind: 'fetch_failed' } },
+ })
+ expect(mapRemoteDiscoverError(err)).toBe(describeDiscoveryError('fetch_failed'))
+ })
+
+ it('surfaces the kernel §4 message verbatim', () => {
+ const err = Object.assign(
+ new Error('400 Bad Request - baseUrl resolves to a private address'),
+ {
+ status: 400,
+ code: 'baseUrl resolves to a private address',
+ message: '400 Bad Request - baseUrl resolves to a private address',
+ }
+ )
+ expect(mapRemoteDiscoverError(err)).toContain('private address')
+ })
+})
+
+describe('mapRemoteInstallError', () => {
+ it('uses the server message for mode_unsupported', () => {
+ const err = Object.assign(new Error('400'), {
+ status: 400,
+ code: 'mode_unsupported',
+ body: {
+ error: 'mode_unsupported',
+ message:
+ 'this authorization server requires dynamic client registration; install with mode "dcr"',
+ },
+ })
+ expect(mapRemoteInstallError(err)).toContain('dynamic client registration')
+ })
+
+ it('maps auth_method_unsupported', () => {
+ const err = Object.assign(new Error('400'), { code: 'auth_method_unsupported', body: {} })
+ expect(mapRemoteInstallError(err)).toMatch(/authentication method/i)
+ })
+
+ it('maps dcr_registration_failed with its detail kind', () => {
+ const err = Object.assign(new Error('400'), {
+ code: 'dcr_registration_failed',
+ body: { error: 'dcr_registration_failed', detail: { kind: 'invalid_response' } },
+ })
+ expect(mapRemoteInstallError(err)).toContain('invalid_response')
+ })
+
+ it('maps callback_base_url_unconfigured to plain copy', () => {
+ const err = Object.assign(new Error('503'), {
+ code: 'callback_base_url_unconfigured',
+ body: {},
+ })
+ expect(mapRemoteInstallError(err)).toMatch(/callback url is not configured/i)
+ })
+
+ it('maps a re-run discovery_failed at install', () => {
+ const err = Object.assign(new Error('400'), {
+ code: 'discovery_failed',
+ body: { error: 'discovery_failed', detail: { kind: 'no_s256' } },
+ })
+ expect(mapRemoteInstallError(err)).toBe(describeDiscoveryError('no_s256'))
+ })
+
+ it('passes through a context-not-found / allowlist error message', () => {
+ const err = Object.assign(new Error('404 Not Found - context "research" not found'), {
+ status: 404,
+ code: 'context "research" not found',
+ message: '404 Not Found - context "research" not found',
+ })
+ expect(mapRemoteInstallError(err)).toContain('context "research" not found')
+ })
+})
diff --git a/control-ui/lib/remoteMcp.ts b/control-ui/lib/remoteMcp.ts
new file mode 100644
index 000000000..b5e4e0924
--- /dev/null
+++ b/control-ui/lib/remoteMcp.ts
@@ -0,0 +1,240 @@
+'use client'
+
+import { apiSend } from './api'
+import { isValidK8sName } from './k8sValidation'
+import type {
+ DiscoverRemoteResponse,
+ InstallRemoteRequest,
+ InstallRemoteResponse,
+ RemoteClientMode,
+ RemoteDetected,
+ RemoteDiscoveryErrorKind,
+ RemoteInstallMode,
+ RemoteRegistrationMode,
+} from './remoteMcp.types'
+
+/** Real admin prefix for the remote MCP-OAuth routes (control-api). */
+export const REMOTE_MCP_BASE = '/api/v1/admin/mcp-servers/remote'
+
+// ── API client (matches lib/api.ts; apiSend attaches the admin bearer) ───────
+
+/**
+ * Dry-run discovery for `baseUrl`. Resolves to the `detected` prefill or throws
+ * the `apiSend` error (whose `.code`/`.body` carry the discovery-error detail).
+ */
+export async function discoverRemoteServer(baseUrl: string): Promise<RemoteDetected> {
+ const res = (await apiSend('POST', `${REMOTE_MCP_BASE}/discover`, {
+ baseUrl,
+ })) as DiscoverRemoteResponse
+ return res.detected
+}
+
+/** Transactional install saga. Resolves to the names-only summary (201). */
+export async function installRemoteServer(
+ body: InstallRemoteRequest
+): Promise<InstallRemoteResponse> {
+ return (await apiSend('POST', REMOTE_MCP_BASE, body)) as InstallRemoteResponse
+}
+
+// ── Pure decision logic (D-3/D-5/D-7/D-8), tested independently ───────────────
+
+/**
+ * D-3 / D-7: map the AS-resolved registration mode to the install mode.
+ * Authority is the backend `registrationMode`; the UI never re-orders it.
+ * cimd → cimd (public client, no credentials)
+ * dcr → dcr (backend registers + manages the client, incl. its secret)
+ * manual → pre-registered (D-7: the only supported degradation is an
+ * operator-supplied pre-registered confidential client)
+ * pre-registered → pre-registered (install-only echo; kept total)
+ */
+export function installModeForRegistration(mode: RemoteRegistrationMode): RemoteInstallMode {
+ switch (mode) {
+ case 'cimd':
+ return 'cimd'
+ case 'dcr':
+ return 'dcr'
+ case 'manual':
+ case 'pre-registered':
+ return 'pre-registered'
+ }
+}
+
+/**
+ * D-5: only the pre-registered (manual-degraded) mode asks the operator for a
+ * client_id/client_secret. CIMD is public; DCR credentials are backend-managed.
+ */
+export function requiresPreRegisteredCredentials(mode: RemoteInstallMode): boolean {
+ return mode === 'pre-registered'
+}
+
+/**
+ * D-8: show the persistent re-consent warning iff the AS does not support token
+ * refresh. Fail-closed — an absent/false `supportsRefresh` warns.
+ */
+export function shouldWarnNoRefresh(detected: Pick<RemoteDetected, 'quirks'>): boolean {
+ return detected.quirks.supportsRefresh === false
+}
+
+/**
+ * The client mode to display on the confirm step. Pre-registered is always
+ * confidential; CIMD is always public; DCR carries the AS-derived mode in its
+ * `dcr` block (default to confidential when the block is somehow absent).
+ */
+export function displayClientMode(detected: RemoteDetected): RemoteClientMode {
+ const installMode = installModeForRegistration(detected.registrationMode)
+ if (installMode === 'pre-registered') return 'confidential'
+ if (installMode === 'cimd') return 'public'
+ return detected.dcr?.clientMode ?? 'confidential'
+}
+
+/**
+ * Validate the operator-typed server name as a Kubernetes resource name, mirror
+ * of the connector-create form. Returns '' when acceptable, else a message.
+ * The client uses the stricter RFC1123 DNS label (≤63) — always a subset of the
+ * server's acceptance, so a name that passes here never 400s on the name check.
+ */
+export function getRemoteServerNameError(name: string): string {
+ if (!name.trim()) return 'Server name is required.'
+ if (!isValidK8sName(name)) {
+ return 'Server name must be a valid Kubernetes name: lowercase letters, numbers, and hyphens, starting and ending alphanumeric, max 63 characters.'
+ }
+ return ''
+}
+
+// ── Error mapping to human-readable UI text ──────────────────────────────────
+
+type CodedError = {
+ status?: number
+ code?: string
+ message?: string
+ body?: Record<string, unknown>
+}
+
+function asCodedError(error: unknown): CodedError {
+ if (error && typeof error === 'object') {
+ const e = error as CodedError
+ return { status: e.status, code: e.code, message: e.message, body: e.body }
+ }
+ return { message: String(error) }
+}
+
+/** Human copy for a `discovery_failed` detail kind (used by discover + install). */
+export function describeDiscoveryError(
+ kind: RemoteDiscoveryErrorKind | string | undefined
+): string {
+ switch (kind) {
+ case 'fetch_failed':
+ return "Couldn't reach the server to read its OAuth metadata. Check the URL and that the host is publicly reachable."
+ case 'content_encoding_rejected':
+ return 'The server responded with an unsupported content encoding, so its OAuth metadata could not be read safely.'
+ case 'kernel_rejected':
+ return 'The server URL was rejected by the security policy (it resolves to a private, blocked, or non-HTTPS address).'
+ case 'invalid_metadata':
+ return "The server's OAuth metadata is missing or malformed."
+ case 'no_s256':
+ return "The authorization server does not advertise PKCE S256, which is required. This server can't be installed."
+ case 'no_authorization_server':
+ return 'The server does not point to an OAuth authorization server, so it cannot be installed as a remote OAuth connector.'
+ case 'redirect_blocked':
+ return 'A redirect while reading the OAuth metadata was blocked by the security policy.'
+ case 'prm_resource_mismatch':
+ return "The server's protected-resource metadata is inconsistent with its own URL."
+ case 'issuer_mismatch':
+ return "The authorization server's issuer does not match the address it was fetched from."
+ default:
+ return 'OAuth discovery failed for this server.'
+ }
+}
+
+function discoveryDetailKind(body: Record<string, unknown> | undefined): string | undefined {
+ const detail = body?.detail
+ if (detail && typeof detail === 'object') {
+ const kind = (detail as { kind?: unknown }).kind
+ if (typeof kind === 'string') return kind
+ }
+ return undefined
+}
+
+/**
+ * Map a discover-step failure (from `discoverRemoteServer`) to UI copy. Covers
+ * the typed `discovery_failed` union and the kernel §4 pre-check 400 (whose
+ * `error` is a plain message, surfaced verbatim).
+ */
+export function mapRemoteDiscoverError(error: unknown): string {
+ const e = asCodedError(error)
+ if (e.code === 'discovery_failed') {
+ return describeDiscoveryError(discoveryDetailKind(e.body))
+ }
+ // Kernel §4 400: `{ error: '<message>', errors }`. formatApiError surfaces the
+ // message in `.message`; fall back to it (or a generic line).
+ return e.message?.trim() || 'Could not detect the remote server. Check the URL and try again.'
+}
+
+/** Map an install-step failure to UI copy across the documented error codes. */
+export function mapRemoteInstallError(error: unknown): string {
+ const e = asCodedError(error)
+ const code = e.code
+ const body = e.body
+ const serverMessage =
+ body && typeof body.message === 'string' && body.message.trim() ? body.message.trim() : ''
+
+ switch (code) {
+ case 'mode_unsupported':
+ // The backend explains exactly which mode the AS actually resolved to.
+ return serverMessage || 'The requested registration mode is not supported by this server.'
+ case 'auth_method_unsupported':
+ return "The authorization server assigned a client authentication method this platform cannot present, so this server can't be installed automatically."
+ case 'dcr_registration_failed':
+ return `Dynamic client registration failed at the authorization server${
+ discoveryDetailKind(body) ? ` (${discoveryDetailKind(body)})` : ''
+ }.`
+ case 'dcr_persist_failed':
+ return 'The client was registered but its credentials could not be stored. Nothing was installed — please try again.'
+ case 'callback_base_url_unconfigured':
+ return 'The public OAuth callback URL is not configured on this deployment. Set it before installing a remote OAuth server.'
+ case 'discovery_failed':
+ // D-7: install re-runs discovery server-side, so a discover-time failure
+ // reappears here with the same detail kind.
+ return describeDiscoveryError(discoveryDetailKind(body))
+ case 'invalid_request':
+ return 'The install request was rejected as invalid. Reload the page and try again.'
+ default:
+ break
+ }
+
+ // Context-not-found and Secret/Context allowlist failures arrive as a plain
+ // `{ error: '<string>' }`; formatApiError surfaces that string in `.message`.
+ return e.message?.trim() || 'Failed to install the remote server.'
+}
+
+// ── Request assembly ─────────────────────────────────────────────────────────
+
+/**
+ * Assemble the install request body from wizard state. Credentials are attached
+ * only for the pre-registered mode (D-5); grantScope is always sent (default
+ * `user`) so the choice is explicit.
+ */
+export function buildRemoteInstallRequest(input: {
+ serverName: string
+ contextRef: string
+ baseUrl: string
+ mode: RemoteInstallMode
+ grantScope: RemoteGrantScopeInput
+ clientId?: string
+ clientSecret?: string
+}): InstallRemoteRequest {
+ const body: InstallRemoteRequest = {
+ serverName: input.serverName.trim(),
+ contextRef: input.contextRef,
+ baseUrl: input.baseUrl.trim(),
+ mode: input.mode,
+ grantScope: input.grantScope,
+ }
+ if (input.mode === 'pre-registered') {
+ body.clientId = input.clientId?.trim()
+ body.clientSecret = input.clientSecret
+ }
+ return body
+}
+
+type RemoteGrantScopeInput = InstallRemoteRequest['grantScope']
diff --git a/control-ui/lib/remoteMcp.types.ts b/control-ui/lib/remoteMcp.types.ts
new file mode 100644
index 000000000..9fac1d02b
--- /dev/null
+++ b/control-ui/lib/remoteMcp.types.ts
@@ -0,0 +1,102 @@
+/**
+ * Wire types for the remote MCP-OAuth admin endpoints consumed by the
+ * "Add remote server" wizard (spec 19 §C5). These mirror EXACTLY the request
+ * and response shapes control-api's `/admin/mcp-servers/remote` routes emit
+ * (control-api/src/routes/admin/remoteMcp.ts). They are the contract boundary,
+ * so they live here rather than inline in the wizard component.
+ */
+
+/**
+ * Client-registration mode the AS resolves to. The dry-run `/discover` never
+ * returns `pre-registered` (that only appears when the install runs with an
+ * operator-supplied client), so the discover response is narrowed to the three
+ * dry-run values; the install response echoes the full union.
+ */
+export type RemoteDiscoverRegistrationMode = 'cimd' | 'dcr' | 'manual'
+export type RemoteRegistrationMode = RemoteDiscoverRegistrationMode | 'pre-registered'
+
+/** Install mode sent to the install saga. */
+export type RemoteInstallMode = 'cimd' | 'pre-registered' | 'dcr'
+
+/** RFC 8707 grant partitioning: a per-user token or a shared per-context one. */
+export type RemoteGrantScope = 'user' | 'context'
+
+export type RemoteClientMode = 'public' | 'confidential'
+
+/** DCR sub-block, present in the discover response only when mode is `dcr`. */
+export interface RemoteDetectedDcr {
+ available: true
+ clientMode: RemoteClientMode
+ supportsRefresh: boolean
+}
+
+export interface RemoteDetectedEndpoints {
+ authorization: string
+ token: string
+ registration?: string
+}
+
+export interface RemoteDetectedQuirks {
+ /** D-8: token goes in the request body, not the Authorization header. */
+ bearerInBody: boolean
+ /** D-8: AS advertises refresh; fail-closed false means periodic re-consent. */
+ supportsRefresh: boolean
+}
+
+/** The `detected` prefill returned by POST /discover (200). */
+export interface RemoteDetected {
+ registrationMode: RemoteDiscoverRegistrationMode
+ dcr?: RemoteDetectedDcr
+ endpoints: RemoteDetectedEndpoints
+ resource: string
+ issuer: string
+ issForCallback?: string
+ scopes: string[]
+ quirks: RemoteDetectedQuirks
+}
+
+export interface DiscoverRemoteRequest {
+ baseUrl: string
+}
+
+export interface DiscoverRemoteResponse {
+ detected: RemoteDetected
+}
+
+export interface InstallRemoteRequest {
+ serverName: string
+ contextRef: string
+ baseUrl: string
+ mode: RemoteInstallMode
+ /** Pre-registered confidential only. */
+ clientId?: string
+ /** Pre-registered confidential only (sensitive). */
+ clientSecret?: string
+ grantScope?: RemoteGrantScope
+}
+
+export interface InstallRemoteResponse {
+ serverName: string
+ namespace: string
+ contextRef: string
+ contextUpdated: true
+ clientMode: RemoteClientMode
+ registrationMode: RemoteRegistrationMode
+ clientSecretName?: string
+}
+
+/**
+ * The typed error union returned by `/discover` (and re-run at install) under
+ * `{ error: 'discovery_failed', detail }`. Mirrors control-api's `DiscoveryError`
+ * `kind` values so the wizard can map each to actionable copy.
+ */
+export type RemoteDiscoveryErrorKind =
+ | 'fetch_failed'
+ | 'content_encoding_rejected'
+ | 'kernel_rejected'
+ | 'invalid_metadata'
+ | 'no_s256'
+ | 'no_authorization_server'
+ | 'redirect_blocked'
+ | 'prm_resource_mismatch'
+ | 'issuer_mismatch'
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 55057f0bb..5238431b6 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.604",
+ "version": "0.1.605",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.604",
+ "version": "0.1.605",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --git a/control-ui/package.json b/control-ui/package.json
index e5c50bedf..e49332bf3 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.604",
+ "version": "0.1.605",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/control-ui/test/fixtures/__tests__/remoteMcpDiscovery.contract.test.ts b/control-ui/test/fixtures/__tests__/remoteMcpDiscovery.contract.test.ts
new file mode 100644
index 000000000..fa8115d25
--- /dev/null
+++ b/control-ui/test/fixtures/__tests__/remoteMcpDiscovery.contract.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from 'vitest'
+import type { RemoteDetected } from '../../../lib/remoteMcp.types'
+import {
+ CANVA_AS_JSON,
+ CANVA_DETECTED,
+ CANVA_PRM_JSON,
+ DCR_CONFIDENTIAL_AS_JSON,
+ DCR_CONFIDENTIAL_DETECTED,
+ DCR_PUBLIC_AS_JSON,
+ DCR_PUBLIC_DETECTED,
+ LINEAR_AS_JSON,
+ LINEAR_DETECTED,
+ LINEAR_PRM_JSON,
+ NOTION_AS_JSON,
+ NOTION_DETECTED,
+ NOTION_PRM_JSON,
+ SENTRY_AS_JSON,
+ SENTRY_DETECTED,
+ SENTRY_PRM_JSON,
+} from '../remoteMcpDiscovery'
+
+/**
+ * Reproduces the producer's projection (control-api discovery.ts + remoteMcp.ts
+ * route) from the verbatim raw probe bytes and asserts each hand-derived
+ * `detected` fixture equals it. A fixture value that drifts from the real server
+ * bytes fails here, so the fixtures cannot silently encode an invented shape.
+ */
+function projectDetected(prmJson: string, asJson: string): RemoteDetected {
+ const prm = JSON.parse(prmJson) as Record<string, unknown>
+ const as = JSON.parse(asJson) as Record<string, unknown>
+
+ const authMethods = (as.token_endpoint_auth_methods_supported as string[] | undefined) ?? []
+ const hasRegistration = typeof as.registration_endpoint === 'string'
+ // D-3, dry-run (no pre-registered client): cimd > dcr > manual.
+ const registrationMode =
+ as.client_id_metadata_document_supported === true && authMethods.includes('none')
+ ? 'cimd'
+ : hasRegistration
+ ? 'dcr'
+ : 'manual'
+
+ const prmScopes = prm.scopes_supported as string[] | undefined
+ const asScopes = as.scopes_supported as string[] | undefined
+ const scopes = prmScopes ?? asScopes ?? []
+
+ const bearerMethods = prm.bearer_methods_supported as string[] | undefined
+ const bearerInBody = Array.isArray(bearerMethods)
+ ? bearerMethods.includes('body') && !bearerMethods.includes('header')
+ : false
+ const grantTypes = as.grant_types_supported as string[] | undefined
+ const supportsRefresh = grantTypes?.includes('refresh_token') ?? false
+
+ const detected: RemoteDetected = {
+ registrationMode: registrationMode as RemoteDetected['registrationMode'],
+ endpoints: {
+ authorization: as.authorization_endpoint as string,
+ token: as.token_endpoint as string,
+ ...(hasRegistration ? { registration: as.registration_endpoint as string } : {}),
+ },
+ resource: prm.resource as string,
+ issuer: as.issuer as string,
+ ...(as.authorization_response_iss_parameter_supported === true
+ ? { issForCallback: as.issuer as string }
+ : {}),
+ scopes,
+ quirks: { bearerInBody, supportsRefresh },
+ }
+ if (registrationMode === 'dcr') {
+ detected.dcr = {
+ available: true,
+ clientMode: authMethods.includes('none') ? 'public' : 'confidential',
+ supportsRefresh,
+ }
+ }
+ return detected
+}
+
+describe('remote MCP `detected` fixtures match the real probe bytes', () => {
+ const cases: Array<{ name: string; prm: string; as: string; fixture: RemoteDetected }> = [
+ { name: 'notion', prm: NOTION_PRM_JSON, as: NOTION_AS_JSON, fixture: NOTION_DETECTED },
+ { name: 'linear', prm: LINEAR_PRM_JSON, as: LINEAR_AS_JSON, fixture: LINEAR_DETECTED },
+ { name: 'sentry', prm: SENTRY_PRM_JSON, as: SENTRY_AS_JSON, fixture: SENTRY_DETECTED },
+ { name: 'canva', prm: CANVA_PRM_JSON, as: CANVA_AS_JSON, fixture: CANVA_DETECTED },
+ {
+ name: 'dcr-public',
+ prm: NOTION_PRM_JSON,
+ as: DCR_PUBLIC_AS_JSON,
+ fixture: DCR_PUBLIC_DETECTED,
+ },
+ {
+ name: 'dcr-confidential',
+ prm: NOTION_PRM_JSON,
+ as: DCR_CONFIDENTIAL_AS_JSON,
+ fixture: DCR_CONFIDENTIAL_DETECTED,
+ },
+ ]
+
+ for (const { name, prm, as, fixture } of cases) {
+ it(`${name}: fixture equals the producer projection of the raw bytes`, () => {
+ expect(fixture).toEqual(projectDetected(prm, as))
+ })
+ }
+
+ it('the four CIMD pilots resolve to cimd and carry a registration endpoint', () => {
+ for (const fixture of [NOTION_DETECTED, LINEAR_DETECTED, SENTRY_DETECTED, CANVA_DETECTED]) {
+ expect(fixture.registrationMode).toBe('cimd')
+ expect(fixture.endpoints.registration).toBeTruthy()
+ expect(fixture.dcr).toBeUndefined()
+ }
+ })
+
+ it('only sentry advertises issForCallback (RFC 9207)', () => {
+ expect(SENTRY_DETECTED.issForCallback).toBe('https://mcp.sentry.dev')
+ expect(NOTION_DETECTED.issForCallback).toBeUndefined()
+ expect(LINEAR_DETECTED.issForCallback).toBeUndefined()
+ expect(CANVA_DETECTED.issForCallback).toBeUndefined()
+ })
+})
diff --git a/control-ui/test/fixtures/remoteMcpDiscovery.ts b/control-ui/test/fixtures/remoteMcpDiscovery.ts
new file mode 100644
index 000000000..a458bd318
--- /dev/null
+++ b/control-ui/test/fixtures/remoteMcpDiscovery.ts
@@ -0,0 +1,165 @@
+/**
+ * Producer fixtures — the `detected` prefill POST /admin/mcp-servers/remote/discover
+ * returns (spec 19 §C5). control-ui cannot run control-api's discovery in this
+ * package (its deps — pino, @clerum/image-policy — are not installed here), so the
+ * `detected` objects below are DERIVED FROM THE REAL SERVER PROBE BYTES: the raw
+ * PRM/AS JSON strings are copied verbatim from control-api's own T1 fixtures
+ * (control-api/test/fixtures/remoteOAuthDiscovery.ts — live probes 2026-09-20) and
+ * the projection that turns those bytes into `detected` is the one the producer
+ * applies (control-api/src/oauth/discovery.ts + src/routes/admin/remoteMcp.ts).
+ *
+ * The colocated contract test re-parses the verbatim raw bytes and asserts that
+ * every `detected` field equals the real server field under the producer's
+ * documented rule, so a hand-typed value that drifts from the real bytes fails.
+ * This mirrors the repo's existing producer-fixture pattern (test/fixtures/
+ * contextResource.ts + its *.contract.test.ts).
+ */
+import type { RemoteDetected } from '../../lib/remoteMcp.types'
+
+// ─── Verbatim real probe bytes (control-api T1 fixtures, 2026-09-20) ──────────
+
+export const NOTION_PRM_JSON =
+ '{"resource":"https://mcp.notion.com","authorization_servers":["https://mcp.notion.com"],"scopes_supported":["default"],"bearer_methods_supported":["header"],"resource_name":"Notion MCP (Beta)"}'
+export const NOTION_AS_JSON =
+ '{"issuer":"https://mcp.notion.com","authorization_endpoint":"https://mcp.notion.com/authorize","token_endpoint":"https://mcp.notion.com/token","registration_endpoint":"https://mcp.notion.com/register","scopes_supported":["default"],"response_types_supported":["code"],"response_modes_supported":["query"],"grant_types_supported":["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:jwt-bearer"],"authorization_grant_profiles_supported":["urn:ietf:params:oauth:grant-profile:id-jag"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"revocation_endpoint":"https://mcp.notion.com/token","code_challenge_methods_supported":["plain","S256"],"client_id_metadata_document_supported":true,"introspection_endpoint":"https://mcp.notion.com/introspect","introspection_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"]}'
+
+export const LINEAR_PRM_JSON =
+ '{"resource":"https://mcp.linear.app/mcp","authorization_servers":["https://mcp.linear.app"],"scopes_supported":["read","write"],"bearer_methods_supported":["header"]}'
+export const LINEAR_AS_JSON =
+ '{"issuer":"https://mcp.linear.app","authorization_endpoint":"https://mcp.linear.app/authorize","token_endpoint":"https://mcp.linear.app/token","registration_endpoint":"https://mcp.linear.app/register","scopes_supported":["read","write","openid","email"],"response_types_supported":["code"],"response_modes_supported":["query"],"grant_types_supported":["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:jwt-bearer"],"authorization_grant_profiles_supported":["urn:ietf:params:oauth:grant-profile:id-jag"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"revocation_endpoint":"https://mcp.linear.app/token","code_challenge_methods_supported":["S256"],"client_id_metadata_document_supported":true,"resource":"https://mcp.linear.app/mcp","resource_metadata":"https://mcp.linear.app/.well-known/oauth-protected-resource/mcp"}'
+
+export const SENTRY_PRM_JSON =
+ '{"resource":"https://mcp.sentry.dev/mcp","authorization_servers":["https://mcp.sentry.dev"],"scopes_supported":["org:read","project:write","team:write","event:write"],"bearer_methods_supported":["header"]}'
+export const SENTRY_AS_JSON =
+ '{"issuer":"https://mcp.sentry.dev","authorization_endpoint":"https://mcp.sentry.dev/oauth/authorize","token_endpoint":"https://mcp.sentry.dev/oauth/token","registration_endpoint":"https://mcp.sentry.dev/oauth/register","scopes_supported":["org:read","project:write","team:write","event:write"],"response_types_supported":["code"],"response_modes_supported":["query"],"grant_types_supported":["authorization_code","refresh_token"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"revocation_endpoint":"https://mcp.sentry.dev/oauth/token","code_challenge_methods_supported":["S256"],"authorization_response_iss_parameter_supported":true,"client_id_metadata_document_supported":true}'
+
+export const CANVA_PRM_JSON =
+ '{"resource":"https://mcp.canva.com","authorization_servers":["https://mcp.canva.com"],"scopes_supported":["profile:read","design:meta:read","design:content:write","design:content:read","folder:read","folder:write","brandtemplate:content:read","brandtemplate:meta:read","brandtemplate:content:write","comment:write","comment:read","asset:read","asset:write","brandkit:read","help:answers:read","help:answers:write"],"bearer_methods_supported":["header"]}'
+export const CANVA_AS_JSON =
+ '{"issuer":"https://mcp.canva.com","authorization_endpoint":"https://mcp.canva.com/authorize","token_endpoint":"https://mcp.canva.com/token","registration_endpoint":"https://mcp.canva.com/register","response_types_supported":["code"],"response_modes_supported":["query"],"grant_types_supported":["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:jwt-bearer"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"revocation_endpoint":"https://mcp.canva.com/token","code_challenge_methods_supported":["plain","S256"],"client_id_metadata_document_supported":true,"authorization_grant_profiles_supported":["urn:ietf:params:oauth:grant-profile:id-jag"]}'
+
+/**
+ * DCR-forced AS bytes — same documented subtraction control-api uses (DEC-19):
+ * removing `client_id_metadata_document_supported` from the real Notion AS pushes
+ * the mode selector off CIMD onto DCR (Notion advertises a `/register` endpoint);
+ * additionally dropping `none` from the auth methods forces DCR-confidential.
+ * Nothing is invented — the removed fields are exactly the ones Notion emits.
+ */
+function subtractedNotionAs(mutate: (as: Record<string, unknown>) => void): string {
+ const as = JSON.parse(NOTION_AS_JSON) as Record<string, unknown>
+ mutate(as)
+ return JSON.stringify(as)
+}
+export const DCR_PUBLIC_AS_JSON = subtractedNotionAs(as => {
+ delete as.client_id_metadata_document_supported
+})
+export const DCR_CONFIDENTIAL_AS_JSON = subtractedNotionAs(as => {
+ delete as.client_id_metadata_document_supported
+ as.token_endpoint_auth_methods_supported = ['client_secret_basic', 'client_secret_post']
+})
+
+// ─── `detected` fixtures (hand-derived; locked to the bytes by the contract test) ─
+
+/** Notion — CIMD (public), refresh supported, no `iss`. */
+export const NOTION_DETECTED: RemoteDetected = {
+ registrationMode: 'cimd',
+ endpoints: {
+ authorization: 'https://mcp.notion.com/authorize',
+ token: 'https://mcp.notion.com/token',
+ registration: 'https://mcp.notion.com/register',
+ },
+ resource: 'https://mcp.notion.com',
+ issuer: 'https://mcp.notion.com',
+ scopes: ['default'],
+ quirks: { bearerInBody: false, supportsRefresh: true },
+}
+
+/** Linear — CIMD, resource carries a `/mcp` path. */
+export const LINEAR_DETECTED: RemoteDetected = {
+ registrationMode: 'cimd',
+ endpoints: {
+ authorization: 'https://mcp.linear.app/authorize',
+ token: 'https://mcp.linear.app/token',
+ registration: 'https://mcp.linear.app/register',
+ },
+ resource: 'https://mcp.linear.app/mcp',
+ issuer: 'https://mcp.linear.app',
+ scopes: ['read', 'write'],
+ quirks: { bearerInBody: false, supportsRefresh: true },
+}
+
+/** Sentry — CIMD, advertises RFC 9207 `iss` (issForCallback present). */
+export const SENTRY_DETECTED: RemoteDetected = {
+ registrationMode: 'cimd',
+ endpoints: {
+ authorization: 'https://mcp.sentry.dev/oauth/authorize',
+ token: 'https://mcp.sentry.dev/oauth/token',
+ registration: 'https://mcp.sentry.dev/oauth/register',
+ },
+ resource: 'https://mcp.sentry.dev/mcp',
+ issuer: 'https://mcp.sentry.dev',
+ issForCallback: 'https://mcp.sentry.dev',
+ scopes: ['org:read', 'project:write', 'team:write', 'event:write'],
+ quirks: { bearerInBody: false, supportsRefresh: true },
+}
+
+/** Canva — CIMD; AS has no scopes_supported, so scopes come from the PRM. */
+export const CANVA_DETECTED: RemoteDetected = {
+ registrationMode: 'cimd',
+ endpoints: {
+ authorization: 'https://mcp.canva.com/authorize',
+ token: 'https://mcp.canva.com/token',
+ registration: 'https://mcp.canva.com/register',
+ },
+ resource: 'https://mcp.canva.com',
+ issuer: 'https://mcp.canva.com',
+ scopes: [
+ 'profile:read',
+ 'design:meta:read',
+ 'design:content:write',
+ 'design:content:read',
+ 'folder:read',
+ 'folder:write',
+ 'brandtemplate:content:read',
+ 'brandtemplate:meta:read',
+ 'brandtemplate:content:write',
+ 'comment:write',
+ 'comment:read',
+ 'asset:read',
+ 'asset:write',
+ 'brandkit:read',
+ 'help:answers:read',
+ 'help:answers:write',
+ ],
+ quirks: { bearerInBody: false, supportsRefresh: true },
+}
+
+/** DCR-public (Notion minus CIMD support). */
+export const DCR_PUBLIC_DETECTED: RemoteDetected = {
+ registrationMode: 'dcr',
+ dcr: { available: true, clientMode: 'public', supportsRefresh: true },
+ endpoints: {
+ authorization: 'https://mcp.notion.com/authorize',
+ token: 'https://mcp.notion.com/token',
+ registration: 'https://mcp.notion.com/register',
+ },
+ resource: 'https://mcp.notion.com',
+ issuer: 'https://mcp.notion.com',
+ scopes: ['default'],
+ quirks: { bearerInBody: false, supportsRefresh: true },
+}
+
+/** DCR-confidential (Notion minus CIMD support and minus `none`). */
+export const DCR_CONFIDENTIAL_DETECTED: RemoteDetected = {
+ registrationMode: 'dcr',
+ dcr: { available: true, clientMode: 'confidential', supportsRefresh: true },
+ endpoints: {
+ authorization: 'https://mcp.notion.com/authorize',
+ token: 'https://mcp.notion.com/token',
+ registration: 'https://mcp.notion.com/register',
+ },
+ resource: 'https://mcp.notion.com',
+ issuer: 'https://mcp.notion.com',
+ scopes: ['default'],
+ quirks: { bearerInBody: false, supportsRefresh: true },
+}