Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-ui): ask for the Entra tenant, make scopes editable and show the AS profile
Diego Zacarias6da789a82efb
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex c0f62a48f..0de3ae7bd 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -4740,6 +4740,14 @@ td.cu-registry-description {margin-top: var(--cu-space-1);}+/* Remote wizard: the exact scopes an Entra install asks the operator to confirm. */+.cu-unverified-scopes {+ margin: var(--cu-space-1) 0;+ padding-left: var(--cu-space-4);+ font-family: var(--cu-font-mono);+ overflow-wrap: anywhere;+}+/* Catalog-attention banner (stale-but-referenced models) on /llm-models. */.cu-model-attention__lede {margin: 0 0 var(--cu-space-2);diff --git a/control-ui/components/AddRemoteServerWizard/constants.ts b/control-ui/components/AddRemoteServerWizard/constants.tsindex 939700a1a..2709d7453 100644--- a/control-ui/components/AddRemoteServerWizard/constants.ts+++ b/control-ui/components/AddRemoteServerWizard/constants.ts@@ -48,3 +48,10 @@ export const REGISTRATION_MODE_HINT: Record<RemoteDiscoverRegistrationMode, strimanual:'The server offers neither CIMD nor dynamic registration, so you must supply a pre-registered client_id and client_secret.',}++/**+ * Scopes the operator may type; mirrors the McpServer CRD `spec.oauth.scopes` maxItems.+ * Scopes an authorization-server profile adds (Entra's offline_access) are counted only+ * by control-api, which answers with its own message when the total is over.+ */+export const REMOTE_SCOPES_MAX = 128diff --git a/control-ui/components/AddRemoteServerWizard/index.tsx b/control-ui/components/AddRemoteServerWizard/index.tsxindex 9c9336c57..71ce58dbe 100644--- a/control-ui/components/AddRemoteServerWizard/index.tsx+++ b/control-ui/components/AddRemoteServerWizard/index.tsx@@ -5,7 +5,7 @@ import { CreateFlowPanel } from '@components/CreateFlowPanel'import { CreateStepFlow } from '@components/CreateStepFlow'import { useToast } from '@components/Toast'import { IconCopy } from '@components/icons'-import { Button, Field, SelectInput, TextInput } from '@components/ui'+import { Button, CheckboxField, Field, SelectInput, TextInput } from '@components/ui'import { getContexts, isSilentApiError } from '@lib/api'import type { ContextResource } from '@lib/api'import { copyTextToClipboard } from '@lib/clipboard'@@ -15,28 +15,36 @@ import {describeTransportProbe,discoverRemoteServer,displayClientMode,+ getEntraTenantIdError,getRemoteBaseUrlError,getRemoteServerNameError,installModeForRegistration,installRemoteServer,mapRemoteDiscoverError,mapRemoteInstallError,+ parseRemoteScopesInput,remoteCallbackBlocker,remotePreRegisteredRedirectUri,+ remoteScopesOverride,requiresPreRegisteredCredentials,shouldWarnNoRefresh,+ tenantAuthority,+ tenantRequiredDetail,transportBlocksContinue,+ unverifiedScopesFromInstallError,} from '@lib/remoteMcp'import type {RemoteCallbackPreview,RemoteDetected,RemoteGrantScope,+ RemoteTenantRequiredDetail,RemoteTransportProbe,} from '@lib/remoteMcp.types'import {GRANT_SCOPE_OPTIONS,REGISTRATION_MODE_HINT,REGISTRATION_MODE_LABEL,+ REMOTE_SCOPES_MAX,REMOTE_WIZARD_STEPS,REMOTE_WIZARD_STEP_DETAILS,} from './constants'@@ -76,11 +84,22 @@ export function AddRemoteServerWizard({const [transport, setTransport] = useState<RemoteTransportProbe | null>(null)// Callback preview for the current detection; undefined on an older control-api.const [callback, setCallback] = useState<RemoteCallbackPreview | undefined>(undefined)+ // Set when the server signs in through Entra's multi-tenant authority: the operator+ // must name the tenant before discovery can pin an issuer. Survives a failed+ // re-detect so a wrong tenant can be corrected in place.+ const [tenantPrompt, setTenantPrompt] = useState<RemoteTenantRequiredDetail | null>(null)+ const [tenantId, setTenantId] = useState('')+ // Authorization server used by the discover that produced `detected`; sent again at+ // install so control-api re-discovers against the same tenant.+ const [detectedAuthorizationServer, setDetectedAuthorizationServer] = useState<+ string | undefined+ >(undefined)// Step 1 — configurationconst [clientId, setClientId] = useState('')const [clientSecret, setClientSecret] = useState('')const [grantScope, setGrantScope] = useState<RemoteGrantScope>('user')+ const [scopesInput, setScopesInput] = useState('')// Step 2 — installconst [installing, setInstalling] = useState(false)@@ -88,6 +107,10 @@ export function AddRemoteServerWizard({// A pre-registered install holds here so the operator can copy the redirect URI// the AS must hold before leaving the wizard.const [installed, setInstalled] = useState<InstalledRedirectUri | null>(null)+ // Scopes whose API control-api cannot tie to this server. The confirmation covers+ // exactly this list: replacing the list always clears it.+ const [unverifiedToConfirm, setUnverifiedToConfirm] = useState<string[]>([])+ const [unverifiedConfirmed, setUnverifiedConfirmed] = useState(false)useEffect(() => {let cancelled = false@@ -114,6 +137,8 @@ export function AddRemoteServerWizard({getRemoteBaseUrlError(trimmedBaseUrl) === '' &&getRemoteServerNameError(serverName) === '' &&contextRef !== ''+ const tenantIdError = getEntraTenantIdError(tenantId)+ const tenantReady = !tenantPrompt || tenantIdError === ''const installMode = detected ? installModeForRegistration(detected.registrationMode) : nullconst needsCredentials = installMode ? requiresPreRegisteredCredentials(installMode) : false@@ -130,10 +155,35 @@ export function AddRemoteServerWizard({: nullconst asEndpointHosts = detected?.asEndpointHosts+ const entraProfile = detected?.asProfile === 'entra-v2'+ // Without a profile, the advertised list is accepted as typed even when it breaks+ // RFC 6749, so a server with non-conforming scopes is not blocked here. With a profile+ // the list is always sent and control-api enforces the charset, so validate it.+ const scopeTokens = scopesInput.trim().split(/\s+/).filter(Boolean)+ const scopesAsAdvertised =+ detected !== null &&+ !entraProfile &&+ scopeTokens.length === detected.scopes.length &&+ scopeTokens.every((scope, i) => scope === detected.scopes[i])+ const parsedScopes = scopesAsAdvertised+ ? { scopes: scopeTokens }+ : parseRemoteScopesInput(scopesInput, REMOTE_SCOPES_MAX)+ const scopesError = 'error' in parsedScopes ? parsedScopes.error : ''+ const scopesOverride =+ detected && 'scopes' in parsedScopes+ ? remoteScopesOverride(parsedScopes.scopes, detected.scopes)+ : undefined+ const effectiveScopes = scopesOverride ?? detected?.scopes ?? []+const credentialsComplete =!needsCredentials || (clientId.trim().length > 0 && clientSecret.length > 0)const step1Valid =- Boolean(detected) && identifiersValid && credentialsComplete && callbackBlocker === ''+ Boolean(detected) &&+ identifiersValid &&+ credentialsComplete &&+ callbackBlocker === '' &&+ scopesError === ''+ const confirmationPending = unverifiedToConfirm.length > 0 && !unverifiedConfirmedfunction canSelectStep(target: number): boolean {// Once installed, going back would offer a second install of the same server.@@ -152,11 +202,40 @@ export function AddRemoteServerWizard({[contexts])+ function clearUnverifiedConfirmation() {+ setUnverifiedToConfirm([])+ setUnverifiedConfirmed(false)+ }+function resetDetection() {setDetected(null)setTransport(null)setCallback(undefined)setDiscoverError('')+ setDetectedAuthorizationServer(undefined)+ setScopesInput('')+ clearUnverifiedConfirmation()+ }++ // A new URL may be a different server, so the tenant asked for the old one is dropped.+ function changeBaseUrl(value: string) {+ setBaseUrl(value)+ // Editing the URL invalidates a prior detection or transport probe.+ if (detected || transport) resetDetection()+ setTenantPrompt(null)+ setTenantId('')+ }++ function goToStep(target: number) {+ if (target === 2 && step !== 2) {+ // The backend's discover-time list only holds for the scopes it advertised; for+ // edited scopes the install answers with the list to confirm.+ setUnverifiedToConfirm(scopesOverride === undefined ? (detected?.unverifiedScopes ?? []) : [])+ setUnverifiedConfirmed(false)+ } else if (target < 2) {+ clearUnverifiedConfirmation()+ }+ setStep(target)}async function copyRedirectUri(uri: string) {@@ -167,6 +246,10 @@ export function AddRemoteServerWizard({}async function runDetect() {+ const authorizationServer =+ tenantPrompt && tenantIdError === ''+ ? tenantAuthority(tenantPrompt.tenantAuthorityTemplate, tenantId)+ : undefinedsetDetecting(true)setDiscoverError('')setTransport(null)@@ -176,7 +259,9 @@ export function AddRemoteServerWizard({detected: nextDetected,transport: nextTransport,callback: nextCallback,- } = await discoverRemoteServer(trimmedBaseUrl)+ } = await (authorizationServer === undefined+ ? discoverRemoteServer(trimmedBaseUrl)+ : discoverRemoteServer(trimmedBaseUrl, authorizationServer))if (transportBlocksContinue(nextTransport)) {// Dead MCP transport: never install a URL the probe proved dead. Hold on// step 0, surface the reason (and any canonical URL suggestion), and keep@@ -188,10 +273,19 @@ export function AddRemoteServerWizard({setDetected(nextDetected)setTransport(nextTransport ?? null)setCallback(nextCallback)+ setDetectedAuthorizationServer(authorizationServer)+ setScopesInput(nextDetected.scopes.join(' '))setStep(1)} catch (e) {if (isSilentApiError(e)) returnsetDetected(null)+ const tenantRequired = tenantRequiredDetail(e)+ if (tenantRequired) {+ // The tenant prompt replaces the error banner: this is a question, not a failure.+ setTenantPrompt(tenantRequired)+ setDiscoverError('')+ return+ }setDiscoverError(mapRemoteDiscoverError(e))} finally {setDetecting(false)@@ -199,7 +293,7 @@ export function AddRemoteServerWizard({}async function runInstall() {- if (!detected || !installMode) return+ if (!detected || !installMode || confirmationPending) returnsetInstalling(true)setInstallError('')try {@@ -211,6 +305,11 @@ export function AddRemoteServerWizard({grantScope,clientId: needsCredentials ? clientId : undefined,clientSecret: needsCredentials ? clientSecret : undefined,+ // With a profile control-api requires the list, so the one on screen is always+ // sent rather than letting a re-discovery decide what gets installed.+ scopes: entraProfile ? effectiveScopes : scopesOverride,+ authorizationServer: detectedAuthorizationServer,+ confirmedUnverifiedScopes: unverifiedConfirmed ? unverifiedToConfirm : undefined,})const res = await installRemoteServer(body)showToast(`Remote server ${res.serverName} installed.`, { tone: 'success' })@@ -225,6 +324,12 @@ export function AddRemoteServerWizard({onInstalled()} catch (e) {if (isSilentApiError(e)) return+ const toConfirm = unverifiedScopesFromInstallError(e)+ if (toConfirm) {+ setUnverifiedToConfirm(toConfirm)+ setUnverifiedConfirmed(false)+ return+ }setInstallError(mapRemoteInstallError(e, { callbackVariant: callback?.variant }))} finally {setInstalling(false)@@ -246,7 +351,7 @@ export function AddRemoteServerWizard({className="cu-create-step-flow--3"currentStep={step}onStepChange={target => {- if (canSelectStep(target)) setStep(target)+ if (canSelectStep(target)) goToStep(target)}}canSelectStep={canSelectStep}steps={REMOTE_WIZARD_STEP_DETAILS}@@ -266,11 +371,7 @@ export function AddRemoteServerWizard({id="remote-base-url"invalid={Boolean(baseUrlError)}monospace- onChange={event => {- setBaseUrl(event.target.value)- // Editing the URL invalidates a prior detection or transport probe.- if (detected || transport) resetDetection()- }}+ onChange={event => changeBaseUrl(event.target.value)}placeholder="https://mcp.example.com/mcp"disabled={detecting}autoFocus@@ -278,6 +379,30 @@ export function AddRemoteServerWizard({/></Field>+ {tenantPrompt ? (+ <Field+ label="Microsoft Entra tenant ID"+ description="This server signs in with Microsoft Entra ID. Enter your organization's Directory (tenant) ID — a GUID shown on the Microsoft Entra admin center overview."+ error={tenantId.length > 0 ? tenantIdError || undefined : undefined}+ htmlFor="remote-entra-tenant-id"+ required+ >+ <TextInput+ id="remote-entra-tenant-id"+ monospace+ autoFocus+ value={tenantId}+ placeholder="00000000-0000-0000-0000-000000000000"+ disabled={detecting}+ invalid={tenantId.length > 0 && tenantIdError !== ''}+ onChange={event => {+ setTenantId(event.target.value)+ if (detected || transport) resetDetection()+ }}+ />+ </Field>+ ) : null}+<Fielddescription="Kubernetes resource name: lowercase alphanumeric and hyphens, max 63 chars."error={serverNameError || undefined}@@ -332,10 +457,7 @@ export function AddRemoteServerWizard({{suggestedBaseUrl ? (<div className="cu-transport-suggestion"><Button- onClick={() => {- setBaseUrl(suggestedBaseUrl)- resetDetection()- }}+ onClick={() => changeBaseUrl(suggestedBaseUrl)}size="sm"variant="ghost">@@ -376,9 +498,19 @@ export function AddRemoteServerWizard({<span>Issuer</span><strong>{detected.issuer}</strong></div>+ {entraProfile ? (+ <div className="cu-summary-list__row">+ <span>Authorization server</span>+ <strong>Microsoft Entra ID</strong>+ </div>+ ) : null}<div className="cu-summary-list__row"><span>Resource</span>- <strong>{detected.resource}</strong>+ <strong>+ {entraProfile+ ? `${detected.resource} (not sent to Microsoft Entra ID)`+ : detected.resource}+ </strong></div>{aliveTransport ? (<div className="cu-summary-list__row">@@ -402,10 +534,6 @@ export function AddRemoteServerWizard({<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>@@ -414,6 +542,38 @@ export function AddRemoteServerWizard({) : null}</section>+ {detected.scopeAudienceMissing ? (+ <div className="cu-banner cu-banner--warning" role="status">+ This server doesn’t advertise its own scope. Enter it before installing; sign-in+ scopes alone would send a Microsoft Graph token to the server.+ </div>+ ) : null}++ {detected.scopeAudienceViolation ? (+ <div className="cu-banner cu-banner--warning" role="status">+ {`The server suggests the scope "${detected.scopeAudienceViolation}", which would mint a token for another API. Replace it with this server's own scope before installing.`}+ </div>+ ) : null}++ <Field+ label="Scopes"+ htmlFor="remote-scopes"+ error={scopesError || undefined}+ description={+ entraProfile+ ? 'Space-separated. offline_access is always added so connections can refresh. Leave empty to use the scopes the server advertises.'+ : 'Space-separated scopes requested at sign-in. Leave empty to use the scopes the server advertises.'+ }+ >+ <TextInput+ id="remote-scopes"+ monospace+ invalid={scopesError !== ''}+ value={scopesInput}+ onChange={event => setScopesInput(event.target.value)}+ />+ </Field>+<p className="cu-field__hint">{REGISTRATION_MODE_HINT[detected.registrationMode]}</p>{callbackBlocker ? (@@ -542,6 +702,10 @@ export function AddRemoteServerWizard({<span>Token endpoint</span><strong>{detected.endpoints.token}</strong></div>+ <div className="cu-summary-list__row">+ <span>Scopes</span>+ <strong>{effectiveScopes.join(' ') || '—'}</strong>+ </div>{preRegisteredRedirectUri ? (<div className="cu-summary-list__row"><span>Redirect URI</span>@@ -565,6 +729,26 @@ export function AddRemoteServerWizard({</div>) : null}+ {unverifiedToConfirm.length > 0 ? (+ <div className="cu-banner cu-banner--warning" role="status">+ <div>+ These scopes name a Microsoft Entra API that this platform cannot tie to this+ server. A token for that API will be sent to the server.+ </div>+ <ul className="cu-unverified-scopes">+ {unverifiedToConfirm.map(scope => (+ <li key={scope}>{scope}</li>+ ))}+ </ul>+ <CheckboxField+ checked={unverifiedConfirmed}+ disabled={installing}+ label="I confirm these scopes belong to this server’s own API."+ onChange={event => setUnverifiedConfirmed(event.target.checked)}+ />+ </div>+ ) : null}+{installError ? (<div className="cu-banner cu-banner--error" role="alert">{installError}@@ -582,7 +766,7 @@ export function AddRemoteServerWizard({{installed ? null : (<Buttondisabled={detecting || installing}- onClick={() => (step === 0 ? onCancel() : setStep(current => current - 1))}+ onClick={() => (step === 0 ? onCancel() : goToStep(step - 1))}size="sm"variant="ghost">@@ -594,7 +778,7 @@ export function AddRemoteServerWizard({detected ? (<Buttondisabled={!identifiersValid}- onClick={() => setStep(1)}+ onClick={() => goToStep(1)}size="sm"variant="primary">@@ -602,7 +786,7 @@ export function AddRemoteServerWizard({</Button>) : (<Button- disabled={!identifiersValid || detecting}+ disabled={!identifiersValid || !tenantReady || detecting}loading={detecting}onClick={() => void runDetect()}size="sm"@@ -614,14 +798,19 @@ export function AddRemoteServerWizard({) : null}{step === 1 ? (- <Button disabled={!step1Valid} onClick={() => setStep(2)} size="sm" variant="primary">+ <Button+ disabled={!step1Valid}+ onClick={() => goToStep(2)}+ size="sm"+ variant="primary"+ >Continue</Button>) : null}{step === 2 && !installed ? (<Button- disabled={!step1Valid || installing}+ disabled={!step1Valid || installing || confirmationPending}loading={installing}size="sm"type="submit"diff --git a/control-ui/components/__tests__/AddRemoteServerWizard.test.tsx b/control-ui/components/__tests__/AddRemoteServerWizard.test.tsxindex 0edb96a00..883916e88 100644--- a/control-ui/components/__tests__/AddRemoteServerWizard.test.tsx+++ b/control-ui/components/__tests__/AddRemoteServerWizard.test.tsx@@ -13,6 +13,8 @@ import {ATLASSIAN_DISCOVER,ATLASSIAN_DISCOVER_UNCONFIGURED,CALLBACK_UNCONFIGURED_FAILURE,+ ENTRA_NO_SCOPES_DISCOVER,+ ENTRA_UNKNOWN_GUID_DISCOVER,LINEAR_DISCOVER,LINEAR_DISCOVER_UNCONFIGURED,LINEAR_INSTALLED,@@ -21,6 +23,12 @@ import {PRE_REGISTERED_PER_SERVER_DISCOVER,PRE_REGISTERED_PER_SERVER_INSTALLED,PRE_REGISTERED_SHARED_INSTALLED,+ SCOPE_AUDIENCE_MISSING_FAILURE,+ SCOPE_AUDIENCE_UNVERIFIED_FAILURE,+ SCOPE_LIMIT_EXCEEDED_FAILURE,+ WORKIQ_DISCOVER,+ WORKIQ_DISCOVER_TENANT_REQUIRED,+ WORKIQ_INSTALLED,apiErrorFrom,} from '../../test/fixtures/remoteMcpWire'import { AddRemoteServerWizard } from '../AddRemoteServerWizard'@@ -76,6 +84,10 @@ afterEach(() => {// next test, then restore the default successful copy.copyMock.mockReset()copyMock.mockResolvedValue(true)+ // Same for the network stubs: a test that fails before consuming its queued answers+ // must not hand them to the next one.+ discoverMock.mockReset()+ installMock.mockReset()})function renderWizard(props?: Partial<Parameters<typeof AddRemoteServerWizard>[0]>) {@@ -122,7 +134,7 @@ describe('AddRemoteServerWizard', () => {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()+ expect(screen.getByDisplayValue('default')).toBeInTheDocument()})it('D-4: editing the URL after a detect invalidates it and blocks proceeding until re-detect', async () => {@@ -493,4 +505,303 @@ describe('AddRemoteServerWizard', () => {screen.queryByRole('region', { name: 'Authorization server hosts' })).not.toBeInTheDocument()})++ // ── Microsoft Entra ID (tenant prompt, editable scopes, profile) ───────────++ const WORKIQ_URL = 'https://workiq.svc.cloud.microsoft/mcp'+ const TENANT = '72f988bf-86f1-41af-91ab-2d7cd011db47'+ const TENANT_AUTHORITY = `https://login.microsoftonline.com/${TENANT}/v2.0`++ function tenantInput() {+ return screen.getByLabelText(/Microsoft Entra tenant ID/)+ }++ function scopesInput() {+ return screen.getByLabelText('Scopes')+ }++ function lastInstallBody() {+ const calls = installMock.mock.calls+ return calls[calls.length - 1]?.[0]+ }++ /** Detect → tenant_required → type the tenant → Detect against `body`. */+ async function detectEntra(body: DiscoverRemoteResponse, tenant = TENANT) {+ discoverMock+ .mockRejectedValueOnce(apiErrorFrom(WORKIQ_DISCOVER_TENANT_REQUIRED))+ .mockResolvedValueOnce(body)+ const utils = renderWizard()+ await fillIdentity(WORKIQ_URL, 'workiq')+ clickDetect()+ await screen.findByLabelText(/Microsoft Entra tenant ID/)+ fireEvent.change(tenantInput(), { target: { value: tenant } })+ clickDetect()+ await screen.findByLabelText('Scopes')+ return utils+ }++ function fillCredentials() {+ fireEvent.change(screen.getByLabelText(/Client ID/), { target: { value: 'cid' } })+ fireEvent.change(screen.getByLabelText(/Client secret/), { target: { value: 'secret' } })+ }++ async function toConfirm() {+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+ return screen.findByRole('button', { name: 'Install remote server' })+ }++ it('entra 1: tenant_required asks for the tenant instead of showing an error', async () => {+ discoverMock.mockRejectedValueOnce(apiErrorFrom(WORKIQ_DISCOVER_TENANT_REQUIRED))+ renderWizard()+ await fillIdentity(WORKIQ_URL, 'workiq')+ clickDetect()++ expect(await screen.findByLabelText(/Microsoft Entra tenant ID/)).toBeInTheDocument()+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()+ // Still on step 0, waiting for the tenant.+ expect(screen.getByRole('button', { name: 'Detect' })).toBeDisabled()+ })++ it('entra 2: a tenant that is not a GUID keeps Detect disabled and says why', async () => {+ discoverMock.mockRejectedValueOnce(apiErrorFrom(WORKIQ_DISCOVER_TENANT_REQUIRED))+ renderWizard()+ await fillIdentity(WORKIQ_URL, 'workiq')+ clickDetect()+ await screen.findByLabelText(/Microsoft Entra tenant ID/)++ fireEvent.change(tenantInput(), { target: { value: 'contoso.onmicrosoft.com' } })+ expect(screen.getByRole('button', { name: 'Detect' })).toBeDisabled()+ expect(screen.getByText(/Enter the tenant ID as a GUID/)).toBeInTheDocument()+ expect(discoverMock).toHaveBeenCalledTimes(1)+ })++ it('entra 3: an upper-case GUID is sent as the lower-case tenant authority', async () => {+ await detectEntra(WORKIQ_DISCOVER, TENANT.toUpperCase())+ expect(discoverMock).toHaveBeenCalledTimes(2)+ expect(discoverMock).toHaveBeenNthCalledWith(1, WORKIQ_URL)+ expect(discoverMock).toHaveBeenNthCalledWith(2, WORKIQ_URL, TENANT_AUTHORITY)+ })++ it('entra 4: shows the Entra profile, the unsent resource and the advertised scopes', async () => {+ await detectEntra(WORKIQ_DISCOVER)+ const summary = screen.getByRole('region', { name: 'Detected OAuth configuration' })+ expect(summary).toHaveTextContent('Authorization serverMicrosoft Entra ID')+ expect(summary).toHaveTextContent(+ `${WORKIQ_DISCOVER.detected.resource} (not sent to Microsoft Entra ID)`+ )+ expect(scopesInput()).toHaveValue(WORKIQ_DISCOVER.detected.scopes.join(' '))+ expect(screen.queryByText(/does not support token refresh/i)).not.toBeInTheDocument()++ fillCredentials()+ await toConfirm()+ expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()+ })++ it('entra 5: the install sends the shown scopes and the tenant authority', async () => {+ installMock.mockResolvedValue(WORKIQ_INSTALLED)+ await detectEntra(WORKIQ_DISCOVER)+ fillCredentials()+ await toConfirm()+ // The confirm step lists the scopes that will be requested.+ expect(screen.getByRole('region', { name: 'Install summary' })).toHaveTextContent(+ `Scopes${WORKIQ_DISCOVER.detected.scopes.join(' ')}`+ )+ fireEvent.click(screen.getByRole('button', { name: 'Install remote server' }))++ await waitFor(() => expect(installMock).toHaveBeenCalledTimes(1))+ expect(lastInstallBody()).toMatchObject({+ serverName: 'workiq',+ mode: 'pre-registered',+ authorizationServer: TENANT_AUTHORITY,+ scopes: WORKIQ_DISCOVER.detected.scopes,+ })+ expect(lastInstallBody()).not.toHaveProperty('confirmedUnverifiedScopes')+ expect(await screen.findByRole('textbox', { name: 'Redirect URI' })).toHaveValue(+ WORKIQ_INSTALLED.redirectUri+ )+ })++ it('entra 5b: edited scopes are what the install sends', async () => {+ installMock.mockResolvedValue(WORKIQ_INSTALLED)+ await detectEntra(WORKIQ_DISCOVER)+ fireEvent.change(scopesInput(), {+ target: { value: 'api://workiq.svc.cloud.microsoft/WorkIQAgent.Ask' },+ })+ fillCredentials()+ await toConfirm()+ fireEvent.click(screen.getByRole('button', { name: 'Install remote server' }))++ await waitFor(() => expect(installMock).toHaveBeenCalledTimes(1))+ expect(lastInstallBody()?.scopes).toEqual(['api://workiq.svc.cloud.microsoft/WorkIQAgent.Ask'])+ })++ it('entra 5c: an emptied field with the profile still sends the advertised list', async () => {+ installMock.mockResolvedValue(WORKIQ_INSTALLED)+ await detectEntra(WORKIQ_DISCOVER)+ fireEvent.change(scopesInput(), { target: { value: ' ' } })+ fillCredentials()+ await toConfirm()+ fireEvent.click(screen.getByRole('button', { name: 'Install remote server' }))++ await waitFor(() => expect(installMock).toHaveBeenCalledTimes(1))+ expect(lastInstallBody()?.scopes).toEqual(WORKIQ_DISCOVER.detected.scopes)+ })++ it('entra 6: editing the URL drops the tenant prompt', async () => {+ discoverMock.mockRejectedValueOnce(apiErrorFrom(WORKIQ_DISCOVER_TENANT_REQUIRED))+ renderWizard()+ await fillIdentity(WORKIQ_URL, 'workiq')+ clickDetect()+ await screen.findByLabelText(/Microsoft Entra tenant ID/)+ fireEvent.change(tenantInput(), { target: { value: TENANT } })++ fireEvent.change(screen.getByPlaceholderText('https://mcp.example.com/mcp'), {+ target: { value: 'https://mcp.linear.app/mcp' },+ })+ expect(screen.queryByLabelText(/Microsoft Entra tenant ID/)).not.toBeInTheDocument()++ // A later tenant_required for the new URL starts from an empty tenant.+ discoverMock.mockRejectedValueOnce(apiErrorFrom(WORKIQ_DISCOVER_TENANT_REQUIRED))+ clickDetect()+ expect(await screen.findByLabelText(/Microsoft Entra tenant ID/)).toHaveValue('')+ expect(discoverMock).toHaveBeenLastCalledWith('https://mcp.linear.app/mcp')+ })++ it('entra 7: a server advertising no scopes installs with an empty field and no scopes', async () => {+ // No golden advertises an empty list; Linear's body with only `scopes` emptied stands+ // for a PRM and AS that both omit scopes_supported (the backend then derives []).+ const noScopes: DiscoverRemoteResponse = {+ ...LINEAR_DISCOVER,+ detected: { ...LINEAR_DISCOVER.detected, scopes: [] },+ }+ discoverMock.mockResolvedValue(noScopes)+ installMock.mockResolvedValue(LINEAR_INSTALLED)+ renderWizard()+ await fillIdentity('https://mcp.linear.app/mcp', 'linear')+ clickDetect()+ expect(await screen.findByLabelText('Scopes')).toHaveValue('')++ const install = await toConfirm()+ expect(install).toBeEnabled()+ fireEvent.click(install)+ await waitFor(() => expect(installMock).toHaveBeenCalledTimes(1))+ expect(lastInstallBody()).not.toHaveProperty('scopes')+ expect(lastInstallBody()).not.toHaveProperty('authorizationServer')+ })++ it('entra 7b: without a profile, untouched scopes are not sent and edited ones are', async () => {+ discoverMock.mockResolvedValue(LINEAR_DISCOVER)+ installMock.mockResolvedValue(LINEAR_INSTALLED)+ renderWizard()+ await fillIdentity('https://mcp.linear.app/mcp', 'linear')+ clickDetect()+ await screen.findByLabelText('Scopes')+ fireEvent.change(scopesInput(), { target: { value: 'read' } })+ fireEvent.click(await toConfirm())+ await waitFor(() => expect(installMock).toHaveBeenCalledTimes(1))+ expect(lastInstallBody()?.scopes).toEqual(['read'])+ })++ it('entra 9: an unverifiable advertised scope must be confirmed, and the confirmation is sent', async () => {+ installMock.mockResolvedValue(WORKIQ_INSTALLED)+ const unverified = ENTRA_UNKNOWN_GUID_DISCOVER.detected.unverifiedScopes ?? []+ expect(unverified.length).toBeGreaterThan(0)+ await detectEntra(ENTRA_UNKNOWN_GUID_DISCOVER)+ fillCredentials()+ const install = await toConfirm()++ const notice = screen.getByText(/cannot tie to this server/).closest('[role="status"]')+ expect(notice).not.toBeNull()+ for (const scope of unverified) expect(notice).toHaveTextContent(scope)+ const confirm = screen.getByRole('checkbox', {+ name: 'I confirm these scopes belong to this server’s own API.',+ })+ expect(install).toBeDisabled()++ fireEvent.click(confirm)+ expect(install).toBeEnabled()+ fireEvent.click(install)+ await waitFor(() => expect(installMock).toHaveBeenCalledTimes(1))+ expect(lastInstallBody()?.confirmedUnverifiedScopes).toEqual(unverified)+ })++ it('entra 9b: going back clears a confirmation', async () => {+ await detectEntra(ENTRA_UNKNOWN_GUID_DISCOVER)+ fillCredentials()+ await toConfirm()+ fireEvent.click(screen.getByRole('checkbox'))+ fireEvent.click(screen.getByRole('button', { name: 'Back' }))+ const install = await toConfirm()+ expect(screen.getByRole('checkbox')).not.toBeChecked()+ expect(install).toBeDisabled()+ })++ it('entra 10: an edited scope the backend cannot verify turns into the confirmation', async () => {+ const edited = (SCOPE_AUDIENCE_UNVERIFIED_FAILURE.body as { scopes: string[] }).scopes+ installMock+ .mockRejectedValueOnce(apiErrorFrom(SCOPE_AUDIENCE_UNVERIFIED_FAILURE))+ .mockResolvedValueOnce(WORKIQ_INSTALLED)+ await detectEntra(WORKIQ_DISCOVER)+ fireEvent.change(scopesInput(), { target: { value: edited.join(' ') } })+ fillCredentials()+ const install = await toConfirm()+ // The discover-time list does not cover edited scopes: nothing to confirm yet.+ expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()+ fireEvent.click(install)++ const confirm = await screen.findByRole('checkbox')+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()+ expect(install).toBeDisabled()+ expect(lastInstallBody()).not.toHaveProperty('confirmedUnverifiedScopes')++ fireEvent.click(confirm)+ fireEvent.click(install)+ await waitFor(() => expect(installMock).toHaveBeenCalledTimes(2))+ expect(lastInstallBody()).toMatchObject({ scopes: edited, confirmedUnverifiedScopes: edited })+ })++ it('entra 11: a known GUID scope for its own host needs no confirmation', async () => {+ expect(WORKIQ_DISCOVER.detected.unverifiedScopes).toBeUndefined()+ await detectEntra(WORKIQ_DISCOVER)+ fillCredentials()+ const install = await toConfirm()+ expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()+ expect(screen.queryByText(/cannot tie to this server/)).not.toBeInTheDocument()+ expect(install).toBeEnabled()+ })++ it('entra 12: sign-in scopes only warn on detect and the install explains the 400', async () => {+ installMock.mockRejectedValueOnce(apiErrorFrom(SCOPE_AUDIENCE_MISSING_FAILURE))+ await detectEntra(ENTRA_NO_SCOPES_DISCOVER)+ const banner = screen.getByText(/doesn’t advertise its own scope/)+ expect(banner.closest('[role="status"]')).not.toBeNull()++ fillCredentials()+ fireEvent.click(await toConfirm())+ expect(await screen.findByRole('alert')).toHaveTextContent(+ 'Add this server’s own scope. Sign-in scopes alone (openid, profile, email, offline_access) would send a Microsoft Graph token to the server.'+ )+ })++ it('entra 13: 128 scopes pass the field; the backend limit message is shown', async () => {+ installMock.mockRejectedValueOnce(apiErrorFrom(SCOPE_LIMIT_EXCEEDED_FAILURE))+ await detectEntra(WORKIQ_DISCOVER)+ const many = Array.from({ length: 128 }, (_, i) => `api://workiq.svc.cloud.microsoft/Scope${i}`)+ fireEvent.change(scopesInput(), { target: { value: many.join(' ') } })+ expect(screen.queryByText(/At most 128 scopes/)).not.toBeInTheDocument()++ fillCredentials()+ fireEvent.click(await toConfirm())+ expect(await screen.findByRole('alert')).toHaveTextContent(+ (SCOPE_LIMIT_EXCEEDED_FAILURE.body as { message: string }).message+ )+ expect(lastInstallBody()?.scopes).toEqual(many)+ })++ it('entra: a scope with characters OAuth forbids blocks Continue with the profile', async () => {+ await detectEntra(WORKIQ_DISCOVER)+ fireEvent.change(scopesInput(), { target: { value: 'bad"scope' } })+ expect(screen.getByText(/contains characters OAuth does not allow/)).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled()+ })})diff --git a/control-ui/lib/__tests__/remoteMcp.test.ts b/control-ui/lib/__tests__/remoteMcp.test.tsindex 37f437609..cd06c2b3d 100644--- a/control-ui/lib/__tests__/remoteMcp.test.ts+++ b/control-ui/lib/__tests__/remoteMcp.test.ts@@ -13,6 +13,7 @@ import {DCR_CONFIDENTIAL_DETECTED,DCR_REDIRECT_MISMATCH_FAILURE,DROPBOX_DISCOVER_FAILURE,+ ENTRA_UNKNOWN_TENANT_DISCOVER_FAILURE,ISSUER_PUBLIC_SUFFIX_DISCOVER_FAILURE,LINEAR_DETECTED,LINEAR_DISCOVER,@@ -23,6 +24,12 @@ import {OLDER_CONTROL_API_LINEAR_DISCOVER,PRE_REGISTERED_PER_SERVER_DETECTED,PRE_REGISTERED_PER_SERVER_DISCOVER,+ SCOPE_AUDIENCE_MISMATCH_FAILURE,+ SCOPE_AUDIENCE_MISSING_FAILURE,+ SCOPE_AUDIENCE_UNVERIFIED_FAILURE,+ SCOPE_LIMIT_EXCEEDED_FAILURE,+ WORKIQ_DISCOVER,+ WORKIQ_DISCOVER_TENANT_REQUIRED,apiErrorFrom,} from '../../test/fixtures/remoteMcpWire'import {@@ -30,17 +37,23 @@ import {describeDiscoveryError,describeTransportProbe,displayClientMode,+ getEntraTenantIdError,getRemoteBaseUrlError,getRemoteServerNameError,installModeForRegistration,mapRemoteDiscoverError,mapRemoteInstallError,+ parseRemoteScopesInput,remoteCallbackBlocker,remoteCallbackVariant,remotePreRegisteredRedirectUri,+ remoteScopesOverride,requiresPreRegisteredCredentials,shouldWarnNoRefresh,+ tenantAuthority,+ tenantRequiredDetail,transportBlocksContinue,+ unverifiedScopesFromInstallError,} from '../remoteMcp'import type { RemoteTransportProbe } from '../remoteMcp.types'@@ -252,6 +265,148 @@ describe('buildRemoteInstallRequest', () => {expect(body.clientSecret).toBe('super-secret')expect(body.grantScope).toBe('context')})++ it('sends the Entra fields only when set, and confirmations only when non-empty', () => {+ const base = {+ serverName: 'workiq',+ contextRef: 'research',+ baseUrl: 'https://workiq.svc.cloud.microsoft/mcp',+ mode: 'pre-registered' as const,+ grantScope: 'user' as const,+ clientId: 'cid',+ clientSecret: 'secret',+ }+ const bare = buildRemoteInstallRequest(base)+ expect(bare).not.toHaveProperty('authorizationServer')+ expect(bare).not.toHaveProperty('scopes')+ expect(bare).not.toHaveProperty('confirmedUnverifiedScopes')++ expect(+ buildRemoteInstallRequest({ ...base, confirmedUnverifiedScopes: [] })+ ).not.toHaveProperty('confirmedUnverifiedScopes')++ const full = buildRemoteInstallRequest({+ ...base,+ authorizationServer: 'https://login.microsoftonline.com/t/v2.0',+ scopes: ['a/b', 'offline_access'],+ confirmedUnverifiedScopes: ['a/b'],+ })+ expect(full).toMatchObject({+ authorizationServer: 'https://login.microsoftonline.com/t/v2.0',+ scopes: ['a/b', 'offline_access'],+ confirmedUnverifiedScopes: ['a/b'],+ })+ })+})++describe('getEntraTenantIdError', () => {+ it('requires a value', () => {+ expect(getEntraTenantIdError('')).toBe('Tenant ID is required.')+ expect(getEntraTenantIdError(' ')).toBe('Tenant ID is required.')+ })++ it('accepts a GUID in either case, with surrounding spaces', () => {+ expect(getEntraTenantIdError('72f988bf-86f1-41af-91ab-2d7cd011db47')).toBe('')+ expect(getEntraTenantIdError(' 72F988BF-86F1-41AF-91AB-2D7CD011DB47 ')).toBe('')+ })++ it('rejects a domain name or a malformed GUID', () => {+ for (const value of ['contoso.onmicrosoft.com', '72f988bf86f141af91ab2d7cd011db47', 'x']) {+ expect(getEntraTenantIdError(value)).toMatch(/as a GUID/)+ }+ })+})++describe('tenantAuthority', () => {+ const template = tenantRequiredDetail(apiErrorFrom(WORKIQ_DISCOVER_TENANT_REQUIRED))+ ?.tenantAuthorityTemplate as string++ it('fills the backend template with the trimmed, lower-case tenant', () => {+ expect(tenantAuthority(template, ' 72F988BF-86F1-41AF-91AB-2D7CD011DB47 ')).toBe(+ 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0'+ )+ })++ it('produces the authority the Work IQ discovery pinned as issuer', () => {+ expect(tenantAuthority(template, '72f988bf-86f1-41af-91ab-2d7cd011db47')).toBe(+ WORKIQ_DISCOVER.detected.issuer+ )+ })+})++describe('tenantRequiredDetail', () => {+ it('reads the tenant_required detail of a discover failure', () => {+ expect(tenantRequiredDetail(apiErrorFrom(WORKIQ_DISCOVER_TENANT_REQUIRED))).toEqual(+ WORKIQ_DISCOVER_TENANT_REQUIRED.body &&+ (WORKIQ_DISCOVER_TENANT_REQUIRED.body as { detail: unknown }).detail+ )+ })++ it('is null for any other discovery failure', () => {+ expect(tenantRequiredDetail(apiErrorFrom(DROPBOX_DISCOVER_FAILURE))).toBeNull()+ expect(tenantRequiredDetail(apiErrorFrom(ENTRA_UNKNOWN_TENANT_DISCOVER_FAILURE))).toBeNull()+ expect(tenantRequiredDetail(new Error('boom'))).toBeNull()+ })+})++describe('parseRemoteScopesInput', () => {+ it('reads an empty field as no scopes', () => {+ expect(parseRemoteScopesInput('', 128)).toEqual({ scopes: [] })+ expect(parseRemoteScopesInput(' \n\t ', 128)).toEqual({ scopes: [] })+ })++ it('splits on whitespace only, keeping order and dropping duplicates', () => {+ expect(parseRemoteScopesInput(' a,b c\nd c ', 128)).toEqual({ scopes: ['a,b', 'c', 'd'] })+ })++ it('names the first scope with characters OAuth does not allow', () => {+ expect(parseRemoteScopesInput('ok bad"quote', 128)).toEqual({+ error: 'Scope "bad"quote" contains characters OAuth does not allow.',+ })+ expect(parseRemoteScopesInput('back\\slash', 128)).toEqual({+ error: 'Scope "back\\slash" contains characters OAuth does not allow.',+ })+ })++ it('caps the count after removing duplicates', () => {+ expect(parseRemoteScopesInput('a b c', 2)).toEqual({ error: 'At most 2 scopes.' })+ expect(parseRemoteScopesInput('a b a', 2)).toEqual({ scopes: ['a', 'b'] })+ })+})++describe('remoteScopesOverride', () => {+ const detected = WORKIQ_DISCOVER.detected.scopes++ it('sends nothing for an empty field or the advertised list', () => {+ expect(remoteScopesOverride([], detected)).toBeUndefined()+ expect(remoteScopesOverride([...detected], detected)).toBeUndefined()+ })++ it('sends the typed list when it differs, including only in order', () => {+ const edited = ['api://workiq.svc.cloud.microsoft/WorkIQAgent.Ask']+ expect(remoteScopesOverride(edited, detected)).toEqual(edited)+ const reordered = [...detected].reverse()+ expect(remoteScopesOverride(reordered, detected)).toEqual(reordered)+ })+})++describe('unverifiedScopesFromInstallError', () => {+ it('returns the scopes of a scope_audience_unverified answer', () => {+ expect(+ unverifiedScopesFromInstallError(apiErrorFrom(SCOPE_AUDIENCE_UNVERIFIED_FAILURE))+ ).toEqual((SCOPE_AUDIENCE_UNVERIFIED_FAILURE.body as { scopes: string[] }).scopes)+ })++ it('is null for other errors and for a body without a usable list', () => {+ expect(+ unverifiedScopesFromInstallError(apiErrorFrom(SCOPE_AUDIENCE_MISMATCH_FAILURE))+ ).toBeNull()+ const malformed = apiErrorFrom({+ ...SCOPE_AUDIENCE_UNVERIFIED_FAILURE,+ body: { ...(SCOPE_AUDIENCE_UNVERIFIED_FAILURE.body as object), scopes: [42] },+ })+ expect(unverifiedScopesFromInstallError(malformed)).toBeNull()+ })})describe('describeDiscoveryError', () => {@@ -267,6 +422,8 @@ describe('describeDiscoveryError', () => {'prm_resource_mismatch','issuer_mismatch','as_endpoints_cross_site',+ 'tenant_required',+ 'authorization_server_override_rejected',] as constconst texts = kinds.map(describeDiscoveryError)expect(new Set(texts).size).toBe(kinds.length)@@ -291,14 +448,49 @@ describe('mapRemoteDiscoverError', () => {})it('maps a discovery_failed detail kind', () => {- const err = Object.assign(new Error('502 ...'), {- status: 502,+ const err = Object.assign(new Error('424 ...'), {+ status: 424,code: 'discovery_failed',body: { error: 'discovery_failed', detail: { kind: 'fetch_failed' } },})expect(mapRemoteDiscoverError(err)).toBe(describeDiscoveryError('fetch_failed'))})+ it('maps an unknown Entra tenant to "did not recognize" instead of the reachability copy', () => {+ const copy = mapRemoteDiscoverError(apiErrorFrom(ENTRA_UNKNOWN_TENANT_DISCOVER_FAILURE))+ expect(ENTRA_UNKNOWN_TENANT_DISCOVER_FAILURE.status).toBe(424)+ expect(copy).toBe(+ 'Microsoft Entra ID did not recognize this tenant ID. Check the Directory (tenant) ID and try again.'+ )+ })++ it('keeps the reachability copy for a fetch failure outside Entra', () => {+ const err = Object.assign(new Error('424'), {+ code: 'discovery_failed',+ body: {+ error: 'discovery_failed',+ detail: { kind: 'fetch_failed', status: 400, url: 'https://mcp.example.com/.well-known/x' },+ },+ })+ expect(mapRemoteDiscoverError(err)).toBe(describeDiscoveryError('fetch_failed'))+ })++ it('maps tenant_required to its copy when it reaches the generic mapper', () => {+ expect(mapRemoteDiscoverError(apiErrorFrom(WORKIQ_DISCOVER_TENANT_REQUIRED))).toMatch(+ /Enter your organization's tenant ID/+ )+ })++ it('maps a discover invalid_request to a reload hint', () => {+ const err = Object.assign(new Error('400'), {+ code: 'invalid_request',+ body: { error: 'invalid_request', detail: [] },+ })+ expect(mapRemoteDiscoverError(err)).toBe(+ 'The request was rejected as invalid. Reload the page and try again.'+ )+ })+it('surfaces the kernel §4 message verbatim', () => {const err = Object.assign(new Error('400 Bad Request - baseUrl resolves to a private address'),@@ -415,6 +607,48 @@ describe('mapRemoteInstallError', () => {expect(mapRemoteInstallError(bare)).toMatch(/does not advertise RFC 9207/)})+ it('names the scope that belongs to another API', () => {+ const scope = (SCOPE_AUDIENCE_MISMATCH_FAILURE.body as { scope: string }).scope+ expect(mapRemoteInstallError(apiErrorFrom(SCOPE_AUDIENCE_MISMATCH_FAILURE))).toBe(+ `The scope "${scope}" belongs to another API, so a token for it must not be sent to this server. Remove it or use this server's own scope.`+ )+ })++ it('maps scope_audience_mismatch without a scope name', () => {+ const err = Object.assign(new Error('400'), {+ code: 'scope_audience_mismatch',+ body: { error: 'scope_audience_mismatch' },+ })+ expect(mapRemoteInstallError(err)).toMatch(/^A scope belongs to another API/)+ })++ it('maps scope_audience_missing to "add this server\'s own scope"', () => {+ expect(mapRemoteInstallError(apiErrorFrom(SCOPE_AUDIENCE_MISSING_FAILURE))).toBe(+ 'Add this server’s own scope. Sign-in scopes alone (openid, profile, email, offline_access) would send a Microsoft Graph token to the server.'+ )+ })++ it('maps a scope_audience_unverified answer with no usable list to review copy', () => {+ const err = Object.assign(new Error('400'), {+ code: 'scope_audience_unverified',+ body: { error: 'scope_audience_unverified' },+ })+ expect(mapRemoteInstallError(err)).toMatch(/cannot tie to the server/)+ })++ it('shows the server message of an invalid_request, else the reload hint', () => {+ expect(mapRemoteInstallError(apiErrorFrom(SCOPE_LIMIT_EXCEEDED_FAILURE))).toBe(+ (SCOPE_LIMIT_EXCEEDED_FAILURE.body as { message: string }).message+ )+ const bare = Object.assign(new Error('400'), {+ code: 'invalid_request',+ body: { error: 'invalid_request', detail: [] },+ })+ expect(mapRemoteInstallError(bare)).toBe(+ 'The install request was rejected as invalid. Reload the page and try again.'+ )+ })+it('maps a re-run discovery_failed at install', () => {const err = Object.assign(new Error('400'), {code: 'discovery_failed',diff --git a/control-ui/lib/remoteMcp.ts b/control-ui/lib/remoteMcp.tsindex 6e41c139b..165b090fd 100644--- a/control-ui/lib/remoteMcp.ts+++ b/control-ui/lib/remoteMcp.ts@@ -16,6 +16,7 @@ import type {RemoteDiscoveryErrorKind,RemoteInstallMode,RemoteRegistrationMode,+ RemoteTenantRequiredDetail,RemoteTransportProbe,} from './remoteMcp.types'@@ -28,10 +29,16 @@ export const REMOTE_MCP_BASE = '/api/v1/admin/mcp-servers/remote'* Dry-run discovery for `baseUrl`. Resolves to the full discover response — the* `detected` OAuth prefill plus the optional MCP `transport` probe — or throws* the `apiSend` error (whose `.code`/`.body` carry the discovery-error detail).+ * `authorizationServer` is the Entra tenant authority, sent only after a+ * `tenant_required` answer.*/-export async function discoverRemoteServer(baseUrl: string): Promise<DiscoverRemoteResponse> {+export async function discoverRemoteServer(+ baseUrl: string,+ authorizationServer?: string+): Promise<DiscoverRemoteResponse> {return (await apiSend('POST', `${REMOTE_MCP_BASE}/discover`, {baseUrl,+ ...(authorizationServer ? { authorizationServer } : {}),})) as DiscoverRemoteResponse}@@ -224,6 +231,92 @@ export function getRemoteBaseUrlError(raw: string): string {return ''}+// RFC 6749 §3.3 scope-token. Commas are legal inside a scope, so — unlike the generic+// lane's parser — remote scopes split on whitespace only.+const SCOPE_TOKEN_RE = /^[\x21\x23-\x5B\x5D-\x7E]+$/+const ENTRA_TENANT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i++/**+ * Validate the operator-typed Microsoft Entra tenant ID. Only the GUID form works:+ * Entra reports the issuer with the GUID, so a domain name could never match it.+ */+export function getEntraTenantIdError(raw: string): string {+ const value = raw.trim()+ if (!value) return 'Tenant ID is required.'+ if (!ENTRA_TENANT_ID_RE.test(value)) {+ return 'Enter the tenant ID as a GUID (Directory (tenant) ID in the Microsoft Entra admin center), not a domain name.'+ }+ return ''+}++/**+ * Fill the backend's tenant authority template. control-api accepts only the lower-case+ * GUID, so the tenant is normalised here.+ */+export function tenantAuthority(template: string, tenantId: string): string {+ return template.split('{tenantId}').join(tenantId.trim().toLowerCase())+}++/**+ * Parse the space-separated scopes field. An empty field yields no scopes, which the+ * wizard reads as "use the scopes the server advertises".+ */+export function parseRemoteScopesInput(+ raw: string,+ maxScopes: number+): { scopes: string[] } | { error: string } {+ const scopes = [...new Set(raw.split(/\s+/).filter(Boolean))]+ const invalid = scopes.find(scope => !SCOPE_TOKEN_RE.test(scope))+ if (invalid !== undefined) {+ return { error: `Scope "${invalid}" contains characters OAuth does not allow.` }+ }+ if (scopes.length > maxScopes) return { error: `At most ${maxScopes} scopes.` }+ return { scopes }+}++/** The scopes to send on install: undefined when the input is empty or equals the detected list (same order). */+export function remoteScopesOverride(parsed: string[], detected: string[]): string[] | undefined {+ if (parsed.length === 0) return undefined+ const same =+ parsed.length === detected.length && parsed.every((scope, i) => scope === detected[i])+ return same ? undefined : parsed+}++/**+ * The `tenant_required` detail of a discover failure, or null for any other error. The+ * wizard answers it with the tenant prompt instead of an error banner.+ */+export function tenantRequiredDetail(error: unknown): RemoteTenantRequiredDetail | null {+ const e = asCodedError(error)+ if (e.code !== 'discovery_failed') return null+ const detail = e.body?.detail+ if (!detail || typeof detail !== 'object') return null+ const d = detail as Record<string, unknown>+ if (+ d.kind !== 'tenant_required' ||+ typeof d.authorizationServer !== 'string' ||+ typeof d.tenantAuthorityTemplate !== 'string'+ ) {+ return null+ }+ return {+ kind: 'tenant_required',+ authorizationServer: d.authorizationServer,+ tenantAuthorityTemplate: d.tenantAuthorityTemplate,+ detail: typeof d.detail === 'string' ? d.detail : '',+ }+}++/** `scopes` of a 400 scope_audience_unverified install error (strings only), or null for any other error. */+export function unverifiedScopesFromInstallError(error: unknown): string[] | null {+ const e = asCodedError(error)+ if (e.code !== 'scope_audience_unverified') return null+ const scopes = e.body?.scopes+ if (!Array.isArray(scopes)) return null+ const strings = scopes.filter((scope): scope is string => typeof scope === 'string')+ return strings.length > 0 ? strings : null+}+// ── Error mapping to human-readable UI text ──────────────────────────────────type CodedError = {@@ -266,6 +359,10 @@ export function describeDiscoveryError(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."+ case 'tenant_required':+ return "This server signs in with Microsoft Entra ID through a multi-tenant authority. Enter your organization's tenant ID to continue."+ case 'authorization_server_override_rejected':+ return "This server doesn't accept a Microsoft Entra tenant sign-in address. Check the server URL."default:return 'OAuth discovery failed for this server.'}@@ -303,7 +400,25 @@ function detailString(return undefined}+const ENTRA_LOGIN_ORIGIN = 'https://login.microsoftonline.com/'++/** Entra answers the metadata of a tenant it does not know with a 400. */+function isUnknownEntraTenant(body: Record<string, unknown> | undefined): boolean {+ const detail = body?.detail+ if (!detail || typeof detail !== 'object') return false+ const d = detail as Record<string, unknown>+ return (+ d.kind === 'fetch_failed' &&+ d.status === 400 &&+ typeof d.url === 'string' &&+ d.url.startsWith(ENTRA_LOGIN_ORIGIN)+ )+}+function describeDiscoveryFailure(body: Record<string, unknown> | undefined): string {+ if (isUnknownEntraTenant(body)) {+ return 'Microsoft Entra ID did not recognize this tenant ID. Check the Directory (tenant) ID and try again.'+ }return describeDiscoveryError(discoveryDetailKind(body), detailString(body, 'field'))}@@ -348,6 +463,9 @@ export function mapRemoteDiscoverError(error: unknown): string {if (e.code === 'discovery_failed') {return describeDiscoveryFailure(e.body)}+ if (e.code === 'invalid_request') {+ return 'The request was rejected as invalid. Reload the page and try again.'+ }// 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.'@@ -400,7 +518,24 @@ export function mapRemoteInstallError(// reappears here with the same detail kind.return describeDiscoveryFailure(body)case 'invalid_request':- return 'The install request was rejected as invalid. Reload the page and try again.'+ // Set when the request is well formed but the server refuses it (e.g. a required+ // field for this authorization server, or the scope limit).+ return (+ serverMessage ||+ 'The install request was rejected as invalid. Reload the page and try again.'+ )+ case 'scope_audience_mismatch': {+ const scope = typeof body?.scope === 'string' ? body.scope : ''+ return scope+ ? `The scope "${scope}" belongs to another API, so a token for it must not be sent to this server. Remove it or use this server's own scope.`+ : "A scope belongs to another API, so a token for it must not be sent to this server. Remove it or use this server's own scope."+ }+ case 'scope_audience_missing':+ return 'Add this server’s own scope. Sign-in scopes alone (openid, profile, email, offline_access) would send a Microsoft Graph token to the server.'+ case 'scope_audience_unverified':+ // A well-formed answer is turned into the confirmation by the wizard; this copy+ // only covers a body without a usable scope list.+ return 'Some scopes name an API this platform cannot tie to the server. Review the scopes and try again.'case 'transport_unreachable': {// The MCP transport probe found the typed path dead before any write.const detail =@@ -438,6 +573,9 @@ export function buildRemoteInstallRequest(input: {grantScope: RemoteGrantScopeInputclientId?: stringclientSecret?: string+ authorizationServer?: string+ scopes?: string[]+ confirmedUnverifiedScopes?: string[]}): InstallRemoteRequest {const body: InstallRemoteRequest = {serverName: input.serverName.trim(),@@ -450,6 +588,11 @@ export function buildRemoteInstallRequest(input: {body.clientId = input.clientId?.trim()body.clientSecret = input.clientSecret}+ if (input.authorizationServer !== undefined) body.authorizationServer = input.authorizationServer+ if (input.scopes !== undefined) body.scopes = input.scopes+ if (input.confirmedUnverifiedScopes && input.confirmedUnverifiedScopes.length > 0) {+ body.confirmedUnverifiedScopes = input.confirmedUnverifiedScopes+ }return body}diff --git a/control-ui/lib/remoteMcp.types.ts b/control-ui/lib/remoteMcp.types.tsindex 1bf4ad5b6..73078d8b1 100644--- a/control-ui/lib/remoteMcp.types.ts+++ b/control-ui/lib/remoteMcp.types.ts@@ -55,6 +55,13 @@ export interface RemoteDetectedQuirks {supportsRefresh: boolean}+/**+ * Closed authorization-server profile control-api recognised from the pinned issuer.+ * `entra-v2` (a Microsoft Entra ID tenant): RFC 8707 `resource` is not sent and+ * `offline_access` is always requested.+ */+export type RemoteAsProfile = 'entra-v2'+/** The `detected` prefill returned by POST /discover (200). */export interface RemoteDetected {registrationMode: RemoteDiscoverRegistrationMode@@ -63,6 +70,13 @@ export interface RemoteDetected {resource: stringissuer: stringissForCallback?: string+ asProfile?: RemoteAsProfile+ /** First advertised scope that would mint a token for another API (warning only). */+ scopeAudienceViolation?: string+ /** Advertised scopes whose API cannot be tied to the server; the install needs them confirmed. */+ unverifiedScopes?: string[]+ /** The advertised scopes name no resource of the server (sign-in scopes only). */+ scopeAudienceMissing?: trueasEndpointHosts?: RemoteAsEndpointHostsscopes: string[]quirks: RemoteDetectedQuirks@@ -92,6 +106,8 @@ export interface RemoteCallbackPreview {export interface DiscoverRemoteRequest {baseUrl: string+ /** A Microsoft Entra ID tenant authority, sent only after a `tenant_required` answer. */+ authorizationServer?: string}/**@@ -146,6 +162,12 @@ export interface InstallRemoteRequest {/** Pre-registered confidential only (sensitive). */clientSecret?: stringgrantScope?: RemoteGrantScope+ /** The authorization server the detection used (the Entra tenant authority). */+ authorizationServer?: string+ /** Full override of the requested scopes; absent means the advertised ones. */+ scopes?: string[]+ /** The exact unverifiable scopes the operator confirmed as this server's API. */+ confirmedUnverifiedScopes?: string[]}export interface InstallRemoteResponse {@@ -201,3 +223,17 @@ export type RemoteDiscoveryErrorKind =| 'prm_resource_mismatch'| 'issuer_mismatch'| 'as_endpoints_cross_site'+ | 'tenant_required'+ | 'authorization_server_override_rejected'++/**+ * Detail of the `tenant_required` discovery error: the server signs in through Microsoft+ * Entra ID's multi-tenant authority, so the operator must name the tenant.+ * `tenantAuthorityTemplate` carries a literal `{tenantId}` placeholder.+ */+export interface RemoteTenantRequiredDetail {+ kind: 'tenant_required'+ authorizationServer: string+ tenantAuthorityTemplate: string+ detail: string+}diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 15c63a871..c8e6c55d0 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.735",+ "version": "0.1.736","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.735",+ "version": "0.1.736","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.jsonindex aedbdfe14..e0dec5632 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.735",+ "version": "0.1.736","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/control-ui/test/fixtures/__tests__/remoteMcpDiscovery.projection.test.ts b/control-ui/test/fixtures/__tests__/remoteMcpDiscovery.projection.test.tsindex d197c54d7..6eb9226e1 100644--- a/control-ui/test/fixtures/__tests__/remoteMcpDiscovery.projection.test.ts+++ b/control-ui/test/fixtures/__tests__/remoteMcpDiscovery.projection.test.ts@@ -15,6 +15,7 @@ import {LINEAR_DISCOVER,NOTION_DISCOVER,PRE_REGISTERED_PER_SERVER_DISCOVER,+ WORKIQ_DISCOVER,} from '../remoteMcpWire'/**@@ -33,6 +34,10 @@ describe('remote MCP `/discover` goldens carry the callback contract the wizardexpect(NOTION_DISCOVER.callback?.variant).toBe('per-server')expect(ATLASSIAN_DISCOVER.detected.registrationMode).toBe('dcr')expect(PRE_REGISTERED_PER_SERVER_DISCOVER.detected.registrationMode).toBe('manual')+ // Entra offers neither CIMD nor DCR; its tenant issuer carries the entra-v2 profile.+ expect(WORKIQ_DISCOVER.detected.registrationMode).toBe('manual')+ expect(WORKIQ_DISCOVER.detected.asProfile).toBe('entra-v2')+ expect(WORKIQ_DISCOVER.detected.quirks.supportsRefresh).toBe(true)})for (const { name, body } of ALL_DISCOVER_BODIES) {diff --git a/control-ui/test/fixtures/remoteMcpWire.ts b/control-ui/test/fixtures/remoteMcpWire.tsindex 0d797d5d8..663ded2c5 100644--- a/control-ui/test/fixtures/remoteMcpWire.ts+++ b/control-ui/test/fixtures/remoteMcpWire.ts@@ -51,6 +51,16 @@ export const PRE_REGISTERED_PER_SERVER_DISCOVER = loadGolden<DiscoverRemoteRespo'discover.preRegisteredPerServer').body+/** Work IQ with the Entra tenant authority: entra-v2 profile, pre-registered, per-server. */+export const WORKIQ_DISCOVER = loadGolden<DiscoverRemoteResponse>('discover.workiq').body+/** Work IQ whose PRM advertises an unknown GUID-form scope: the install needs it confirmed. */+export const ENTRA_UNKNOWN_GUID_DISCOVER = loadGolden<DiscoverRemoteResponse>(+ 'discover.entraUnknownGuid'+).body+/** Work IQ whose PRM advertises no scopes: only sign-in scopes are left (scopeAudienceMissing). */+export const ENTRA_NO_SCOPES_DISCOVER =+ loadGolden<DiscoverRemoteResponse>('discover.entraNoScopes').body+export const ALL_DISCOVER_BODIES: ReadonlyArray<{ name: string; body: DiscoverRemoteResponse }> = [{ name: 'linear', body: LINEAR_DISCOVER },{ name: 'notion', body: NOTION_DISCOVER },@@ -59,6 +69,7 @@ export const ALL_DISCOVER_BODIES: ReadonlyArray<{ name: string; body: DiscoverRe{ name: 'linear-unconfigured', body: LINEAR_DISCOVER_UNCONFIGURED },{ name: 'dcr-confidential', body: DCR_CONFIDENTIAL_DISCOVER },{ name: 'pre-registered-per-server', body: PRE_REGISTERED_PER_SERVER_DISCOVER },+ { name: 'workiq', body: WORKIQ_DISCOVER },]// ─── /discover from a control-api older than the per-server callback ─────────@@ -105,6 +116,8 @@ export const PRE_REGISTERED_PER_SERVER_INSTALLED = loadGolden<InstallRemoteRespoexport const PRE_REGISTERED_SHARED_INSTALLED = loadGolden<InstallRemoteResponse>('install.preRegisteredShared').body+/** Work IQ, pre-registered on its per-server callback, with the Entra tenant authority. */+export const WORKIQ_INSTALLED = loadGolden<InstallRemoteResponse>('install.workiq').body// ─── errors ───────────────────────────────────────────────────────────────────@@ -116,6 +129,15 @@ export const CLIENT_ID_IN_USE_FAILURE = loadGolden('install.clientIdInUse')export const DCR_REDIRECT_MISMATCH_FAILURE = loadGolden('install.dcrRedirectMismatch')export const CIMD_WITHOUT_ISS_BINDING_FAILURE = loadGolden('install.cimdWithoutIssBinding')export const CALLBACK_UNCONFIGURED_FAILURE = loadGolden('install.callbackUnconfigured')+/** Work IQ discovered without a tenant: the PRM names Entra's multi-tenant authority. */+export const WORKIQ_DISCOVER_TENANT_REQUIRED = loadGolden('discover.workiqTenantRequired')+/** A tenant Entra does not know: its metadata answers 400, surfaced as a 424. */+export const ENTRA_UNKNOWN_TENANT_DISCOVER_FAILURE = loadGolden('discover.entraUnknownTenant')+export const SCOPE_AUDIENCE_UNVERIFIED_FAILURE = loadGolden('install.scopeAudienceUnverified')+export const SCOPE_AUDIENCE_MISMATCH_FAILURE = loadGolden('install.scopeAudienceMismatch')+export const SCOPE_AUDIENCE_MISSING_FAILURE = loadGolden('install.scopeAudienceMissing')+/** 128 scopes plus the offline_access the Entra profile adds: over the CRD limit. */+export const SCOPE_LIMIT_EXCEEDED_FAILURE = loadGolden('install.scopeLimitExceeded')/*** The error `apiSend` throws for a captured failure: the real `formatApiError` over