Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-ui): per-server redirect URI and AS hosts in the remote wizard
Diego Zacarias7018b04e896c
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 3562756f7..f5f8c5188 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.682",+ "version": "0.1.683","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.682",+ "version": "0.1.683","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex 08002c0c1..63e3b2241 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.682",+ "version": "0.1.683","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/test/fixtures/wire/remoteMcp.discover.atlassian.json b/control-api/test/fixtures/wire/remoteMcp.discover.atlassian.jsonnew file mode 100644index 000000000..111aefbdd--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.discover.atlassian.json@@ -0,0 +1,80 @@+{+ "status": 200,+ "body": {+ "transport": {+ "status": "alive",+ "probedUrl": "https://mcp.atlassian.com/v2/mcp",+ "httpStatus": 401,+ "challenge": true+ },+ "callback": {+ "configured": true,+ "variant": "per-server",+ "redirectUriTemplate": "https://control.example.com/api/v1/oauth-callback/remote/{serverName}/{installId}"+ },+ "detected": {+ "registrationMode": "dcr",+ "dcr": {+ "available": true,+ "clientMode": "public",+ "supportsRefresh": true+ },+ "endpoints": {+ "authorization": "https://auth.atlassian.com/authorize",+ "token": "https://auth.atlassian.com/oauth/token",+ "registration": "https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3/dcr/register"+ },+ "resource": "https://mcp.atlassian.com/v2/mcp",+ "issuer": "https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3",+ "asEndpointHosts": {+ "authorization": "auth.atlassian.com",+ "token": "auth.atlassian.com",+ "registration": "auth.atlassian.com"+ },+ "scopes": [+ "read:me",+ "read:account",+ "offline_access",+ "email",+ "read:jira:agent-interface",+ "write:jira:agent-interface",+ "search:jira:agent-interface",+ "delete:jira:agent-interface",+ "manage:jira:agent-interface",+ "read:confluence:agent-interface",+ "write:confluence:agent-interface",+ "search:confluence:agent-interface",+ "search:rovo:agent-interface",+ "search:code:agent-interface",+ "read:all:twg",+ "write:all:twg",+ "read:goals:agent-interface",+ "write:goals:agent-interface",+ "read:projects:agent-interface",+ "write:projects:agent-interface",+ "read:bitbucket:agent-interface",+ "write:bitbucket:agent-interface",+ "read:loom:agent-interface",+ "write:loom:agent-interface",+ "read:talent:agent-interface",+ "write:talent:agent-interface",+ "read:jira-align:agent-interface",+ "write:jira-align:agent-interface",+ "read:teams:agent-interface",+ "write:teams:agent-interface",+ "read:artifacts:agent-interface",+ "write:artifacts:agent-interface",+ "read:capacity-planning:agent-interface",+ "write:capacity-planning:agent-interface",+ "read:focus:agent-interface",+ "write:focus:agent-interface",+ "read:assets:agent-interface",+ "write:assets:agent-interface"+ ],+ "quirks": {+ "bearerInBody": false,+ "supportsRefresh": true+ }+ }+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.discover.atlassianUnconfigured.json b/control-api/test/fixtures/wire/remoteMcp.discover.atlassianUnconfigured.jsonnew file mode 100644index 000000000..e44d70b78--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.discover.atlassianUnconfigured.json@@ -0,0 +1,79 @@+{+ "status": 200,+ "body": {+ "transport": {+ "status": "alive",+ "probedUrl": "https://mcp.atlassian.com/v2/mcp",+ "httpStatus": 401,+ "challenge": true+ },+ "callback": {+ "configured": false,+ "variant": "per-server"+ },+ "detected": {+ "registrationMode": "dcr",+ "dcr": {+ "available": true,+ "clientMode": "public",+ "supportsRefresh": true+ },+ "endpoints": {+ "authorization": "https://auth.atlassian.com/authorize",+ "token": "https://auth.atlassian.com/oauth/token",+ "registration": "https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3/dcr/register"+ },+ "resource": "https://mcp.atlassian.com/v2/mcp",+ "issuer": "https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3",+ "asEndpointHosts": {+ "authorization": "auth.atlassian.com",+ "token": "auth.atlassian.com",+ "registration": "auth.atlassian.com"+ },+ "scopes": [+ "read:me",+ "read:account",+ "offline_access",+ "email",+ "read:jira:agent-interface",+ "write:jira:agent-interface",+ "search:jira:agent-interface",+ "delete:jira:agent-interface",+ "manage:jira:agent-interface",+ "read:confluence:agent-interface",+ "write:confluence:agent-interface",+ "search:confluence:agent-interface",+ "search:rovo:agent-interface",+ "search:code:agent-interface",+ "read:all:twg",+ "write:all:twg",+ "read:goals:agent-interface",+ "write:goals:agent-interface",+ "read:projects:agent-interface",+ "write:projects:agent-interface",+ "read:bitbucket:agent-interface",+ "write:bitbucket:agent-interface",+ "read:loom:agent-interface",+ "write:loom:agent-interface",+ "read:talent:agent-interface",+ "write:talent:agent-interface",+ "read:jira-align:agent-interface",+ "write:jira-align:agent-interface",+ "read:teams:agent-interface",+ "write:teams:agent-interface",+ "read:artifacts:agent-interface",+ "write:artifacts:agent-interface",+ "read:capacity-planning:agent-interface",+ "write:capacity-planning:agent-interface",+ "read:focus:agent-interface",+ "write:focus:agent-interface",+ "read:assets:agent-interface",+ "write:assets:agent-interface"+ ],+ "quirks": {+ "bearerInBody": false,+ "supportsRefresh": true+ }+ }+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.discover.dcrConfidential.json b/control-api/test/fixtures/wire/remoteMcp.discover.dcrConfidential.jsonnew file mode 100644index 000000000..ee5dd865c--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.discover.dcrConfidential.json@@ -0,0 +1,41 @@+{+ "status": 200,+ "body": {+ "transport": {+ "status": "alive",+ "probedUrl": "https://mcp.notion.com/mcp",+ "httpStatus": 401,+ "challenge": true+ },+ "callback": {+ "configured": true,+ "variant": "per-server",+ "redirectUriTemplate": "https://control.example.com/api/v1/oauth-callback/remote/{serverName}/{installId}"+ },+ "detected": {+ "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",+ "asEndpointHosts": {+ "authorization": "mcp.notion.com",+ "token": "mcp.notion.com",+ "registration": "mcp.notion.com"+ },+ "scopes": ["default"],+ "quirks": {+ "bearerInBody": false,+ "supportsRefresh": true+ }+ }+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.discover.dropbox.json b/control-api/test/fixtures/wire/remoteMcp.discover.dropbox.jsonnew file mode 100644index 000000000..bd95adc92--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.discover.dropbox.json@@ -0,0 +1,11 @@+{+ "status": 400,+ "body": {+ "error": "discovery_failed",+ "detail": {+ "kind": "as_endpoints_cross_site",+ "field": "token",+ "detail": "token endpoint is on site \"dropboxapi.com\", issuer is on site \"dropbox.com\""+ }+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.discover.issuerPublicSuffix.json b/control-api/test/fixtures/wire/remoteMcp.discover.issuerPublicSuffix.jsonnew file mode 100644index 000000000..bab9656c8--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.discover.issuerPublicSuffix.json@@ -0,0 +1,11 @@+{+ "status": 400,+ "body": {+ "error": "discovery_failed",+ "detail": {+ "kind": "as_endpoints_cross_site",+ "field": "issuer",+ "detail": "issuer has no registrable domain (public suffix, IP literal, userinfo or invalid URL)"+ }+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.discover.linear.json b/control-api/test/fixtures/wire/remoteMcp.discover.linear.jsonnew file mode 100644index 000000000..1a76791ba--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.discover.linear.json@@ -0,0 +1,32 @@+{+ "status": 200,+ "body": {+ "transport": {+ "status": "alive",+ "probedUrl": "https://mcp.linear.app/mcp",+ "httpStatus": 401,+ "challenge": true+ },+ "callback": {+ "configured": true,+ "variant": "shared",+ "redirectUriTemplate": "https://control.example.com/api/v1/oauth-callback/remote"+ },+ "detected": {+ "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",+ "issForCallback": "https://mcp.linear.app",+ "scopes": ["read", "write"],+ "quirks": {+ "bearerInBody": false,+ "supportsRefresh": true+ }+ }+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.discover.linearUnconfigured.json b/control-api/test/fixtures/wire/remoteMcp.discover.linearUnconfigured.jsonnew file mode 100644index 000000000..f38b0482a--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.discover.linearUnconfigured.json@@ -0,0 +1,31 @@+{+ "status": 200,+ "body": {+ "transport": {+ "status": "alive",+ "probedUrl": "https://mcp.linear.app/mcp",+ "httpStatus": 401,+ "challenge": true+ },+ "callback": {+ "configured": false,+ "variant": "shared"+ },+ "detected": {+ "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",+ "issForCallback": "https://mcp.linear.app",+ "scopes": ["read", "write"],+ "quirks": {+ "bearerInBody": false,+ "supportsRefresh": true+ }+ }+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.discover.notion.json b/control-api/test/fixtures/wire/remoteMcp.discover.notion.jsonnew file mode 100644index 000000000..02fa41836--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.discover.notion.json@@ -0,0 +1,41 @@+{+ "status": 200,+ "body": {+ "transport": {+ "status": "alive",+ "probedUrl": "https://mcp.notion.com/mcp",+ "httpStatus": 401,+ "challenge": true+ },+ "callback": {+ "configured": true,+ "variant": "per-server",+ "redirectUriTemplate": "https://control.example.com/api/v1/oauth-callback/remote/{serverName}/{installId}"+ },+ "detected": {+ "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",+ "asEndpointHosts": {+ "authorization": "mcp.notion.com",+ "token": "mcp.notion.com",+ "registration": "mcp.notion.com"+ },+ "scopes": ["default"],+ "quirks": {+ "bearerInBody": false,+ "supportsRefresh": true+ }+ }+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.discover.preRegisteredPerServer.json b/control-api/test/fixtures/wire/remoteMcp.discover.preRegisteredPerServer.jsonnew file mode 100644index 000000000..febe1cff2--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.discover.preRegisteredPerServer.json@@ -0,0 +1,34 @@+{+ "status": 200,+ "body": {+ "transport": {+ "status": "alive",+ "probedUrl": "https://mcp.linear.app/mcp",+ "httpStatus": 401,+ "challenge": true+ },+ "callback": {+ "configured": true,+ "variant": "per-server",+ "redirectUriTemplate": "https://control.example.com/api/v1/oauth-callback/remote/{serverName}"+ },+ "detected": {+ "registrationMode": "manual",+ "endpoints": {+ "authorization": "https://mcp.linear.app/authorize",+ "token": "https://mcp.linear.app/token"+ },+ "resource": "https://mcp.linear.app/mcp",+ "issuer": "https://mcp.linear.app",+ "asEndpointHosts": {+ "authorization": "mcp.linear.app",+ "token": "mcp.linear.app"+ },+ "scopes": ["read", "write"],+ "quirks": {+ "bearerInBody": false,+ "supportsRefresh": true+ }+ }+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.install.atlassian.json b/control-api/test/fixtures/wire/remoteMcp.install.atlassian.jsonnew file mode 100644index 000000000..1fcb8c33f--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.install.atlassian.json@@ -0,0 +1,13 @@+{+ "status": 201,+ "body": {+ "serverName": "atlassian",+ "namespace": "mcp-server",+ "contextRef": "research",+ "contextUpdated": true,+ "clientMode": "public",+ "registrationMode": "dcr",+ "callbackVariant": "per-server",+ "redirectUri": "https://control.example.com/api/v1/oauth-callback/remote/atlassian/5b0f3c2e-8d1a-4c6f-9e2b-7a4d1f0c9e31"+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.install.callbackUnconfigured.json b/control-api/test/fixtures/wire/remoteMcp.install.callbackUnconfigured.jsonnew file mode 100644index 000000000..2d03d344d--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.install.callbackUnconfigured.json@@ -0,0 +1,6 @@+{+ "status": 503,+ "body": {+ "error": "callback_base_url_unconfigured"+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.install.cimdWithoutIssBinding.json b/control-api/test/fixtures/wire/remoteMcp.install.cimdWithoutIssBinding.jsonnew file mode 100644index 000000000..6a7f3e425--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.install.cimdWithoutIssBinding.json@@ -0,0 +1,7 @@+{+ "status": 400,+ "body": {+ "error": "mode_unsupported",+ "message": "this authorization server supports CIMD but not RFC 9207; install with mode \"dcr\""+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.install.clientIdInUse.json b/control-api/test/fixtures/wire/remoteMcp.install.clientIdInUse.jsonnew file mode 100644index 000000000..17f34deda--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.install.clientIdInUse.json@@ -0,0 +1,8 @@+{+ "status": 409,+ "body": {+ "error": "oauth_client_id_in_use",+ "conflict": "remote_server",+ "message": "this client_id already backs another client; register a separate OAuth client for this server"+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.install.dcrRedirectMismatch.json b/control-api/test/fixtures/wire/remoteMcp.install.dcrRedirectMismatch.jsonnew file mode 100644index 000000000..b64124a91--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.install.dcrRedirectMismatch.json@@ -0,0 +1,9 @@+{+ "status": 400,+ "body": {+ "error": "dcr_registration_failed",+ "detail": {+ "kind": "redirect_uris_mismatch"+ }+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.install.linear.json b/control-api/test/fixtures/wire/remoteMcp.install.linear.jsonnew file mode 100644index 000000000..7adfb916b--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.install.linear.json@@ -0,0 +1,13 @@+{+ "status": 201,+ "body": {+ "serverName": "linear",+ "namespace": "mcp-server",+ "contextRef": "research",+ "contextUpdated": true,+ "clientMode": "public",+ "registrationMode": "cimd",+ "callbackVariant": "shared",+ "redirectUri": "https://control.example.com/api/v1/oauth-callback/remote"+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.install.preRegisteredPerServer.json b/control-api/test/fixtures/wire/remoteMcp.install.preRegisteredPerServer.jsonnew file mode 100644index 000000000..4bb72a6d5--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.install.preRegisteredPerServer.json@@ -0,0 +1,14 @@+{+ "status": 201,+ "body": {+ "serverName": "linear-pre",+ "namespace": "mcp-server",+ "contextRef": "research",+ "contextUpdated": true,+ "clientMode": "confidential",+ "registrationMode": "pre-registered",+ "callbackVariant": "per-server",+ "redirectUri": "https://control.example.com/api/v1/oauth-callback/remote/linear-pre",+ "clientSecretName": "linear-pre-oauth-client"+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.install.preRegisteredShared.json b/control-api/test/fixtures/wire/remoteMcp.install.preRegisteredShared.jsonnew file mode 100644index 000000000..6bd0761c0--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.install.preRegisteredShared.json@@ -0,0 +1,14 @@+{+ "status": 201,+ "body": {+ "serverName": "linear-pre",+ "namespace": "mcp-server",+ "contextRef": "research",+ "contextUpdated": true,+ "clientMode": "confidential",+ "registrationMode": "pre-registered",+ "callbackVariant": "shared",+ "redirectUri": "https://control.example.com/api/v1/oauth-callback/remote",+ "clientSecretName": "linear-pre-oauth-client"+ }+}diff --git a/control-api/test/routes.adminRemoteMcp.wireGoldens.test.ts b/control-api/test/routes.adminRemoteMcp.wireGoldens.test.tsnew file mode 100644index 000000000..d0e0c0192--- /dev/null+++ b/control-api/test/routes.adminRemoteMcp.wireGoldens.test.ts@@ -0,0 +1,325 @@+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import express from 'express'+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import request from 'supertest'+import { config } from '../src/config.js'+import type { PinnedTransport } from '../src/http/pinnedFetch.js'+import type { K8sGateway } from '../src/k8s.js'+import { discoverRemoteOAuth } from '../src/oauth/discovery.js'+import { probeMcpTransport } from '../src/oauth/mcpTransportProbe.js'+import {+ type AdminRemoteMcpDeps,+ createAdminRemoteMcpRouter,+} from '../src/routes/admin/remoteMcp.js'+import {+ ATLASSIAN_V2_PILOT,+ DCR_PUBLIC_REGISTRATION_RESPONSE,+ DROPBOX_PILOT,+ PILOTS,+ type PilotFixture,+ dcrPilot,+ makeDcrTransport,+ makeDiscoveryTransport,+ makeInMemoryDynamicClientsDb,+} from './fixtures/remoteOAuthDiscovery.js'+import { MockGateway } from './mockGateway.js'++/**+ * Golden wire bodies of the remote MCP admin routes (`/admin/mcp-servers/remote`),+ * consumed verbatim by control-ui's wizard tests (control-ui/test/fixtures/+ * remoteMcpWire.ts). control-ui cannot import control-api, so instead of retyping the+ * response shape there, every golden here is the body the real router returns: real+ * discovery and transport probe over the recorded probe bytes, the real install saga+ * over a MockGateway and the in-memory dynamic_clients harness.+ *+ * A producer change fails the equality below and forces the golden to move. To+ * regenerate after an intended change: `UPDATE_WIRE_GOLDENS=1 npx vitest run <this file>`,+ * `npx prettier --write test/fixtures/wire/remoteMcp.*.json`, then review the JSON diff.+ */++vi.mock('node:dns/promises', () => ({+ lookup: vi.fn(async () => [{ address: '93.184.216.34', family: 4 }]),+}))++// The install nonce is the only non-deterministic byte in these bodies (it ends the+// per-server DCR redirect URI); pinning it keeps the golden byte-stable.+const FIXED_INSTALL_ID = '5b0f3c2e-8d1a-4c6f-9e2b-7a4d1f0c9e31'+vi.mock('node:crypto', async importOriginal => {+ const actual = await importOriginal<typeof import('node:crypto')>()+ return { ...actual, randomUUID: () => FIXED_INSTALL_ID }+})++const ORIGIN = 'https://control.example.com'+const PUBLIC_IP = async () => ['93.184.216.34']+const UPDATE = process.env.UPDATE_WIRE_GOLDENS === '1'+const WIRE_DIR = new URL('./fixtures/wire/', import.meta.url)++type WireCapture = { status: number; body: unknown }++function golden(name: string, actual: WireCapture): WireCapture {+ const file = new URL(`remoteMcp.${name}.json`, WIRE_DIR)+ if (UPDATE) {+ mkdirSync(WIRE_DIR, { recursive: true })+ writeFileSync(file, `${JSON.stringify(actual, null, 2)}\n`)+ }+ return JSON.parse(readFileSync(file, 'utf8')) as WireCapture+}++/** Documented subtraction on the recorded AS bytes: drop the named metadata fields. */+function withoutAsFields(pilot: PilotFixture, fields: string[]): PilotFixture {+ const as = JSON.parse(pilot.as.json) as Record<string, unknown>+ for (const field of fields) delete as[field]+ return { ...pilot, name: `${pilot.name}-minus`, as: { ...pilot.as, json: JSON.stringify(as) } }+}++function appFor(+ pilot: PilotFixture,+ gateway: MockGateway,+ extra: Omit<AdminRemoteMcpDeps, 'discover' | 'probe'> = {}+) {+ const transport: PinnedTransport = makeDiscoveryTransport(pilot)+ const deps: AdminRemoteMcpDeps = {+ discover: (url, discoveryDeps, opts) =>+ discoverRemoteOAuth(url, { ...discoveryDeps, transport, resolveDns: PUBLIC_IP }, opts),+ probe: (baseUrl, probeDeps, opts) =>+ probeMcpTransport(baseUrl, { ...probeDeps, transport, resolveDns: PUBLIC_IP }, opts),+ ...extra,+ }+ const app = express()+ app.use(express.json())+ app.use(createAdminRemoteMcpRouter(gateway as unknown as K8sGateway, deps))+ return app+}++function gatewayWithContext(): MockGateway {+ const gw = new MockGateway(config.mcpServersNamespace)+ void gw.createResource(+ 'contexts',+ { metadata: { name: 'research' }, spec: { contextId: 'research' } },+ config.mcpServersNamespace+ )+ return gw+}++async function discover(pilot: PilotFixture): Promise<WireCapture> {+ const res = await request(appFor(pilot, gatewayWithContext()))+ .post('/admin/mcp-servers/remote/discover')+ .send({ baseUrl: pilot.mcpUrl })+ return { status: res.status, body: res.body }+}++async function install(+ pilot: PilotFixture,+ body: Record<string, unknown>,+ opts: { gateway?: MockGateway; deps?: Omit<AdminRemoteMcpDeps, 'discover' | 'probe'> } = {}+): Promise<WireCapture> {+ const res = await request(appFor(pilot, opts.gateway ?? gatewayWithContext(), opts.deps))+ .post('/admin/mcp-servers/remote')+ .send({ contextRef: 'research', baseUrl: pilot.mcpUrl, ...body })+ return { status: res.status, body: res.body }+}++// CIMD-only AS without RFC 9207 and without DCR: the operator must pre-register a client,+// on a per-server redirect URI. Real Linear bytes minus the two fields.+const PRE_REGISTERED_PER_SERVER_PILOT = withoutAsFields(PILOTS.linear, [+ 'registration_endpoint',+ 'authorization_response_iss_parameter_supported',+])+// The same AS with RFC 9207 but neither CIMD nor DCR: pre-registered on the shared+// callback. Paired with the case above it is what the wizard sees when the AS starts+// returning `iss` between discover and install.+const PRE_REGISTERED_SHARED_PILOT = withoutAsFields(PILOTS.linear, [+ 'registration_endpoint',+ 'client_id_metadata_document_supported',+])+// An AS whose issuer is itself a public suffix (a shared-hosting apex, here the PSL+// private entry `github.io`), so it has no registrable domain to anchor the same-site+// rule. Real Notion bytes (no RFC 9207) with the AS moved to that host: the PRM points+// its authorization server there and every AS metadata URL follows; the resource stays.+const ISSUER_ON_PUBLIC_SUFFIX_PILOT = ((): PilotFixture => {+ const moved = (json: string) => json.split('https://mcp.notion.com').join('https://github.io')+ return {+ ...PILOTS.notion,+ name: 'issuer-public-suffix',+ prm: {+ ...PILOTS.notion.prm,+ json: PILOTS.notion.prm.json.replace(+ '"authorization_servers":["https://mcp.notion.com"]',+ '"authorization_servers":["https://github.io"]'+ ),+ },+ as: {+ url: 'https://github.io/.well-known/oauth-authorization-server',+ json: moved(PILOTS.notion.as.json),+ },+ }+})()++const ATLASSIAN_REGISTRATION = JSON.parse(ATLASSIAN_V2_PILOT.as.json)+ .registration_endpoint as string++let savedCallbackBaseUrl: string+beforeAll(() => {+ savedCallbackBaseUrl = config.oauthCallbackBaseUrl+ config.oauthCallbackBaseUrl = ORIGIN+})+afterAll(() => {+ config.oauthCallbackBaseUrl = savedCallbackBaseUrl+})++describe('remote MCP wire goldens — POST /discover', () => {+ const CASES: Array<{ name: string; pilot: () => PilotFixture; status: number }> = [+ { name: 'discover.linear', pilot: () => PILOTS.linear, status: 200 },+ { name: 'discover.notion', pilot: () => PILOTS.notion, status: 200 },+ { name: 'discover.atlassian', pilot: () => ATLASSIAN_V2_PILOT, status: 200 },+ { name: 'discover.dcrConfidential', pilot: () => dcrPilot('confidential'), status: 200 },+ {+ name: 'discover.preRegisteredPerServer',+ pilot: () => PRE_REGISTERED_PER_SERVER_PILOT,+ status: 200,+ },+ { name: 'discover.dropbox', pilot: () => DROPBOX_PILOT, status: 400 },+ ]+ for (const c of CASES) {+ it(`${c.name} equals the router's response`, async () => {+ const actual = await discover(c.pilot())+ expect(actual.status).toBe(c.status)+ expect(actual).toEqual(golden(c.name, actual))+ })+ }++ const UNCONFIGURED_CASES: Array<{ name: string; pilot: () => PilotFixture }> = [+ { name: 'discover.atlassianUnconfigured', pilot: () => ATLASSIAN_V2_PILOT },+ { name: 'discover.linearUnconfigured', pilot: () => PILOTS.linear },+ ]+ for (const c of UNCONFIGURED_CASES) {+ it(`${c.name}: no callback base URL configured`, async () => {+ config.oauthCallbackBaseUrl = ''+ try {+ const actual = await discover(c.pilot())+ expect(actual.status).toBe(200)+ expect(actual).toEqual(golden(c.name, actual))+ } finally {+ config.oauthCallbackBaseUrl = ORIGIN+ }+ })+ }++ it('discover.issuerPublicSuffix: issuer on a public suffix, no RFC 9207 → 400', async () => {+ const actual = await discover(ISSUER_ON_PUBLIC_SUFFIX_PILOT)+ expect(actual.status).toBe(400)+ expect(actual).toEqual(golden('discover.issuerPublicSuffix', actual))+ })+})++describe('remote MCP wire goldens — POST / (install)', () => {+ it('install.atlassian: per-server DCR 201', async () => {+ const { db } = makeInMemoryDynamicClientsDb()+ const { transport } = makeDcrTransport({+ registrationEndpoint: ATLASSIAN_REGISTRATION,+ responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),+ redirectUris: 'requested',+ })+ const actual = await install(+ ATLASSIAN_V2_PILOT,+ { serverName: 'atlassian', mode: 'dcr' },+ { deps: { db, dcr: { transport, resolveDns: PUBLIC_IP } } }+ )+ expect(actual.status).toBe(201)+ expect(actual).toEqual(golden('install.atlassian', actual))+ })++ it('install.linear: shared CIMD 201', async () => {+ const actual = await install(PILOTS.linear, { serverName: 'linear', mode: 'cimd' })+ expect(actual.status).toBe(201)+ expect(actual).toEqual(golden('install.linear', actual))+ })++ it('install.preRegisteredPerServer: per-server pre-registered 201', async () => {+ const { db } = makeInMemoryDynamicClientsDb()+ const actual = await install(+ PRE_REGISTERED_PER_SERVER_PILOT,+ {+ serverName: 'linear-pre',+ mode: 'pre-registered',+ clientId: 'pre-registered-client',+ clientSecret: 'pre-registered-secret',+ },+ { deps: { db } }+ )+ expect(actual.status).toBe(201)+ expect(actual).toEqual(golden('install.preRegisteredPerServer', actual))+ })++ it('install.preRegisteredShared: shared pre-registered 201', async () => {+ const actual = await install(PRE_REGISTERED_SHARED_PILOT, {+ serverName: 'linear-pre',+ mode: 'pre-registered',+ clientId: 'pre-registered-client',+ clientSecret: 'pre-registered-secret',+ })+ expect(actual.status).toBe(201)+ expect(actual).toEqual(golden('install.preRegisteredShared', actual))+ })++ it('install.clientIdInUse: a second per-server server on the same client_id → 409', async () => {+ const { db } = makeInMemoryDynamicClientsDb()+ const gateway = gatewayWithContext()+ const body = {+ mode: 'pre-registered',+ clientId: 'shared-client',+ clientSecret: 'pre-registered-secret',+ }+ const first = await install(+ PRE_REGISTERED_PER_SERVER_PILOT,+ { ...body, serverName: 'first' },+ { gateway, deps: { db } }+ )+ expect(first.status).toBe(201)+ const actual = await install(+ PRE_REGISTERED_PER_SERVER_PILOT,+ { ...body, serverName: 'second' },+ { gateway, deps: { db } }+ )+ expect(actual.status).toBe(409)+ expect(actual).toEqual(golden('install.clientIdInUse', actual))+ })++ it('install.dcrRedirectMismatch: the AS registered another redirect URI → 400', async () => {+ const { db } = makeInMemoryDynamicClientsDb()+ const { transport } = makeDcrTransport({+ registrationEndpoint: ATLASSIAN_REGISTRATION,+ responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),+ redirectUris: [`${ORIGIN}/api/v1/oauth-callback/remote`],+ })+ const actual = await install(+ ATLASSIAN_V2_PILOT,+ { serverName: 'atlassian', mode: 'dcr' },+ { deps: { db, dcr: { transport, resolveDns: PUBLIC_IP } } }+ )+ expect(actual.status).toBe(400)+ expect(actual).toEqual(golden('install.dcrRedirectMismatch', actual))+ })++ it('install.cimdWithoutIssBinding: CIMD requested on an AS without RFC 9207 → 400', async () => {+ const actual = await install(PILOTS.notion, { serverName: 'notion', mode: 'cimd' })+ expect(actual.status).toBe(400)+ expect(actual).toEqual(golden('install.cimdWithoutIssBinding', actual))+ })++ it('install.callbackUnconfigured: per-server without a callback base URL → 503', async () => {+ config.oauthCallbackBaseUrl = ''+ try {+ const { db } = makeInMemoryDynamicClientsDb()+ const actual = await install(+ ATLASSIAN_V2_PILOT,+ { serverName: 'atlassian', mode: 'dcr' },+ { deps: { db } }+ )+ expect(actual.status).toBe(503)+ expect(actual).toEqual(golden('install.callbackUnconfigured', actual))+ } finally {+ config.oauthCallbackBaseUrl = ORIGIN+ }+ })+})diff --git a/control-ui/components/AddRemoteServerWizard/index.tsx b/control-ui/components/AddRemoteServerWizard/index.tsxindex 8d6ead4ec..9c9336c57 100644--- a/control-ui/components/AddRemoteServerWizard/index.tsx+++ b/control-ui/components/AddRemoteServerWizard/index.tsx@@ -4,9 +4,11 @@ import React, { useEffect, useMemo, useState } from 'react'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 { getContexts, isSilentApiError } from '@lib/api'import type { ContextResource } from '@lib/api'+import { copyTextToClipboard } from '@lib/clipboard'import { contextResourceName } from '@lib/contextIdentity'import {buildRemoteInstallRequest,@@ -19,11 +21,18 @@ import {installRemoteServer,mapRemoteDiscoverError,mapRemoteInstallError,+ remoteCallbackBlocker,+ remotePreRegisteredRedirectUri,requiresPreRegisteredCredentials,shouldWarnNoRefresh,transportBlocksContinue,} from '@lib/remoteMcp'-import type { RemoteDetected, RemoteGrantScope, RemoteTransportProbe } from '@lib/remoteMcp.types'+import type {+ RemoteCallbackPreview,+ RemoteDetected,+ RemoteGrantScope,+ RemoteTransportProbe,+} from '@lib/remoteMcp.types'import {GRANT_SCOPE_OPTIONS,REGISTRATION_MODE_HINT,@@ -31,7 +40,12 @@ import {REMOTE_WIZARD_STEPS,REMOTE_WIZARD_STEP_DETAILS,} from './constants'-import type { AddRemoteServerWizardProps } from './types'+import type {+ AddRemoteServerWizardProps,+ AsEndpointHostsSummaryProps,+ InstalledRedirectUri,+ RedirectUriCopyProps,+} from './types'const STEP_TITLE_ID = 'add-remote-server-step-title'@@ -60,6 +74,8 @@ export function AddRemoteServerWizard({// MCP transport probe result for the current URL. A `dead` probe clears// `detected` and holds the wizard on step 0; the others never block.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)// Step 1 — configurationconst [clientId, setClientId] = useState('')@@ -69,6 +85,9 @@ export function AddRemoteServerWizard({// Step 2 — installconst [installing, setInstalling] = useState(false)const [installError, setInstallError] = useState('')+ // 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)useEffect(() => {let cancelled = false@@ -105,11 +124,20 @@ export function AddRemoteServerWizard({const inconclusiveTransport = transport?.status === 'inconclusive' ? transport : nullconst aliveTransport = transport?.status === 'alive' ? transport : null+ const callbackBlocker = detected ? remoteCallbackBlocker({ detected, callback }) : ''+ const preRegisteredRedirectUri = needsCredentials+ ? remotePreRegisteredRedirectUri(callback, serverName)+ : null+ const asEndpointHosts = detected?.asEndpointHosts+const credentialsComplete =!needsCredentials || (clientId.trim().length > 0 && clientSecret.length > 0)- const step1Valid = Boolean(detected) && identifiersValid && credentialsComplete+ const step1Valid =+ Boolean(detected) && identifiersValid && credentialsComplete && callbackBlocker === ''function canSelectStep(target: number): boolean {+ // Once installed, going back would offer a second install of the same server.+ if (installed) return target === 2if (target === 0) return trueif (target === 1) return Boolean(detected) && identifiersValidreturn step1Valid@@ -127,16 +155,28 @@ export function AddRemoteServerWizard({function resetDetection() {setDetected(null)setTransport(null)+ setCallback(undefined)setDiscoverError('')}+ async function copyRedirectUri(uri: string) {+ const ok = await copyTextToClipboard(uri)+ showToast(ok ? 'Redirect URI copied.' : 'Copy failed — select and copy the URI manually.', {+ tone: ok ? 'success' : 'error',+ })+ }+async function runDetect() {setDetecting(true)setDiscoverError('')setTransport(null)+ setCallback(undefined)try {- const { detected: nextDetected, transport: nextTransport } =- await discoverRemoteServer(trimmedBaseUrl)+ const {+ detected: nextDetected,+ transport: nextTransport,+ callback: nextCallback,+ } = await discoverRemoteServer(trimmedBaseUrl)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@@ -147,6 +187,7 @@ export function AddRemoteServerWizard({}setDetected(nextDetected)setTransport(nextTransport ?? null)+ setCallback(nextCallback)setStep(1)} catch (e) {if (isSilentApiError(e)) return@@ -173,10 +214,18 @@ export function AddRemoteServerWizard({})const res = await installRemoteServer(body)showToast(`Remote server ${res.serverName} installed.`, { tone: 'success' })+ if (res.registrationMode === 'pre-registered' && res.redirectUri) {+ setInstalled({+ redirectUri: res.redirectUri,+ changedSincePreview:+ preRegisteredRedirectUri !== null && preRegisteredRedirectUri !== res.redirectUri,+ })+ return+ }onInstalled()} catch (e) {if (isSilentApiError(e)) return- setInstallError(mapRemoteInstallError(e))+ setInstallError(mapRemoteInstallError(e, { callbackVariant: callback?.variant }))} finally {setInstalling(false)}@@ -189,7 +238,7 @@ export function AddRemoteServerWizard({<formonSubmit={event => {event.preventDefault()- if (step === 2) void runInstall()+ if (step === 2 && !installed) void runInstall()}}><CreateStepFlow@@ -367,6 +416,25 @@ export function AddRemoteServerWizard({<p className="cu-field__hint">{REGISTRATION_MODE_HINT[detected.registrationMode]}</p>+ {callbackBlocker ? (+ <div className="cu-banner cu-banner--error" role="alert">+ {callbackBlocker}+ </div>+ ) : null}++ {asEndpointHosts ? (+ <AsEndpointHostsSummary hosts={asEndpointHosts} withExplanation />+ ) : null}++ {needsCredentials && preRegisteredRedirectUri ? (+ <Field+ label="Redirect URI"+ description="Register this exact URI in the provider’s OAuth client before users connect."+ >+ <RedirectUriCopy uri={preRegisteredRedirectUri} onCopy={copyRedirectUri} />+ </Field>+ ) : null}+{needsCredentials ? (<div className="cu-form-grid"><Field@@ -421,7 +489,25 @@ export function AddRemoteServerWizard({</div>) : null}- {step === 2 && detected && installMode ? (+ {step === 2 && installed ? (+ <div className="cu-form-stack cu-agent-form-stack">+ <p className="cu-field__hint">+ {serverName} is installed. Users can connect once this redirect URI is registered in+ the provider’s OAuth client.+ </p>+ {installed.changedSincePreview ? (+ <div className="cu-banner cu-banner--warning" role="status">+ The authorization server changed since detection, so this redirect URI differs+ from the one shown before. Register this one.+ </div>+ ) : null}+ <Field label="Redirect URI" description="Register this exact URI at the provider.">+ <RedirectUriCopy uri={installed.redirectUri} onCopy={copyRedirectUri} />+ </Field>+ </div>+ ) : null}++ {step === 2 && !installed && 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">@@ -456,8 +542,16 @@ export function AddRemoteServerWizard({<span>Token endpoint</span><strong>{detected.endpoints.token}</strong></div>+ {preRegisteredRedirectUri ? (+ <div className="cu-summary-list__row">+ <span>Redirect URI</span>+ <strong>{preRegisteredRedirectUri}</strong>+ </div>+ ) : null}</section>+ {asEndpointHosts ? <AsEndpointHostsSummary hosts={asEndpointHosts} /> : null}+{noRefresh ? (<div className="cu-banner cu-banner--warning" role="status">Reminder: this server does not support token refresh — users will re-authorize@@ -480,14 +574,21 @@ export function AddRemoteServerWizard({) : 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>+ {installed ? (+ <Button onClick={onInstalled} size="sm" variant="primary">+ Done+ </Button>+ ) : null}+ {installed ? null : (+ <Button+ disabled={detecting || installing}+ onClick={() => (step === 0 ? onCancel() : setStep(current => current - 1))}+ size="sm"+ variant="ghost"+ >+ {step === 0 ? 'Cancel' : 'Back'}+ </Button>+ )}{step === 0 ? (detected ? (@@ -518,7 +619,7 @@ export function AddRemoteServerWizard({</Button>) : null}- {step === 2 ? (+ {step === 2 && !installed ? (<Buttondisabled={!step1Valid || installing}loading={installing}@@ -535,3 +636,51 @@ export function AddRemoteServerWizard({</CreateFlowPanel>)}++function RedirectUriCopy({ uri, onCopy }: RedirectUriCopyProps) {+ return (+ <div className="cu-table-actions">+ <TextInput value={uri} readOnly monospace aria-label="Redirect URI" />+ <Button+ type="button"+ variant="ghost"+ size="sm"+ icon+ onClick={() => onCopy(uri)}+ aria-label="Copy redirect URI"+ >+ <IconCopy width={16} height={16} />+ </Button>+ </div>+ )+}++function AsEndpointHostsSummary({ hosts, withExplanation = false }: AsEndpointHostsSummaryProps) {+ return (+ <>+ {withExplanation ? (+ <div className="cu-banner cu-banner--info" role="note">+ This authorization server does not identify itself in its OAuth responses (RFC 9207), so+ the connector trusts these hosts because they share the issuer’s domain. Confirm they+ belong to the provider before installing.+ </div>+ ) : null}+ <section className="cu-summary-list" aria-label="Authorization server hosts">+ <div className="cu-summary-list__row">+ <span>Authorization host</span>+ <strong>{hosts.authorization}</strong>+ </div>+ <div className="cu-summary-list__row">+ <span>Token host</span>+ <strong>{hosts.token}</strong>+ </div>+ {hosts.registration ? (+ <div className="cu-summary-list__row">+ <span>Registration host</span>+ <strong>{hosts.registration}</strong>+ </div>+ ) : null}+ </section>+ </>+ )+}diff --git a/control-ui/components/AddRemoteServerWizard/types.ts b/control-ui/components/AddRemoteServerWizard/types.tsindex 9ec15e980..346b4951b 100644--- a/control-ui/components/AddRemoteServerWizard/types.ts+++ b/control-ui/components/AddRemoteServerWizard/types.ts@@ -1,5 +1,5 @@import type { ReactNode } from 'react'-import type { RemoteGrantScope } from '../../lib/remoteMcp.types'+import type { RemoteAsEndpointHosts, RemoteGrantScope } from '../../lib/remoteMcp.types'export type AddRemoteServerWizardProps = {/** Rendered create-page header (icon, title, back). */@@ -15,3 +15,22 @@ export type GrantScopeOption = {label: stringdescription: string}++/** A pre-registered install that succeeded; the wizard holds to show its redirect URI. */+export type InstalledRedirectUri = {+ /** The URI control-api reported in the 201 — authoritative over the preview. */+ redirectUri: string+ /** The 201 URI differs from the one previewed before install. */+ changedSincePreview: boolean+}++export type RedirectUriCopyProps = {+ uri: string+ onCopy: (uri: string) => void+}++export type AsEndpointHostsSummaryProps = {+ hosts: RemoteAsEndpointHosts+ /** Explain why the hosts are shown (the configuration step; the confirm step omits it). */+ withExplanation?: boolean+}diff --git a/control-ui/components/__tests__/AddRemoteServerWizard.test.tsx b/control-ui/components/__tests__/AddRemoteServerWizard.test.tsxindex 57d1132dd..e4c16333f 100644--- a/control-ui/components/__tests__/AddRemoteServerWizard.test.tsx+++ b/control-ui/components/__tests__/AddRemoteServerWizard.test.tsx@@ -2,19 +2,26 @@ 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 {- DiscoverRemoteResponse,- RemoteDetected,- RemoteTransportProbe,-} from '../../lib/remoteMcp.types'+import type { DiscoverRemoteResponse, RemoteTransportProbe } from '../../lib/remoteMcp.types'import { buildContextResource } from '../../test/fixtures/contextResource'import {- DCR_PUBLIC_DETECTED,- NOTION_DETECTED,- NOTION_TRANSPORT_ALIVE,TRANSPORT_INCONCLUSIVE_TIMEOUT,VERCEL_TRANSPORT_DEAD,} from '../../test/fixtures/remoteMcpDiscovery'+import {+ ATLASSIAN_DISCOVER,+ ATLASSIAN_DISCOVER_UNCONFIGURED,+ CALLBACK_UNCONFIGURED_FAILURE,+ LINEAR_DISCOVER,+ LINEAR_DISCOVER_UNCONFIGURED,+ LINEAR_INSTALLED,+ NOTION_DISCOVER,+ OLDER_CONTROL_API_DCR_DISCOVER,+ PRE_REGISTERED_PER_SERVER_DISCOVER,+ PRE_REGISTERED_PER_SERVER_INSTALLED,+ PRE_REGISTERED_SHARED_INSTALLED,+ apiErrorFrom,+} from '../../test/fixtures/remoteMcpWire'import { AddRemoteServerWizard } from '../AddRemoteServerWizard'import { ToastProvider } from '../Toast'@@ -42,12 +49,15 @@ const discoverMock = vi.mocked(remoteMcp.discoverRemoteServer)const installMock = vi.mocked(remoteMcp.installRemoteServer)const getContextsMock = vi.mocked(api.getContexts)-/** The discover response shape control-api returns: `detected` plus the probe. */+/**+ * A captured control-api discover body (goldens from the real router), optionally with+ * the transport probe swapped for another probe outcome of the same producer.+ */function discovered(- detected: RemoteDetected,+ body: DiscoverRemoteResponse,transport?: RemoteTransportProbe): DiscoverRemoteResponse {- return { detected, transport }+ return transport ? { ...body, transport } : body}afterEach(() => {@@ -92,7 +102,7 @@ function clickDetect() {describe('AddRemoteServerWizard', () => {it('detects a server and advances to the configuration step showing the detected values', async () => {- discoverMock.mockResolvedValue(discovered(NOTION_DETECTED))+ discoverMock.mockResolvedValue(discovered(NOTION_DISCOVER))renderWizard()await fillIdentity()clickDetect()@@ -107,7 +117,7 @@ describe('AddRemoteServerWizard', () => {})it('D-4: editing the URL after a detect invalidates it and blocks proceeding until re-detect', async () => {- discoverMock.mockResolvedValue(discovered(NOTION_DETECTED))+ discoverMock.mockResolvedValue(discovered(NOTION_DISCOVER))renderWizard()await fillIdentity()clickDetect()@@ -145,9 +155,7 @@ describe('AddRemoteServerWizard', () => {})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(discovered(manualDetected))+ discoverMock.mockResolvedValue(discovered(PRE_REGISTERED_PER_SERVER_DISCOVER))renderWizard()await fillIdentity()clickDetect()@@ -159,15 +167,15 @@ describe('AddRemoteServerWizard', () => {})it('does not show credential fields for cimd or dcr modes', async () => {- discoverMock.mockResolvedValue(discovered(NOTION_DETECTED)) // cimd+ discoverMock.mockResolvedValue(discovered(LINEAR_DISCOVER)) // cimdrenderWizard()- await fillIdentity()+ await fillIdentity('https://mcp.linear.app/mcp', 'linear')clickDetect()- await screen.findByText('https://mcp.notion.com/authorize')+ await screen.findByText('https://mcp.linear.app/authorize')expect(screen.queryByLabelText(/Client ID/)).not.toBeInTheDocument()cleanup()- discoverMock.mockResolvedValue(discovered(DCR_PUBLIC_DETECTED)) // dcr+ discoverMock.mockResolvedValue(discovered(NOTION_DISCOVER)) // dcrrenderWizard()await fillIdentity()clickDetect()@@ -176,9 +184,13 @@ describe('AddRemoteServerWizard', () => {})it('D-8: shows the no-refresh warning banner iff supportsRefresh is false', async () => {- const noRefresh: RemoteDetected = {- ...NOTION_DETECTED,- quirks: { bearerInBody: false, supportsRefresh: false },+ // No recorded pilot lacks refresh; only the quirk the banner reads is changed.+ const noRefresh: DiscoverRemoteResponse = {+ ...NOTION_DISCOVER,+ detected: {+ ...NOTION_DISCOVER.detected,+ quirks: { bearerInBody: false, supportsRefresh: false },+ },}discoverMock.mockResolvedValue(discovered(noRefresh))renderWizard()@@ -187,7 +199,7 @@ describe('AddRemoteServerWizard', () => {expect(await screen.findByText(/does not support token refresh/i)).toBeInTheDocument()cleanup()- discoverMock.mockResolvedValue(discovered(NOTION_DETECTED)) // supportsRefresh true+ discoverMock.mockResolvedValue(discovered(NOTION_DISCOVER)) // supportsRefresh truerenderWizard()await fillIdentity()clickDetect()@@ -196,19 +208,12 @@ describe('AddRemoteServerWizard', () => {})it('installs successfully: sends the request, fires onInstalled, and toasts', async () => {- discoverMock.mockResolvedValue(discovered(NOTION_DETECTED))- installMock.mockResolvedValue({- serverName: 'notion-remote',- namespace: 'mcp-server',- contextRef: 'research',- contextUpdated: true,- clientMode: 'public',- registrationMode: 'cimd',- })+ discoverMock.mockResolvedValue(discovered(LINEAR_DISCOVER))+ installMock.mockResolvedValue(LINEAR_INSTALLED)const { onInstalled } = renderWizard()- await fillIdentity()+ await fillIdentity('https://mcp.linear.app/mcp', 'linear')clickDetect()- await screen.findByText('https://mcp.notion.com/authorize')+ await screen.findByText('https://mcp.linear.app/authorize')fireEvent.click(screen.getByRole('button', { name: 'Continue' })) // → ConfirmfireEvent.click(await screen.findByRole('button', { name: 'Install remote server' }))@@ -216,9 +221,9 @@ describe('AddRemoteServerWizard', () => {await waitFor(() => expect(installMock).toHaveBeenCalledTimes(1))expect(installMock).toHaveBeenCalledWith(expect.objectContaining({- serverName: 'notion-remote',+ serverName: 'linear',contextRef: 'research',- baseUrl: 'https://mcp.notion.com/mcp',+ baseUrl: 'https://mcp.linear.app/mcp',mode: 'cimd',grantScope: 'user',})@@ -228,19 +233,21 @@ describe('AddRemoteServerWizard', () => {})it('shows a mapped install error inline', async () => {- discoverMock.mockResolvedValue(discovered(NOTION_DETECTED))- installMock.mockRejectedValue(- Object.assign(new Error('503'), { code: 'callback_base_url_unconfigured', body: {} })- )+ // Shared CIMD on a deployment without a callback base URL: detect does not block,+ // the install answers 503.+ discoverMock.mockResolvedValue(discovered(LINEAR_DISCOVER_UNCONFIGURED))+ installMock.mockRejectedValue(apiErrorFrom(CALLBACK_UNCONFIGURED_FAILURE))const { onInstalled } = renderWizard()- await fillIdentity()+ await fillIdentity('https://mcp.linear.app/mcp', 'linear')clickDetect()- await screen.findByText('https://mcp.notion.com/authorize')+ await screen.findByText('https://mcp.linear.app/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()+ const error = await screen.findByText(/callback url is not configured/i)+ expect(error).toHaveTextContent('CONTROL_API_OAUTH_CALLBACK_BASE_URL')+ expect(error).not.toHaveTextContent(/redirect URI of its own/i)expect(onInstalled).not.toHaveBeenCalled()})@@ -249,7 +256,7 @@ describe('AddRemoteServerWizard', () => {it('C5 transport dead: holds on step 0, alerts, offers the suggestion, and never shows Continue', async () => {// Repro for issue 26-09-25: OAuth valid but MCP transport dead at the typed// path. Against the parent head the wizard advances to step 1 instead.- discoverMock.mockResolvedValue(discovered(NOTION_DETECTED, VERCEL_TRANSPORT_DEAD))+ discoverMock.mockResolvedValue(discovered(NOTION_DISCOVER, VERCEL_TRANSPORT_DEAD))renderWizard()await fillIdentity('https://mcp.vercel.com/mcp', 'vercel-mcp')clickDetect()@@ -275,7 +282,7 @@ describe('AddRemoteServerWizard', () => {})it('C5 transport inconclusive: advances and shows a status banner on the config and confirm steps', async () => {- discoverMock.mockResolvedValue(discovered(NOTION_DETECTED, TRANSPORT_INCONCLUSIVE_TIMEOUT))+ discoverMock.mockResolvedValue(discovered(NOTION_DISCOVER, TRANSPORT_INCONCLUSIVE_TIMEOUT))renderWizard()await fillIdentity()clickDetect()@@ -294,7 +301,7 @@ describe('AddRemoteServerWizard', () => {})it('C5 transport alive: advances with no transport banner and shows the reachable summary row', async () => {- discoverMock.mockResolvedValue(discovered(NOTION_DETECTED, NOTION_TRANSPORT_ALIVE))+ discoverMock.mockResolvedValue(discovered(NOTION_DISCOVER))renderWizard()await fillIdentity()clickDetect()@@ -308,7 +315,7 @@ describe('AddRemoteServerWizard', () => {})it('C5 install transport_unreachable: shows the mapped error inline with the suggested URL', async () => {- discoverMock.mockResolvedValue(discovered(NOTION_DETECTED, NOTION_TRANSPORT_ALIVE))+ discoverMock.mockResolvedValue(discovered(NOTION_DISCOVER))installMock.mockRejectedValue(Object.assign(new Error('400'), {code: 'transport_unreachable',@@ -334,4 +341,123 @@ describe('AddRemoteServerWizard', () => {expect(screen.getByText(/https:\/\/mcp\.vercel\.com\//)).toBeInTheDocument()expect(onInstalled).not.toHaveBeenCalled()})++ // ── Per-server callback (AS without RFC 9207) ──────────────────────────────++ async function detectPreRegisteredPerServer(name = 'linear-pre') {+ discoverMock.mockResolvedValue(discovered(PRE_REGISTERED_PER_SERVER_DISCOVER))+ const utils = renderWizard()+ await fillIdentity('https://mcp.linear.app/mcp', name)+ clickDetect()+ await screen.findByLabelText(/Client ID/)+ return utils+ }++ function perServerUri(name: string): string {+ const template = PRE_REGISTERED_PER_SERVER_DISCOVER.callback?.redirectUriTemplate ?? ''+ return template.replace('{serverName}', name)+ }++ it('pre-registered per-server: shows the redirect URI for this server name, with copy', async () => {+ await detectPreRegisteredPerServer('hubspot')+ const uri = screen.getByRole('textbox', { name: 'Redirect URI' })+ expect(uri).toHaveValue(perServerUri('hubspot'))+ expect(uri).toHaveAttribute('readonly')+ expect(screen.getByRole('button', { name: 'Copy redirect URI' })).toBeInTheDocument()+ })++ it('pre-registered per-server: after the 201 holds on the URI until Done', async () => {+ installMock.mockResolvedValue(PRE_REGISTERED_PER_SERVER_INSTALLED)+ const { onInstalled } = await detectPreRegisteredPerServer()+ fireEvent.change(screen.getByLabelText(/Client ID/), { target: { value: 'cid' } })+ fireEvent.change(screen.getByLabelText(/Client secret/), { target: { value: 'secret' } })+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Install remote server' }))++ await waitFor(() => expect(installMock).toHaveBeenCalledTimes(1))+ expect(installMock).toHaveBeenCalledWith(+ expect.objectContaining({ mode: 'pre-registered', clientId: 'cid' })+ )+ const uri = await screen.findByRole('textbox', { name: 'Redirect URI' })+ expect(uri).toHaveValue(PRE_REGISTERED_PER_SERVER_INSTALLED.redirectUri)+ expect(screen.queryByText(/differs from the one shown before/i)).not.toBeInTheDocument()+ expect(onInstalled).not.toHaveBeenCalled()+ expect(screen.queryByRole('button', { name: 'Back' })).not.toBeInTheDocument()++ // Enter in the read-only URI field must not submit a second install.+ fireEvent.submit(uri.closest('form') as HTMLFormElement)+ expect(installMock).toHaveBeenCalledTimes(1)++ fireEvent.click(screen.getByRole('button', { name: 'Done' }))+ expect(onInstalled).toHaveBeenCalledTimes(1)+ })++ it('pre-registered: the 201 URI wins when the AS changed since detection', async () => {+ installMock.mockResolvedValue(PRE_REGISTERED_SHARED_INSTALLED)+ await detectPreRegisteredPerServer()+ fireEvent.change(screen.getByLabelText(/Client ID/), { target: { value: 'cid' } })+ fireEvent.change(screen.getByLabelText(/Client secret/), { target: { value: 'secret' } })+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Install remote server' }))++ const uri = await screen.findByRole('textbox', { name: 'Redirect URI' })+ expect(uri).toHaveValue(PRE_REGISTERED_SHARED_INSTALLED.redirectUri)+ expect(PRE_REGISTERED_SHARED_INSTALLED.redirectUri).not.toBe(perServerUri('linear-pre'))+ expect(screen.getByText(/differs from the one shown before/i)).toBeInTheDocument()+ })++ it('an AS without RFC 9207 behind an older control-api (no callback preview) is blocked', async () => {+ discoverMock.mockResolvedValue(OLDER_CONTROL_API_DCR_DISCOVER)+ renderWizard()+ await fillIdentity()+ clickDetect()++ expect(await screen.findByRole('alert')).toHaveTextContent(/update control-api/i)+ expect(+ screen.queryByRole('region', { name: 'Authorization server hosts' })+ ).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled()+ })++ it('per-server without a configured callback base URL is blocked before install', async () => {+ discoverMock.mockResolvedValue(discovered(ATLASSIAN_DISCOVER_UNCONFIGURED))+ renderWizard()+ await fillIdentity('https://mcp.atlassian.com/v2/mcp', 'atlassian')+ clickDetect()++ expect(await screen.findByRole('alert')).toHaveTextContent(/callback URL is not configured/i)+ expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled()+ expect(screen.getByRole('button', { name: /Confirm/ })).toBeDisabled()+ })++ it('without RFC 9207, shows the AS endpoint hosts on the configure and confirm steps', async () => {+ discoverMock.mockResolvedValue(discovered(ATLASSIAN_DISCOVER))+ renderWizard()+ await fillIdentity('https://mcp.atlassian.com/v2/mcp', 'atlassian')+ clickDetect()++ const hosts = await screen.findByRole('region', { name: 'Authorization server hosts' })+ expect(hosts).toHaveTextContent('Token host')+ expect(hosts).toHaveTextContent('auth.atlassian.com')+ expect(screen.getByText(/does not identify itself in its OAuth responses/i)).toBeInTheDocument()+ // DCR registers its own URI: nothing for the operator to copy.+ expect(screen.queryByRole('textbox', { name: 'Redirect URI' })).not.toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+ await screen.findByRole('button', { name: 'Install remote server' })+ expect(screen.getByRole('region', { name: 'Authorization server hosts' })).toHaveTextContent(+ 'auth.atlassian.com'+ )+ })++ it('with RFC 9207 (shared callback), shows no endpoint hosts', async () => {+ discoverMock.mockResolvedValue(discovered(LINEAR_DISCOVER))+ renderWizard()+ await fillIdentity('https://mcp.linear.app/mcp', 'linear')+ clickDetect()+ await screen.findByText('https://mcp.linear.app/authorize')+ expect(+ screen.queryByRole('region', { name: 'Authorization server hosts' })+ ).not.toBeInTheDocument()+ })})diff --git a/control-ui/lib/__tests__/remoteMcp.test.ts b/control-ui/lib/__tests__/remoteMcp.test.tsindex 2d6ebe38f..37f437609 100644--- a/control-ui/lib/__tests__/remoteMcp.test.ts+++ b/control-ui/lib/__tests__/remoteMcp.test.ts@@ -1,12 +1,30 @@import { describe, expect, it } from 'vitest'import {- DCR_CONFIDENTIAL_DETECTED,- DCR_PUBLIC_DETECTED,- NOTION_DETECTED,NOTION_TRANSPORT_ALIVE,TRANSPORT_INCONCLUSIVE_TIMEOUT,VERCEL_TRANSPORT_DEAD,} from '../../test/fixtures/remoteMcpDiscovery'+import {+ ATLASSIAN_DISCOVER,+ ATLASSIAN_DISCOVER_UNCONFIGURED,+ CALLBACK_UNCONFIGURED_FAILURE,+ CIMD_WITHOUT_ISS_BINDING_FAILURE,+ CLIENT_ID_IN_USE_FAILURE,+ DCR_CONFIDENTIAL_DETECTED,+ DCR_REDIRECT_MISMATCH_FAILURE,+ DROPBOX_DISCOVER_FAILURE,+ ISSUER_PUBLIC_SUFFIX_DISCOVER_FAILURE,+ LINEAR_DETECTED,+ LINEAR_DISCOVER,+ LINEAR_DISCOVER_UNCONFIGURED,+ NOTION_DETECTED,+ NOTION_DISCOVER,+ OLDER_CONTROL_API_DCR_DISCOVER,+ OLDER_CONTROL_API_LINEAR_DISCOVER,+ PRE_REGISTERED_PER_SERVER_DETECTED,+ PRE_REGISTERED_PER_SERVER_DISCOVER,+ apiErrorFrom,+} from '../../test/fixtures/remoteMcpWire'import {buildRemoteInstallRequest,describeDiscoveryError,@@ -17,11 +35,14 @@ import {installModeForRegistration,mapRemoteDiscoverError,mapRemoteInstallError,+ remoteCallbackBlocker,+ remoteCallbackVariant,+ remotePreRegisteredRedirectUri,requiresPreRegisteredCredentials,shouldWarnNoRefresh,transportBlocksContinue,} from '../remoteMcp'-import type { RemoteDetected, RemoteTransportProbe } from '../remoteMcp.types'+import type { RemoteTransportProbe } from '../remoteMcp.types'describe('installModeForRegistration (D-3/D-7)', () => {it('maps each registration mode to its install mode', () => {@@ -65,11 +86,10 @@ describe('shouldWarnNoRefresh (D-8)', () => {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(LINEAR_DETECTED)).toBe('public') // cimd+ expect(displayClientMode(NOTION_DETECTED)).toBe('public') // dcr, `none` offeredexpect(displayClientMode(DCR_CONFIDENTIAL_DETECTED)).toBe('confidential')- const manual: RemoteDetected = { ...NOTION_DETECTED, registrationMode: 'manual' }- expect(displayClientMode(manual)).toBe('confidential') // pre-registered+ expect(displayClientMode(PRE_REGISTERED_PER_SERVER_DETECTED)).toBe('confidential')})})@@ -92,6 +112,78 @@ describe('getRemoteServerNameError', () => {})})+describe('remoteCallbackVariant', () => {+ it('reads the backend callback preview', () => {+ expect(remoteCallbackVariant(LINEAR_DISCOVER)).toBe('shared')+ expect(remoteCallbackVariant(NOTION_DISCOVER)).toBe('per-server')+ expect(remoteCallbackVariant(PRE_REGISTERED_PER_SERVER_DISCOVER)).toBe('per-server')+ })++ it('on a control-api without the preview, falls back to the RFC 9207 rule', () => {+ expect(remoteCallbackVariant(OLDER_CONTROL_API_LINEAR_DISCOVER)).toBe('shared')+ expect(remoteCallbackVariant(OLDER_CONTROL_API_DCR_DISCOVER)).toBe('per-server')+ })+})++describe('remoteCallbackBlocker', () => {+ it('does not block a configured shared or per-server install', () => {+ expect(remoteCallbackBlocker(LINEAR_DISCOVER)).toBe('')+ expect(remoteCallbackBlocker(ATLASSIAN_DISCOVER)).toBe('')+ expect(remoteCallbackBlocker(PRE_REGISTERED_PER_SERVER_DISCOVER)).toBe('')+ })++ it('blocks a per-server install when the callback base URL is not configured', () => {+ expect(remoteCallbackBlocker(ATLASSIAN_DISCOVER_UNCONFIGURED)).toMatch(+ /callback URL is not configured/i+ )+ })++ it('does not block a shared install without a configured base URL', () => {+ // control-api decides per mode there (a shared CIMD/DCR install still answers 503).+ expect(LINEAR_DISCOVER_UNCONFIGURED.callback).toEqual({ configured: false, variant: 'shared' })+ expect(remoteCallbackBlocker(LINEAR_DISCOVER_UNCONFIGURED)).toBe('')+ })++ it('on an older control-api, blocks every install against an AS without RFC 9207', () => {+ expect(OLDER_CONTROL_API_DCR_DISCOVER.detected.registrationMode).toBe('dcr')+ expect(remoteCallbackBlocker(OLDER_CONTROL_API_DCR_DISCOVER)).toMatch(/update control-api/i)+ expect(remoteCallbackBlocker(OLDER_CONTROL_API_LINEAR_DISCOVER)).toBe('')+ })+})++describe('remotePreRegisteredRedirectUri', () => {+ const perServer = PRE_REGISTERED_PER_SERVER_DISCOVER.callback++ it('fills the server name into the per-server template', () => {+ expect(remotePreRegisteredRedirectUri(perServer, 'hubspot')).toBe(+ perServer?.redirectUriTemplate?.replace('{serverName}', 'hubspot')+ )+ expect(remotePreRegisteredRedirectUri(perServer, 'hubspot')).toMatch(+ /\/api\/v1\/oauth-callback\/remote\/hubspot$/+ )+ })++ it('shows nothing until the name is valid', () => {+ expect(remotePreRegisteredRedirectUri(perServer, '')).toBeNull()+ expect(remotePreRegisteredRedirectUri(perServer, 'Bad_Name')).toBeNull()+ expect(remotePreRegisteredRedirectUri(perServer, '-x')).toBeNull()+ })++ it('returns the shared URI as-is, whatever the name', () => {+ expect(remotePreRegisteredRedirectUri(LINEAR_DISCOVER.callback, '')).toBe(+ LINEAR_DISCOVER.callback?.redirectUriTemplate+ )+ })++ it('never shows a DCR template (control-api registers it) nor an unconfigured one', () => {+ expect(remotePreRegisteredRedirectUri(ATLASSIAN_DISCOVER.callback, 'atlassian')).toBeNull()+ expect(+ remotePreRegisteredRedirectUri(ATLASSIAN_DISCOVER_UNCONFIGURED.callback, 'atlassian')+ ).toBeNull()+ expect(remotePreRegisteredRedirectUri(undefined, 'atlassian')).toBeNull()+ })+})+describe('getRemoteBaseUrlError', () => {it('requires a URL', () => {expect(getRemoteBaseUrlError('')).toMatch(/required/i)@@ -174,6 +266,7 @@ describe('describeDiscoveryError', () => {'redirect_blocked','prm_resource_mismatch','issuer_mismatch',+ 'as_endpoints_cross_site',] as constconst texts = kinds.map(describeDiscoveryError)expect(new Set(texts).size).toBe(kinds.length)@@ -184,6 +277,19 @@ describe('describeDiscoveryError', () => {})describe('mapRemoteDiscoverError', () => {+ it('maps the Dropbox cross-site failure naming the offending endpoint', () => {+ const copy = mapRemoteDiscoverError(apiErrorFrom(DROPBOX_DISCOVER_FAILURE))+ expect(copy).toMatch(/token endpoint is not on the issuer's domain/i)+ expect(copy).toMatch(/RFC 9207/)+ })++ it('maps an issuer without a registrable domain to its own copy', () => {+ const copy = mapRemoteDiscoverError(apiErrorFrom(ISSUER_PUBLIC_SUFFIX_DISCOVER_FAILURE))+ expect(copy).toMatch(/issuer has no registrable domain/i)+ expect(copy).not.toMatch(/endpoint is not on/i)+ expect(copy).not.toBe(mapRemoteDiscoverError(apiErrorFrom(DROPBOX_DISCOVER_FAILURE)))+ })+it('maps a discovery_failed detail kind', () => {const err = Object.assign(new Error('502 ...'), {status: 502,@@ -233,12 +339,80 @@ describe('mapRemoteInstallError', () => {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: {},+ it('maps callback_base_url_unconfigured by the previewed callback variant', () => {+ const err = apiErrorFrom(CALLBACK_UNCONFIGURED_FAILURE)+ const perServer = mapRemoteInstallError(err, { callbackVariant: 'per-server' })+ expect(perServer).toMatch(/callback url is not configured/i)+ expect(perServer).toMatch(/redirect URI of its own/i)+ // Shared CIMD/DCR without an origin answer the same 503; so does an unknown variant.+ for (const copy of [+ mapRemoteInstallError(err, { callbackVariant: 'shared' }),+ mapRemoteInstallError(err),+ ]) {+ expect(copy).toMatch(/callback url is not configured/i)+ expect(copy).toMatch(/CONTROL_API_OAUTH_CALLBACK_BASE_URL/)+ expect(copy).not.toMatch(/redirect URI of its own/i)+ }+ })++ it('uses the server message when CIMD is refused for lack of RFC 9207', () => {+ expect(mapRemoteInstallError(apiErrorFrom(CIMD_WITHOUT_ISS_BINDING_FAILURE))).toBe(+ 'this authorization server supports CIMD but not RFC 9207; install with mode "dcr"'+ )+ })++ it('maps a per-server client_id conflict to "register a separate client"', () => {+ const copy = mapRemoteInstallError(apiErrorFrom(CLIENT_ID_IN_USE_FAILURE))+ expect(copy).toMatch(/another remote server/i)+ expect(copy).toMatch(/separate OAuth client/i)+ })++ it('maps each oauth_client_id_in_use conflict to its own copy', () => {+ const copies = ['remote_server', 'dynamic_client', 'cimd_client', undefined].map(conflict =>+ mapRemoteInstallError(+ Object.assign(new Error('409'), {+ code: 'oauth_client_id_in_use',+ body: { error: 'oauth_client_id_in_use', conflict },+ })+ )+ )+ expect(new Set(copies).size).toBe(copies.length)+ })++ it('maps a refused DCR redirect URI without leaking the raw kind', () => {+ const copy = mapRemoteInstallError(apiErrorFrom(DCR_REDIRECT_MISMATCH_FAILURE))+ expect(copy).toMatch(/different redirect URI/i)+ expect(copy).toMatch(/nothing was installed/i)+ expect(copy).not.toContain('redirect_uris_mismatch')+ })++ it('gives each refused-DCR kind its own copy', () => {+ const kinds = ['redirect_uris_mismatch', 'redirect_uris_missing', 'client_id_is_cimd_identity']+ const copies = kinds.map(kind =>+ mapRemoteInstallError(+ Object.assign(new Error('400'), {+ code: 'dcr_registration_failed',+ body: { error: 'dcr_registration_failed', detail: { kind } },+ })+ )+ )+ expect(new Set(copies).size).toBe(kinds.length)+ for (const [i, copy] of copies.entries()) expect(copy).not.toContain(kinds[i])+ })++ it('maps issuer_binding_required to the server message, else neutral copy', () => {+ // No golden: the router now answers a CIMD request against an AS without RFC 9207+ // with mode_unsupported first, so this 422 is only a defensive branch there.+ const withMessage = Object.assign(new Error('422'), {+ code: 'issuer_binding_required',+ body: { error: 'issuer_binding_required', message: 'a CIMD install requires it' },+ })+ expect(mapRemoteInstallError(withMessage)).toBe('a CIMD install requires it')+ const bare = Object.assign(new Error('422'), {+ code: 'issuer_binding_required',+ body: { error: 'issuer_binding_required' },})- expect(mapRemoteInstallError(err)).toMatch(/callback url is not configured/i)+ expect(mapRemoteInstallError(bare)).toMatch(/does not advertise RFC 9207/)})it('maps a re-run discovery_failed at install', () => {diff --git a/control-ui/lib/remoteMcp.ts b/control-ui/lib/remoteMcp.tsindex 3b35c9c6a..6e41c139b 100644--- a/control-ui/lib/remoteMcp.ts+++ b/control-ui/lib/remoteMcp.ts@@ -7,7 +7,11 @@ import type {InstallRemoteRequest,InstallRemoteResponse,InstallTransportUnreachableDetail,+ RemoteCallbackPreview,+ RemoteCallbackVariant,+ RemoteClientIdConflict,RemoteClientMode,+ RemoteDcrRejectionKind,RemoteDetected,RemoteDiscoveryErrorKind,RemoteInstallMode,@@ -146,6 +150,55 @@ export function getRemoteServerNameError(name: string): string {return ''}+/**+ * The callback variant an install would use. Authority is the backend `callback`+ * preview; a control-api older than it is read with the backend's own rule (shared+ * iff the AS returns `iss`), which that version can only install on the shared path.+ */+export function remoteCallbackVariant(+ discovery: Pick<DiscoverRemoteResponse, 'callback' | 'detected'>+): RemoteCallbackVariant {+ if (discovery.callback) return discovery.callback.variant+ return discovery.detected.issForCallback ? 'shared' : 'per-server'+}++/**+ * Why the detected configuration cannot be installed from here, or '' when it can.+ * A per-server install needs a configured callback origin (control-api answers 503+ * otherwise). A control-api older than the callback preview has no per-server+ * callback at all and rejects every install against an AS without RFC 9207.+ */+export function remoteCallbackBlocker(+ discovery: Pick<DiscoverRemoteResponse, 'callback' | 'detected'>+): string {+ if (remoteCallbackVariant(discovery) !== 'per-server') return ''+ const { callback } = discovery+ if (!callback) {+ return 'This authorization server does not support RFC 9207, and this control-api version can only install servers that do. Update control-api to install it with a redirect URI of its own.'+ }+ if (!callback.configured) {+ return 'The public OAuth callback URL is not configured on this deployment (CONTROL_API_OAUTH_CALLBACK_BASE_URL, a bare origin). This authorization server needs a redirect URI of its own, so it cannot be installed until that is set.'+ }+ return ''+}++/**+ * The redirect URI the operator registers at the provider for a pre-registered+ * client, or null when there is nothing to show yet. The `{serverName}` placeholder+ * is filled only with a name that passes the wizard's validation, and a template+ * still carrying `{installId}` is DCR-only (registered by control-api itself).+ */+export function remotePreRegisteredRedirectUri(+ callback: RemoteCallbackPreview | undefined,+ serverName: string+): string | null {+ const template = callback?.configured ? callback.redirectUriTemplate : undefined+ if (!template || template.includes('{installId}')) return null+ if (!template.includes('{serverName}')) return template+ if (getRemoteServerNameError(serverName) !== '') return null+ return template.split('{serverName}').join(serverName)+}+/*** Client-side FORM validation for the remote wizard's base URL (UX only — control-api* returns the authoritative 422 and its SSRF guard is what blocks a hostile target).@@ -190,8 +243,10 @@ function asCodedError(error: unknown): CodedError {/** Human copy for a `discovery_failed` detail kind (used by discover + install). */export function describeDiscoveryError(- kind: RemoteDiscoveryErrorKind | string | undefined+ kind: RemoteDiscoveryErrorKind | string | undefined,+ field?: string): string {+ if (kind === 'as_endpoints_cross_site') return describeCrossSite(field)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."@@ -216,15 +271,73 @@ export function describeDiscoveryError(}}+/**+ * Without RFC 9207 every AS endpoint must share the issuer's registrable domain.+ * `field` names what failed: the issuer itself (a public suffix, IP literal or URL+ * with credentials has no domain to compare against) or one endpoint, which is then+ * either on another domain or has none.+ */+function describeCrossSite(field: string | undefined): string {+ const why =+ 'It does not identify itself in OAuth responses (RFC 9207), so the connector only trusts endpoints on the issuer’s own domain, and this server cannot be installed.'+ if (field === 'issuer') {+ return `The authorization server's issuer has no registrable domain of its own (it is a shared hosting suffix, an IP address, or carries credentials). ${why}`+ }+ const subject = field ? `${field} endpoint is` : 'endpoints are'+ return `The authorization server's ${subject} not on the issuer's domain. ${why}`+}+function discoveryDetailKind(body: Record<string, unknown> | undefined): string | undefined {+ return detailString(body, 'kind')+}++function detailString(+ body: Record<string, unknown> | undefined,+ key: 'kind' | 'field'+): string | undefined {const detail = body?.detailif (detail && typeof detail === 'object') {- const kind = (detail as { kind?: unknown }).kind- if (typeof kind === 'string') return kind+ const value = (detail as Record<string, unknown>)[key]+ if (typeof value === 'string') return value}return undefined}+function describeDiscoveryFailure(body: Record<string, unknown> | undefined): string {+ return describeDiscoveryError(discoveryDetailKind(body), detailString(body, 'field'))+}++/** Copy for a DCR response refused after the client was minted (and revoked). */+function describeDcrRejection(kind: RemoteDcrRejectionKind): string {+ switch (kind) {+ case 'redirect_uris_mismatch':+ return 'The authorization server registered a different redirect URI than the one requested, so the new client was discarded and nothing was installed.'+ case 'redirect_uris_missing':+ return "The authorization server did not confirm the redirect URI it registered, which this server's own callback requires, so the new client was discarded and nothing was installed."+ case 'client_id_is_cimd_identity':+ return "The authorization server returned this platform's CIMD identity as the new client ID, so the client was discarded and nothing was installed."+ }+}++const DCR_REJECTION_KINDS: readonly string[] = [+ 'redirect_uris_mismatch',+ 'redirect_uris_missing',+ 'client_id_is_cimd_identity',+] satisfies readonly RemoteDcrRejectionKind[]++function describeClientIdConflict(conflict: unknown): string {+ switch (conflict as RemoteClientIdConflict) {+ case 'remote_server':+ return 'This client ID is already used by another remote server. Register a separate OAuth client for this server at the provider, with its own redirect URI.'+ case 'dynamic_client':+ return 'This client ID belongs to a client this platform registered dynamically. Register a separate OAuth client for this server at the provider.'+ case 'cimd_client':+ return "This client ID is the platform's CIMD identity, which cannot back a single server. Register a separate OAuth client for this server at the provider."+ default:+ return 'This client ID already backs another client. Register a separate OAuth client for this server at the provider.'+ }+}+/*** Map a discover-step failure (from `discoverRemoteServer`) to UI copy. Covers* the typed `discovery_failed` union and the kernel §4 pre-check 400 (whose@@ -233,15 +346,21 @@ function discoveryDetailKind(body: Record<string, unknown> | undefined): stringexport function mapRemoteDiscoverError(error: unknown): string {const e = asCodedError(error)if (e.code === 'discovery_failed') {- return describeDiscoveryError(discoveryDetailKind(e.body))+ return describeDiscoveryFailure(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 {+/**+ * Map an install-step failure to UI copy across the documented error codes.+ * `callbackVariant` is the variant the wizard previewed, when control-api reported one.+ */+export function mapRemoteInstallError(+ error: unknown,+ context: { callbackVariant?: RemoteCallbackVariant } = {}+): string {const e = asCodedError(error)const code = e.codeconst body = e.body@@ -254,18 +373,32 @@ export function mapRemoteInstallError(error: unknown): string {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':+ case 'dcr_registration_failed': {+ const kind = discoveryDetailKind(body)+ if (kind && DCR_REJECTION_KINDS.includes(kind)) {+ return describeDcrRejection(kind as RemoteDcrRejectionKind)+ }return `Dynamic client registration failed at the authorization server${- discoveryDetailKind(body) ? ` (${discoveryDetailKind(body)})` : ''+ kind ? ` (${kind})` : ''}.`+ }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.'+ return context.callbackVariant === 'per-server'+ ? 'The public OAuth callback URL is not configured on this deployment (CONTROL_API_OAUTH_CALLBACK_BASE_URL, a bare origin). This authorization server needs a redirect URI of its own, so set it before installing.'+ : 'The public OAuth callback URL is not configured on this deployment. Set CONTROL_API_OAUTH_CALLBACK_BASE_URL (a bare origin) before installing this server.'+ case 'issuer_binding_required':+ return (+ serverMessage ||+ 'This authorization server does not advertise RFC 9207, which this install mode requires.'+ )+ case 'oauth_client_id_in_use':+ return describeClientIdConflict(body?.conflict)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))+ return describeDiscoveryFailure(body)case 'invalid_request':return 'The install request was rejected as invalid. Reload the page and try again.'case 'transport_unreachable': {diff --git a/control-ui/lib/remoteMcp.types.ts b/control-ui/lib/remoteMcp.types.tsindex 6f55b095b..fa573098f 100644--- a/control-ui/lib/remoteMcp.types.ts+++ b/control-ui/lib/remoteMcp.types.ts@@ -36,6 +36,17 @@ export interface RemoteDetectedEndpoints {registration?: string}+/**+ * Hostnames of the AS endpoints an install would trust. Reported only for a+ * `per-server` callback (no RFC 9207 `iss`), where the same-site rule is all that+ * ties them to the issuer and cannot tell two hosts of one domain apart.+ */+export interface RemoteAsEndpointHosts {+ authorization: string+ token: string+ registration?: string+}+export interface RemoteDetectedQuirks {/** D-8: token goes in the request body, not the Authorization header. */bearerInBody: boolean@@ -51,10 +62,33 @@ export interface RemoteDetected {resource: stringissuer: stringissForCallback?: string+ asEndpointHosts?: RemoteAsEndpointHostsscopes: string[]quirks: RemoteDetectedQuirks}+/**+ * Which OAuth callback an install would register: the shared one when the AS+ * returns `iss` (RFC 9207), otherwise one of the server's own.+ */+export type RemoteCallbackVariant = 'shared' | 'per-server'++/** The `/discover` view of the callback an install from this result would use. */+export interface RemoteCallbackPreview {+ /**+ * Whether the deployment has a usable public callback base URL. `false` blocks every+ * `per-server` install. On `shared` only a pre-registered install proceeds (its URI+ * falls back to the request Host at consent); shared CIMD and DCR still answer 503.+ */+ configured: boolean+ variant: RemoteCallbackVariant+ /**+ * Redirect URI the install would register. Per-server URIs carry the literal+ * placeholders `{serverName}` and, for DCR, `{installId}` (minted at install).+ */+ redirectUriTemplate?: string+}+export interface DiscoverRemoteRequest {baseUrl: string}@@ -97,6 +131,8 @@ export interface DiscoverRemoteResponse {* control-api older than the probe (a missing `transport` never blocks).*/transport?: RemoteTransportProbe+ /** Absent on a control-api older than the per-server callback. */+ callback?: RemoteCallbackPreview}export interface InstallRemoteRequest {@@ -118,9 +154,24 @@ export interface InstallRemoteResponse {contextUpdated: trueclientMode: RemoteClientModeregistrationMode: RemoteRegistrationMode+ callbackVariant?: RemoteCallbackVariant+ /**+ * The redirect URI the AS must hold. Authoritative over the `/discover` preview:+ * the AS may have changed its RFC 9207 support in between.+ */+ redirectUri?: stringclientSecretName?: string}+/** Why a DCR registration response was refused after the client was minted. */+export type RemoteDcrRejectionKind =+ | 'redirect_uris_mismatch'+ | 'redirect_uris_missing'+ | 'client_id_is_cimd_identity'++/** What already uses a pre-registered client_id (409 `oauth_client_id_in_use`). */+export type RemoteClientIdConflict = 'cimd_client' | 'remote_server' | 'dynamic_client'+/*** Detail of the new install-time `400 { error: 'transport_unreachable' }`,* emitted before any write when the MCP transport probe finds the typed path@@ -148,3 +199,4 @@ export type RemoteDiscoveryErrorKind =| 'redirect_blocked'| 'prm_resource_mismatch'| 'issuer_mismatch'+ | 'as_endpoints_cross_site'diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex c1d49250d..6cf07b947 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.662",+ "version": "0.1.663","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.662",+ "version": "0.1.663","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 e75746e40..42dfc7727 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.662",+ "version": "0.1.663","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 bb8f0e5c6..99dfec756 100644--- a/control-ui/test/fixtures/__tests__/remoteMcpDiscovery.projection.test.ts+++ b/control-ui/test/fixtures/__tests__/remoteMcpDiscovery.projection.test.ts@@ -1,137 +1,77 @@import { describe, expect, it } from 'vitest'-import type { RemoteDetected, RemoteTransportProbe } from '../../../lib/remoteMcp.types'+import type { RemoteTransportProbe } 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,type InitializeProbeObservation,- LINEAR_AS_JSON,- LINEAR_DETECTED,- LINEAR_PRM_JSON,- NOTION_AS_JSON,- NOTION_DETECTED,NOTION_MCP_INITIALIZE,- NOTION_PRM_JSON,NOTION_TRANSPORT_ALIVE,- SENTRY_AS_JSON,- SENTRY_DETECTED,- SENTRY_PRM_JSON,VERCEL_MCP_INITIALIZE,VERCEL_ROOT_INITIALIZE,VERCEL_ROOT_PRM_JSON,VERCEL_TRANSPORT_DEAD,} from '../remoteMcpDiscovery'+import {+ ALL_DISCOVER_BODIES,+ ATLASSIAN_DISCOVER,+ LINEAR_DISCOVER,+ NOTION_DISCOVER,+ PRE_REGISTERED_PER_SERVER_DISCOVER,+} from '../remoteMcpWire'/**- * This is NOT a cross-service contract test — control-api is not importable from- * control-ui, so nothing here fails when the real producer drifts. The producer- * contract for the discover response (`res.body.detected`) is pinned by control-api- * `test/routes.adminRemoteMcp.test.ts`. What this file guarantees is narrower: each- * hand-derived `detected` fixture equals a LOCAL re-projection of the verbatim raw- * probe bytes, so a fixture cannot silently encode an invented shape.- *- * DRIFT LIMIT: projectDetected is a HAND MIRROR of the producer logic- * (`discoverRemoteOAuth` + `selectRegistrationMode`/`deriveQuirks` in- * control-api/src/oauth/discovery.ts, shaped into `detected` by the remoteMcp.ts- * route). control-api is not importable from control-ui, so a change to that logic- * does NOT fail this test on its own — it only catches fixture-vs-copy drift. Any- * edit to the producer projection must be reflected here, or these fixtures certify- * a stale shape. The producer carries the reverse pointer.+ * The `/discover` bodies are control-api's own responses (golden wire files captured+ * from the real router), so they are not re-projected here. What this block pins is+ * the part of that contract the wizard's decisions rest on; a golden that moves in a+ * way the wizard does not handle fails here, next to the fixture, rather than as a+ * confusing wizard test failure.*/-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+describe('remote MCP `/discover` goldens carry the callback contract the wizard relies on', () => {+ it('the pilots resolve as the backend decides today', () => {+ expect(LINEAR_DISCOVER.detected.registrationMode).toBe('cimd')+ expect(LINEAR_DISCOVER.callback?.variant).toBe('shared')+ // Notion offers CIMD but not RFC 9207, so it can only install by DCR.+ expect(NOTION_DISCOVER.detected.registrationMode).toBe('dcr')+ expect(NOTION_DISCOVER.callback?.variant).toBe('per-server')+ expect(ATLASSIAN_DISCOVER.detected.registrationMode).toBe('dcr')+ expect(PRE_REGISTERED_PER_SERVER_DISCOVER.detected.registrationMode).toBe('manual')+ })- 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-}+ for (const { name, body } of ALL_DISCOVER_BODIES) {+ it(`${name}: without RFC 9207 never CIMD, and the variant follows issForCallback`, () => {+ const hasIss = Boolean(body.detected.issForCallback)+ expect(body.callback?.variant).toBe(hasIss ? 'shared' : 'per-server')+ if (!hasIss) expect(body.detected.registrationMode).not.toBe('cimd')+ })-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,- },- ]+ it(`${name}: endpoint hosts are reported iff per-server, and match the endpoints`, () => {+ const hosts = body.detected.asEndpointHosts+ if (body.callback?.variant !== 'per-server') {+ expect(hosts).toBeUndefined()+ return+ }+ const { authorization, token, registration } = body.detected.endpoints+ expect(hosts).toEqual({+ authorization: new URL(authorization).hostname,+ token: new URL(token).hostname,+ ...(registration ? { registration: new URL(registration).hostname } : {}),+ })+ })- 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(`${name}: the redirect URI template carries the placeholders its mode needs`, () => {+ const callback = body.callback+ if (!callback?.configured) {+ expect(callback?.redirectUriTemplate).toBeUndefined()+ return+ }+ const template = callback.redirectUriTemplate ?? ''+ if (callback.variant === 'shared') {+ expect(template).not.toMatch(/\{/)+ } else if (body.detected.registrationMode === 'dcr') {+ expect(template).toMatch(/\/\{serverName\}\/\{installId\}$/)+ } else {+ expect(template).toMatch(/\/\{serverName\}$/)+ }})}-- 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.tsindex 53002b08a..394d2ef7d 100644--- a/control-ui/test/fixtures/remoteMcpDiscovery.ts+++ b/control-ui/test/fixtures/remoteMcpDiscovery.ts@@ -1,22 +1,16 @@/**- * 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).+ * Raw probe bytes of the remote MCP pilots (PRM + AS metadata), copied verbatim from+ * control-api's own T1 fixtures (control-api/test/fixtures/remoteOAuthDiscovery.ts —+ * live probes 2026-09-20, Linear re-probed 2026-09-29), plus the MCP transport probe+ * fixtures. The generic-lane prefill fixtures project these bytes.*- * 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).+ * The remote wizard's `/discover` and install bodies do NOT live here: they are the+ * producer's own responses, loaded from control-api's golden wire files by the sibling+ * `remoteMcpWire.ts`.*/-import type { RemoteDetected, RemoteTransportProbe } from '../../lib/remoteMcp.types'+import type { RemoteTransportProbe } from '../../lib/remoteMcp.types'-// ─── Verbatim real probe bytes (control-api T1 fixtures, 2026-09-20) ──────────+// ─── Verbatim real probe bytes (control-api T1 fixtures) ──────────────────────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)"}'@@ -25,8 +19,9 @@ export const NOTION_AS_JSON =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"]}'+// Re-probed 2026-09-29: Linear now advertises RFC 9207.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"}'+ '{"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"],"authorization_response_iss_parameter_supported":true,"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"]}'@@ -38,150 +33,14 @@ export const CANVA_PRM_JSON =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']-})--// Per-provider origin for the endpoint URLs below. The public-boundary CI guard-// (scripts/tests/test-minikube-t2-public-boundary.sh) reads a quoted-// `token: '…'` literal as a materialized credential; deriving the endpoint from-// an interpolated origin keeps the value out of that shape (the guard exempts-// interpolated values). Do not inline these back to plain string literals.-const NOTION = 'https://mcp.notion.com'-const LINEAR = 'https://mcp.linear.app'-const SENTRY = 'https://mcp.sentry.dev'-const CANVA = 'https://mcp.canva.com'--// ─── `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: `${NOTION}/authorize`,- token: `${NOTION}/token`,- registration: `${NOTION}/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: `${LINEAR}/authorize`,- token: `${LINEAR}/token`,- registration: `${LINEAR}/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: `${SENTRY}/oauth/authorize`,- token: `${SENTRY}/oauth/token`,- registration: `${SENTRY}/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: `${CANVA}/authorize`,- token: `${CANVA}/token`,- registration: `${CANVA}/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: `${NOTION}/authorize`,- token: `${NOTION}/token`,- registration: `${NOTION}/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: `${NOTION}/authorize`,- token: `${NOTION}/token`,- registration: `${NOTION}/register`,- },- resource: 'https://mcp.notion.com',- issuer: 'https://mcp.notion.com',- scopes: ['default'],- quirks: { bearerInBody: false, supportsRefresh: true },-}-// ─── MCP transport probe fixtures (live probes 2026-09-25) ────────────────────//-// control-ui cannot run control-api's `mcpTransportProbe.ts`, so — as with the-// `detected` fixtures above — the RemoteTransportProbe values below are DERIVED-// FROM THE REAL PROBE OUTPUTS: the verbatim root-PRM bytes plus the observed-// `initialize` HTTP statuses. The colocated contract test re-applies the-// producer's decision table + canonical-URL suggestion rule to those raw inputs-// and asserts each fixture equals the projection, so a drifted value fails.+// control-ui cannot run control-api's `mcpTransportProbe.ts`, so the+// RemoteTransportProbe values below are DERIVED FROM THE REAL PROBE OUTPUTS: the+// verbatim root-PRM bytes plus the observed `initialize` HTTP statuses. The colocated+// contract test re-applies the producer's decision table + canonical-URL suggestion+// rule to those raw inputs and asserts each fixture equals the projection, so a+// drifted value fails./** Vercel serves OAuth PRM per-path; the root `resource` is the canonical URL. */export const VERCEL_ROOT_PRM_JSON =diff --git a/control-ui/test/fixtures/remoteMcpWire.ts b/control-ui/test/fixtures/remoteMcpWire.tsnew file mode 100644index 000000000..0d797d5d8--- /dev/null+++ b/control-ui/test/fixtures/remoteMcpWire.ts@@ -0,0 +1,127 @@+/**+ * Producer fixtures — the bodies control-api's remote MCP admin routes return+ * (`POST /admin/mcp-servers/remote/discover` and `POST /admin/mcp-servers/remote`).+ *+ * control-api is not importable from this package, so these are the golden wire files+ * control-api's own route test captures from the real router (real discovery and+ * transport probe over recorded probe bytes, the real install saga):+ * control-api/test/routes.adminRemoteMcp.wireGoldens.test.ts →+ * control-api/test/fixtures/wire/remoteMcp.*.json. Loading the same bytes means a+ * producer change breaks the golden there before it can drift here.+ */+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { formatApiError } from '../../lib/api'+import type {+ DiscoverRemoteResponse,+ InstallRemoteResponse,+ RemoteDetected,+} from '../../lib/remoteMcp.types'++export type WireCapture<T = unknown> = { status: number; body: T }++const WIRE_DIR = resolve(__dirname, '../../../control-api/test/fixtures/wire')++function loadGolden<T>(name: string): WireCapture<T> {+ return JSON.parse(readFileSync(resolve(WIRE_DIR, `remoteMcp.${name}.json`), 'utf8'))+}++// ─── /discover 200 ────────────────────────────────────────────────────────────++/** Linear: CIMD + RFC 9207 → CIMD on the shared callback. */+export const LINEAR_DISCOVER = loadGolden<DiscoverRemoteResponse>('discover.linear').body+/** Notion: CIMD + DCR without RFC 9207 → public DCR on a per-server callback. */+export const NOTION_DISCOVER = loadGolden<DiscoverRemoteResponse>('discover.notion').body+/** Atlassian v2: same as Notion, with the issuer under a path of auth.atlassian.com. */+export const ATLASSIAN_DISCOVER = loadGolden<DiscoverRemoteResponse>('discover.atlassian').body+/** Atlassian v2 on a deployment without a public callback base URL. */+export const ATLASSIAN_DISCOVER_UNCONFIGURED = loadGolden<DiscoverRemoteResponse>(+ 'discover.atlassianUnconfigured'+).body+/** Linear on a deployment without a public callback base URL (shared, not blocking). */+export const LINEAR_DISCOVER_UNCONFIGURED = loadGolden<DiscoverRemoteResponse>(+ 'discover.linearUnconfigured'+).body+/** Notion minus CIMD and `none` → confidential DCR, per-server. */+export const DCR_CONFIDENTIAL_DISCOVER = loadGolden<DiscoverRemoteResponse>(+ 'discover.dcrConfidential'+).body+/** Linear minus registration and RFC 9207 → pre-registered client, per-server. */+export const PRE_REGISTERED_PER_SERVER_DISCOVER = loadGolden<DiscoverRemoteResponse>(+ 'discover.preRegisteredPerServer'+).body++export const ALL_DISCOVER_BODIES: ReadonlyArray<{ name: string; body: DiscoverRemoteResponse }> = [+ { name: 'linear', body: LINEAR_DISCOVER },+ { name: 'notion', body: NOTION_DISCOVER },+ { name: 'atlassian', body: ATLASSIAN_DISCOVER },+ { name: 'atlassian-unconfigured', body: ATLASSIAN_DISCOVER_UNCONFIGURED },+ { 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 },+]++// ─── /discover from a control-api older than the per-server callback ─────────+//+// That version answered the same body minus `callback` and `detected.asEndpointHosts`,+// so it is modelled by removing exactly those two fields from a current golden. Only+// servers whose registration mode did not change between the versions are modelled:+// Linear (CIMD with RFC 9207) and the confidential-DCR Notion variant (no CIMD, so the+// older selector also resolved DCR). Notion and Canva as recorded would have resolved+// CIMD there, so their current goldens cannot stand for the older backend.++function asOlderControlApi(body: DiscoverRemoteResponse): DiscoverRemoteResponse {+ const { callback: _callback, detected, ...rest } = body+ const { asEndpointHosts: _hosts, ...olderDetected } = detected+ return { ...rest, detected: olderDetected }+}++export const OLDER_CONTROL_API_LINEAR_DISCOVER = asOlderControlApi(LINEAR_DISCOVER)+/** An AS without RFC 9207: the older control-api answers 422 to every install mode. */+export const OLDER_CONTROL_API_DCR_DISCOVER = asOlderControlApi(DCR_CONFIDENTIAL_DISCOVER)++export const LINEAR_DETECTED: RemoteDetected = LINEAR_DISCOVER.detected+export const NOTION_DETECTED: RemoteDetected = NOTION_DISCOVER.detected+export const ATLASSIAN_DETECTED: RemoteDetected = ATLASSIAN_DISCOVER.detected+export const DCR_CONFIDENTIAL_DETECTED: RemoteDetected = DCR_CONFIDENTIAL_DISCOVER.detected+export const PRE_REGISTERED_PER_SERVER_DETECTED: RemoteDetected =+ PRE_REGISTERED_PER_SERVER_DISCOVER.detected++// ─── install 201 ──────────────────────────────────────────────────────────────++/** Per-server DCR; `redirectUri` ends in the (pinned) install nonce. */+export const ATLASSIAN_INSTALLED = loadGolden<InstallRemoteResponse>('install.atlassian').body+export const LINEAR_INSTALLED = loadGolden<InstallRemoteResponse>('install.linear').body+/** Installed as `linear-pre` from {@link PRE_REGISTERED_PER_SERVER_DISCOVER}. */+export const PRE_REGISTERED_PER_SERVER_INSTALLED = loadGolden<InstallRemoteResponse>(+ 'install.preRegisteredPerServer'+).body++/**+ * Same server name, but the AS started returning `iss` (RFC 9207) after the+ * {@link PRE_REGISTERED_PER_SERVER_DISCOVER} detection: the install lands on the+ * shared callback, so its redirect URI differs from the per-server preview.+ */+export const PRE_REGISTERED_SHARED_INSTALLED = loadGolden<InstallRemoteResponse>(+ 'install.preRegisteredShared'+).body++// ─── errors ───────────────────────────────────────────────────────────────────++/** Dropbox: token endpoint on dropboxapi.com, issuer on dropbox.com, no RFC 9207. */+export const DROPBOX_DISCOVER_FAILURE = loadGolden('discover.dropbox')+/** Issuer on a public suffix (`github.io`): no registrable domain to compare against. */+export const ISSUER_PUBLIC_SUFFIX_DISCOVER_FAILURE = loadGolden('discover.issuerPublicSuffix')+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')++/**+ * The error `apiSend` throws for a captured failure: the real `formatApiError` over+ * the golden body, so `.code`/`.body`/`.status` are what the wizard really receives.+ */+export function apiErrorFrom(capture: WireCapture): Error {+ const res = { status: capture.status, statusText: 'Error' } as Response+ return formatApiError(res, JSON.stringify(capture.body))+}