Skip to content

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

TypeScript

feat(control-ui): surface an incomplete mcp-server uninstall for retry (R3-H7)

Diego Zacarias6515ecc48490
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 94b304358..e306e808f 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.674",
+ "version": "0.1.675",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.674",
+ "version": "0.1.675",
"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.json
index 134b8b63c..bd5df3813 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.674",
+ "version": "0.1.675",
"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/mcpServerUninstallIncomplete.mcp_server.json b/control-api/test/fixtures/wire/mcpServerUninstallIncomplete.mcp_server.json
new file mode 100644
index 000000000..424ac1a4e
--- /dev/null
+++ b/control-api/test/fixtures/wire/mcpServerUninstallIncomplete.mcp_server.json
@@ -0,0 +1,6 @@
+{
+ "error": "mcp_server_uninstall_incomplete",
+ "outcome": "repair_required",
+ "pending": ["mcp_server"],
+ "deleted": ["Context/ctx-a (removed from allowlist)", "Secret/srv-credentials"]
+}
diff --git a/control-api/test/fixtures/wire/mcpServerUninstallIncomplete.oauth.json b/control-api/test/fixtures/wire/mcpServerUninstallIncomplete.oauth.json
new file mode 100644
index 000000000..ab2a474ab
--- /dev/null
+++ b/control-api/test/fixtures/wire/mcpServerUninstallIncomplete.oauth.json
@@ -0,0 +1,6 @@
+{
+ "error": "mcp_server_uninstall_incomplete",
+ "outcome": "repair_required",
+ "pending": ["dynamic_client", "oauth_grants"],
+ "deleted": ["Context/ctx-a (removed from allowlist)"]
+}
diff --git a/control-api/test/fixtures/wire/mcpServerUninstallIncomplete.secrets.json b/control-api/test/fixtures/wire/mcpServerUninstallIncomplete.secrets.json
new file mode 100644
index 000000000..b8ed94510
--- /dev/null
+++ b/control-api/test/fixtures/wire/mcpServerUninstallIncomplete.secrets.json
@@ -0,0 +1,6 @@
+{
+ "error": "mcp_server_uninstall_incomplete",
+ "outcome": "repair_required",
+ "pending": ["secrets"],
+ "deleted": ["Context/ctx-a (removed from allowlist)"]
+}
diff --git a/control-api/test/routes.mcpServerUninstall.repairRequired.test.ts b/control-api/test/routes.mcpServerUninstall.repairRequired.test.ts
index b615f10dd..bd1e63ffa 100644
--- a/control-api/test/routes.mcpServerUninstall.repairRequired.test.ts
+++ b/control-api/test/routes.mcpServerUninstall.repairRequired.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import express from 'express'
+import { readFileSync } from 'node:fs'
import request from 'supertest'
import type { K8sGateway } from '../src/k8s.js'
import { MockGateway } from './mockGateway.js'
@@ -66,6 +67,16 @@ async function allowlist(gw: MockGateway): Promise<string[]> {
const grantsPurges = () =>
dbMock.query.mock.calls.filter(([text]) => /DELETE\s+FROM\s+oauth_grants/i.test(text)).length
+// Golden wire bodies, versioned so control-ui's tests load these exact bytes instead of
+// retyping the shape; a producer change fails here and forces the golden to move.
+const wireGolden = (stage: string): unknown =>
+ JSON.parse(
+ readFileSync(
+ new URL(`./fixtures/wire/mcpServerUninstallIncomplete.${stage}.json`, import.meta.url),
+ 'utf8'
+ )
+ )
+
const conflict = () =>
Object.assign(new Error('the object has been modified'), { statusCode: 409, code: 409 })
const serverError = () =>
@@ -127,6 +138,7 @@ describe('DELETE /admin/mcp-servers/:name — cleanup before delete, 503 repair_
const first = await request(app).delete(`/admin/mcp-servers/${SERVER}`)
expect(first.status).toBe(503)
+ expect(first.body).toEqual(wireGolden('secrets'))
expect(first.body.pending).toEqual(['secrets'])
expect(first.body.deleted).toEqual(['Context/ctx-a (removed from allowlist)'])
await expect(gw.getResource('mcpservers', SERVER, NS)).resolves.toBeTruthy()
@@ -154,6 +166,25 @@ describe('DELETE /admin/mcp-servers/:name — cleanup before delete, 503 repair_
expect(grantsPurges()).toBe(0)
})
+ it('a DB outage during the OAuth teardown reports both OAuth stages and keeps the CR', async () => {
+ const { gw, app } = await setup()
+ dbMock.query.mockImplementation(async (text: string) => {
+ if (/dynamic_clients|oauth_grants/i.test(text)) throw new Error('db unavailable')
+ return { rows: [], rowCount: 0 }
+ })
+
+ try {
+ const res = await request(app).delete(`/admin/mcp-servers/${SERVER}`)
+
+ expect(res.status).toBe(503)
+ expect(res.body).toEqual(wireGolden('oauth'))
+ await expect(gw.getResource('mcpservers', SERVER, NS)).resolves.toBeTruthy()
+ await expect(gw.getSecret(CREDENTIALS, NS)).resolves.toBeTruthy()
+ } finally {
+ dbMock.query.mockImplementation(async () => ({ rows: [], rowCount: 0 }))
+ }
+ })
+
it('a CR delete failure reports mcp_server with every dependency already cleaned', async () => {
const { gw, app } = await setup()
vi.spyOn(gw, 'deleteResource').mockRejectedValueOnce(serverError())
@@ -161,6 +192,7 @@ describe('DELETE /admin/mcp-servers/:name — cleanup before delete, 503 repair_
const res = await request(app).delete(`/admin/mcp-servers/${SERVER}`)
expect(res.status).toBe(503)
+ expect(res.body).toEqual(wireGolden('mcp_server'))
expect(res.body.pending).toEqual(['mcp_server'])
expect(res.body.deleted).toEqual([
'Context/ctx-a (removed from allowlist)',
diff --git a/control-ui/app/mcp-servers/page.tsx b/control-ui/app/mcp-servers/page.tsx
index 60b90e02f..47051733a 100644
--- a/control-ui/app/mcp-servers/page.tsx
+++ b/control-ui/app/mcp-servers/page.tsx
@@ -15,7 +15,8 @@ import type {
} from '../../components/McpServerTable.types'
import { useToast } from '../../components/Toast'
import {
- apiSend,
+ McpServerUninstallIncompleteError,
+ deleteMcpServer,
getAgentTeams,
getAgentUsers,
getContexts,
@@ -183,7 +184,8 @@ export default function McpServersPage() {
const [updatingAgentAccessKey, setUpdatingAgentAccessKey] = useState<string | null>(null)
const { confirm, confirmDialog } = useConfirmDialog()
- async function loadAll() {
+ /** Resolves to the load error it displayed, or '' when the reload succeeded. */
+ async function loadAll(): Promise<string> {
setLoading(true)
setError('')
setAccessWarning('')
@@ -263,9 +265,12 @@ export default function McpServersPage() {
setAgentTargets(nextAgentTargets)
setBindingsByConnectorName(nextBindings)
setAccessByConnectorKey(nextAccessByConnectorKey)
+ return ''
} catch (e) {
- if (isSilentApiError(e)) return
- setError(e instanceof Error ? e.message : 'Failed to load connectors')
+ if (isSilentApiError(e)) return ''
+ const message = e instanceof Error ? e.message : 'Failed to load connectors'
+ setError(message)
+ return message
} finally {
setLoading(false)
}
@@ -283,11 +288,25 @@ export default function McpServersPage() {
setDeletingKey(key)
setError('')
try {
- await apiSend('DELETE', `/api/v1/admin/mcp-servers/${encodeURIComponent(server.name)}`)
+ await deleteMcpServer(server.name)
await loadAll()
showToast(`Connector ${key} deleted.`, { tone: 'success' })
} catch (e) {
if (isSilentApiError(e)) return
+ if (e instanceof McpServerUninstallIncompleteError) {
+ // Part of the cleanup already ran (e.g. agent access removed) while the
+ // connector stays listed; reload so the row reflects that before retrying.
+ const refreshError = await loadAll()
+ setError(
+ [
+ `${key}: ${e.message}`,
+ refreshError && `The list could not be refreshed: ${refreshError}`,
+ ]
+ .filter(Boolean)
+ .join(' ')
+ )
+ return
+ }
setError(e instanceof Error ? e.message : `Failed to delete ${key}`)
} finally {
setDeletingKey(null)
diff --git a/control-ui/components/CreateMcpServerForm/index.tsx b/control-ui/components/CreateMcpServerForm/index.tsx
index ae1795914..419ce0dc1 100644
--- a/control-ui/components/CreateMcpServerForm/index.tsx
+++ b/control-ui/components/CreateMcpServerForm/index.tsx
@@ -9,6 +9,7 @@ import { IconX } from '@/components/icons'
import { Button, Field, FormSection, SelectInput, TextInput } from '@/components/ui'
import { getAgentDisplayName } from '@/lib/agentName'
import {
+ McpServerUninstallIncompleteError,
createMcpSecret,
createMcpServer,
deleteMcpSecret,
@@ -602,10 +603,15 @@ export function CreateMcpServerForm({
)
if (oauthScopeError) {
const rollbackFailures: string[] = []
+ let incompleteUninstall: McpServerUninstallIncompleteError | null = null
try {
await deleteMcpServer(name)
- } catch {
- rollbackFailures.push('connector')
+ } catch (rollbackError) {
+ if (rollbackError instanceof McpServerUninstallIncompleteError) {
+ incompleteUninstall = rollbackError
+ } else {
+ rollbackFailures.push('connector')
+ }
}
if (createdSecretName) {
try {
@@ -616,13 +622,15 @@ export function CreateMcpServerForm({
rollbackFailures.push('Secret')
}
}
- setError(
- rollbackFailures.length === 0
- ? oauthScopeError
- : `${oauthScopeError} Automatic cleanup failed for the ${rollbackFailures.join(
- ' and '
- )}; remove it before retrying.`
- )
+ const rollbackNotes = [
+ incompleteUninstall
+ ? `Automatic cleanup of connector "${name}" is incomplete${incompleteUninstall.pendingSummary}; it ${incompleteUninstall.installState}. Delete it from the Installed Connectors list to finish.`
+ : '',
+ rollbackFailures.length > 0
+ ? `Automatic cleanup failed for the ${rollbackFailures.join(' and ')}; remove it before retrying.`
+ : '',
+ ].filter(Boolean)
+ setError([oauthScopeError, ...rollbackNotes].join(' '))
return
}
diff --git a/control-ui/components/__tests__/CreateMcpServerForm.test.tsx b/control-ui/components/__tests__/CreateMcpServerForm.test.tsx
index d789d7ec0..149df5f73 100644
--- a/control-ui/components/__tests__/CreateMcpServerForm.test.tsx
+++ b/control-ui/components/__tests__/CreateMcpServerForm.test.tsx
@@ -2,6 +2,11 @@ import type { ReactNode } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'
import * as api from '../../lib/api'
+import {
+ MCP_SERVER_PENDING_BODY,
+ SECRETS_PENDING_BODY,
+ uninstallIncompleteResponse,
+} from '../../test/fixtures/mcpServerUninstall'
import { CreateMcpServerForm } from '../CreateMcpServerForm'
import { ToastProvider } from '../Toast'
@@ -456,6 +461,56 @@ describe('CreateMcpServerForm — submit', () => {
expect(api.updateContext).not.toHaveBeenCalled()
})
+ it.each([
+ {
+ body: SECRETS_PENDING_BODY,
+ expected:
+ 'Automatic cleanup of connector "shared-drive" is incomplete (pending cleanup: connector Secrets); it is still installed. Delete it from the Installed Connectors list to finish.',
+ },
+ {
+ body: MCP_SERVER_PENDING_BODY,
+ expected:
+ 'Automatic cleanup of connector "shared-drive" is incomplete (pending cleanup: connector resource); it may still be installed. Delete it from the Installed Connectors list to finish.',
+ },
+ ])(
+ 'tells the operator an incomplete rollback and what is pending ($body.pending)',
+ async ({ body, expected }) => {
+ vi.mocked(api.getHosts).mockResolvedValueOnce({
+ items: [
+ { metadata: { name: 'agent-alpha' }, spec: { contextRef: 'ctx-alpha' } },
+ { metadata: { name: 'agent-beta' }, spec: { contextRef: 'ctx-beta' } },
+ ],
+ })
+ vi.mocked(api.createMcpServer).mockResolvedValueOnce({
+ metadata: { name: 'shared-drive' },
+ spec: { contextRef: 'ctx-alpha', oauth: { grantScope: 'context' } },
+ })
+ // The real client parses the producer's 503 body; only the network is stubbed.
+ vi.mocked(api.deleteMcpServer).mockImplementationOnce(async name => {
+ const actual = await vi.importActual<typeof import('../../lib/api')>('../../lib/api')
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(uninstallIncompleteResponse(body)))
+ try {
+ return await actual.deleteMcpServer(name)
+ } finally {
+ vi.unstubAllGlobals()
+ }
+ })
+ render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={vi.fn()} />)
+ await fillIdentity('shared-drive')
+ goToAccessStep()
+ await selectAgents('agent-alpha', 'agent-beta')
+ continueToSecretsStep()
+ chooseNoCredentials()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Create connector' }))
+
+ expect(await screen.findByText(expected, { exact: false })).toBeInTheDocument()
+ expect(
+ screen.queryByText(/Automatic cleanup failed for the connector/)
+ ).not.toBeInTheDocument()
+ }
+ )
+
it('creates a private access scope when no agents are selected', async () => {
const onCreated = vi.fn()
render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={onCreated} />)
diff --git a/control-ui/components/__tests__/McpServersPage.uninstall.test.tsx b/control-ui/components/__tests__/McpServersPage.uninstall.test.tsx
new file mode 100644
index 000000000..888fb8367
--- /dev/null
+++ b/control-ui/components/__tests__/McpServersPage.uninstall.test.tsx
@@ -0,0 +1,153 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import McpServersPage from '../../app/mcp-servers/page'
+import * as api from '../../lib/api'
+import {
+ SECRETS_PENDING_BODY,
+ uninstallIncompleteResponse,
+} from '../../test/fixtures/mcpServerUninstall'
+
+const showToast = vi.fn()
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push: vi.fn() }),
+}))
+
+vi.mock('../ConfirmDialog', () => ({
+ useConfirmDialog: () => ({ confirm: vi.fn().mockResolvedValue(true), confirmDialog: null }),
+}))
+
+vi.mock('../DashboardLayout', async () => {
+ const React = await import('react')
+ return {
+ DashboardLayout: ({ children }: { children: React.ReactNode }) =>
+ React.createElement('div', null, children),
+ }
+})
+
+vi.mock('../Toast', () => ({
+ useToast: () => ({ showToast }),
+}))
+
+vi.mock('../McpServerTable', async () => {
+ const React = await import('react')
+ return {
+ McpServerTable: (props: {
+ items: Array<{ metadata: { name: string; namespace: string } }>
+ deletingKey: string | null
+ onDelete: (server: { name: string; namespace: string }) => Promise<void>
+ }) =>
+ React.createElement(
+ 'ul',
+ null,
+ props.items.map(item =>
+ React.createElement(
+ 'li',
+ { key: item.metadata.name },
+ React.createElement(
+ 'button',
+ {
+ type: 'button',
+ disabled: props.deletingKey !== null,
+ onClick: () => props.onDelete(item.metadata),
+ },
+ `Delete ${item.metadata.name}`
+ )
+ )
+ )
+ ),
+ }
+})
+
+// The page's delete goes through the real client (fetch stubbed below) so the
+// typed error comes from parsing the producer's body, not from a hand-built object.
+vi.mock('../../lib/api', async importOriginal => {
+ const actual = await importOriginal<typeof import('../../lib/api')>()
+ return {
+ ...actual,
+ getAgentTeams: vi.fn().mockResolvedValue({ items: [] }),
+ getAgentUsers: vi.fn().mockResolvedValue({ items: [] }),
+ getContexts: vi.fn().mockResolvedValue({ items: [] }),
+ getHosts: vi.fn().mockResolvedValue({ items: [] }),
+ getMcpServers: vi.fn(),
+ updateContext: vi.fn().mockResolvedValue({}),
+ }
+})
+
+function okResponse(body: unknown): Response {
+ return {
+ ok: true,
+ status: 200,
+ statusText: 'OK',
+ text: async () => JSON.stringify(body),
+ } as unknown as Response
+}
+
+let fetchMock: ReturnType<typeof vi.fn>
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ vi.mocked(api.getMcpServers).mockResolvedValue({
+ items: [{ metadata: { name: 'srv', namespace: 'mcp-server' }, spec: {} }],
+ })
+})
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+})
+
+describe('Installed Connectors delete with an incomplete uninstall', () => {
+ it('shows the pending cleanup, keeps the refreshed row, and lets the operator retry', async () => {
+ fetchMock.mockResolvedValueOnce(uninstallIncompleteResponse(SECRETS_PENDING_BODY))
+ render(<McpServersPage />)
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Delete srv' }))
+
+ expect(
+ await screen.findByText(
+ 'mcp-server/srv: Connector uninstall is incomplete (pending cleanup: connector Secrets). ' +
+ 'The connector is still installed; retry the delete to finish.'
+ )
+ ).toBeInTheDocument()
+ expect(api.getMcpServers).toHaveBeenCalledTimes(2)
+ expect(showToast).not.toHaveBeenCalled()
+ const retry = screen.getByRole('button', { name: 'Delete srv' })
+ await waitFor(() => expect(retry).not.toBeDisabled())
+
+ fetchMock.mockResolvedValueOnce(okResponse({ kind: 'Status', status: 'Success' }))
+ vi.mocked(api.getMcpServers).mockResolvedValue({ items: [] })
+ fireEvent.click(retry)
+
+ await waitFor(() =>
+ expect(showToast).toHaveBeenCalledWith('Connector mcp-server/srv deleted.', {
+ tone: 'success',
+ })
+ )
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(fetchMock).toHaveBeenLastCalledWith(
+ '/control-api/api/v1/admin/mcp-servers/srv',
+ expect.objectContaining({ method: 'DELETE' })
+ )
+ expect(screen.queryByText(/Connector uninstall is incomplete/)).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Delete srv' })).not.toBeInTheDocument()
+ })
+
+ it('keeps both the incomplete-uninstall message and a failed list refresh visible', async () => {
+ fetchMock.mockResolvedValueOnce(uninstallIncompleteResponse(SECRETS_PENDING_BODY))
+ render(<McpServersPage />)
+ const deleteButton = await screen.findByRole('button', { name: 'Delete srv' })
+ vi.mocked(api.getMcpServers).mockRejectedValueOnce(new Error('503 Service Unavailable - down'))
+
+ fireEvent.click(deleteButton)
+
+ expect(
+ await screen.findByText(
+ 'mcp-server/srv: Connector uninstall is incomplete (pending cleanup: connector Secrets). ' +
+ 'The connector is still installed; retry the delete to finish. ' +
+ 'The list could not be refreshed: 503 Service Unavailable - down'
+ )
+ ).toBeInTheDocument()
+ })
+})
diff --git a/control-ui/lib/__tests__/mcpServerUninstall.test.ts b/control-ui/lib/__tests__/mcpServerUninstall.test.ts
new file mode 100644
index 000000000..a37caf25d
--- /dev/null
+++ b/control-ui/lib/__tests__/mcpServerUninstall.test.ts
@@ -0,0 +1,116 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ MCP_SERVER_PENDING_BODY,
+ OAUTH_PENDING_BODY,
+ SECRETS_PENDING_BODY,
+ uninstallIncompleteResponse,
+} from '../../test/fixtures/mcpServerUninstall'
+import { McpServerUninstallIncompleteError, deleteMcpServer } from '../api'
+
+function jsonResponse(body: unknown, status: number, statusText: string): Response {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ statusText,
+ text: async () => JSON.stringify(body),
+ } as unknown as Response
+}
+
+let fetchMock: ReturnType<typeof vi.fn>
+
+beforeEach(() => {
+ fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+})
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+})
+
+describe('deleteMcpServer incomplete uninstall', () => {
+ it('turns the 503 repair_required body into a typed error naming the pending cleanup', async () => {
+ fetchMock.mockResolvedValueOnce(uninstallIncompleteResponse(SECRETS_PENDING_BODY))
+
+ const error = await deleteMcpServer('srv').catch(e => e)
+
+ expect(error).toBeInstanceOf(McpServerUninstallIncompleteError)
+ expect(error.status).toBe(503)
+ expect(error.code).toBe('mcp_server_uninstall_incomplete')
+ expect(error.pending).toEqual(['secrets'])
+ expect(error.deleted).toEqual(['Context/ctx-a (removed from allowlist)'])
+ expect(error.message).toBe(
+ 'Connector uninstall is incomplete (pending cleanup: connector Secrets). ' +
+ 'The connector is still installed; retry the delete to finish.'
+ )
+ })
+
+ it('names a failed CR delete as the pending connector resource that may still be installed', async () => {
+ fetchMock.mockResolvedValueOnce(uninstallIncompleteResponse(MCP_SERVER_PENDING_BODY))
+
+ const error = await deleteMcpServer('srv').catch(e => e)
+
+ expect(error.message).toBe(
+ 'Connector uninstall is incomplete (pending cleanup: connector resource). ' +
+ 'The connector may still be installed; retry the delete to finish.'
+ )
+ })
+
+ it('names every stage when the OAuth teardown leaves several pending', async () => {
+ fetchMock.mockResolvedValueOnce(uninstallIncompleteResponse(OAUTH_PENDING_BODY))
+
+ const error = await deleteMcpServer('srv').catch(e => e)
+
+ expect(error.pending).toEqual(['dynamic_client', 'oauth_grants'])
+ expect(error.message).toBe(
+ 'Connector uninstall is incomplete (pending cleanup: OAuth client registration, OAuth grants). ' +
+ 'The connector is still installed; retry the delete to finish.'
+ )
+ })
+
+ it('keeps the incomplete error for an unknown stage, naming only the known ones', async () => {
+ fetchMock
+ .mockResolvedValueOnce(
+ uninstallIncompleteResponse({ ...SECRETS_PENDING_BODY, pending: ['future_stage'] })
+ )
+ .mockResolvedValueOnce(
+ uninstallIncompleteResponse({
+ ...SECRETS_PENDING_BODY,
+ pending: ['future_stage', 'secrets'],
+ })
+ )
+
+ const unknownOnly = await deleteMcpServer('srv').catch(e => e)
+ const mixed = await deleteMcpServer('srv').catch(e => e)
+
+ expect(unknownOnly).toBeInstanceOf(McpServerUninstallIncompleteError)
+ expect(unknownOnly.pending).toEqual([])
+ expect(unknownOnly.message).toBe(
+ 'Connector uninstall is incomplete. The connector is still installed; retry the delete to finish.'
+ )
+ expect(mixed).toBeInstanceOf(McpServerUninstallIncompleteError)
+ expect(mixed.message).toContain('(pending cleanup: connector Secrets)')
+ expect(mixed.message).not.toContain('future_stage')
+ })
+
+ it('leaves a 404 for a missing connector as the generic API error', async () => {
+ fetchMock.mockResolvedValueOnce(
+ jsonResponse({ error: 'mcpservers/srv not found' }, 404, 'Not Found')
+ )
+
+ const error = await deleteMcpServer('srv').catch(e => e)
+
+ expect(error).not.toBeInstanceOf(McpServerUninstallIncompleteError)
+ expect(error.status).toBe(404)
+ })
+
+ it('does not treat an unrelated 503 as an incomplete uninstall', async () => {
+ fetchMock.mockResolvedValueOnce(
+ jsonResponse({ error: 'upstream_unavailable' }, 503, 'Service Unavailable')
+ )
+
+ const error = await deleteMcpServer('srv').catch(e => e)
+
+ expect(error).not.toBeInstanceOf(McpServerUninstallIncompleteError)
+ expect(error.status).toBe(503)
+ })
+})
diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.ts
index fc6ba5e73..01f1e022c 100644
--- a/control-ui/lib/api.ts
+++ b/control-ui/lib/api.ts
@@ -1532,11 +1532,92 @@ export async function createMcpServer(payload: {
return apiSend('POST', '/api/v1/admin/mcp-servers', payload) as Promise<McpServerResource>
}
+/** Cleanup stages control-api reports as `pending` when an mcp-server uninstall stops. */
+export type McpServerUninstallStage =
+ | 'contexts'
+ | 'dynamic_client'
+ | 'oauth_grants'
+ | 'secrets'
+ | 'mcp_server'
+
+const MCP_SERVER_UNINSTALL_STAGE_LABELS: Record<McpServerUninstallStage, string> = {
+ contexts: 'agent access',
+ dynamic_client: 'OAuth client registration',
+ oauth_grants: 'OAuth grants',
+ secrets: 'connector Secrets',
+ mcp_server: 'connector resource',
+}
+
+export function isMcpServerUninstallStage(value: unknown): value is McpServerUninstallStage {
+ return typeof value === 'string' && Object.hasOwn(MCP_SERVER_UNINSTALL_STAGE_LABELS, value)
+}
+
+/**
+ * The uninstall stopped at a failing cleanup step; repeating the same DELETE
+ * resumes it. Keeps `status`/`code`/`body` so generic error handling that
+ * inspects them still works. Stages this client does not know are dropped from
+ * `pending` (the message then names only the known ones).
+ */
+export class McpServerUninstallIncompleteError extends Error {
+ readonly status = 503
+ readonly code = 'mcp_server_uninstall_incomplete'
+ /** Human-readable `pending`, e.g. " (pending cleanup: OAuth grants)"; empty when none is known. */
+ readonly pendingSummary: string
+ /**
+ * "is still installed", or "may still be installed" when the CR delete itself
+ * failed: that error does not tell whether the API server already accepted it.
+ */
+ readonly installState: string
+
+ constructor(
+ readonly pending: McpServerUninstallStage[],
+ readonly deleted: string[],
+ readonly body: Record<string, unknown>
+ ) {
+ const labels = pending.map(stage => MCP_SERVER_UNINSTALL_STAGE_LABELS[stage])
+ const pendingSummary = labels.length > 0 ? ` (pending cleanup: ${labels.join(', ')})` : ''
+ const installState = pending.includes('mcp_server')
+ ? 'may still be installed'
+ : 'is still installed'
+ super(
+ `Connector uninstall is incomplete${pendingSummary}. The connector ${installState}; retry the delete to finish.`
+ )
+ this.name = 'McpServerUninstallIncompleteError'
+ this.pendingSummary = pendingSummary
+ this.installState = installState
+ }
+}
+
+function toMcpServerUninstallIncompleteError(
+ err: unknown
+): McpServerUninstallIncompleteError | null {
+ if (!(err instanceof Error) || (err as Error & { status?: unknown }).status !== 503) {
+ return null
+ }
+ const body = apiErrorBody(err)
+ if (
+ !body ||
+ body.error !== 'mcp_server_uninstall_incomplete' ||
+ body.outcome !== 'repair_required'
+ ) {
+ return null
+ }
+ const pending = Array.isArray(body.pending) ? body.pending.filter(isMcpServerUninstallStage) : []
+ const deleted = Array.isArray(body.deleted)
+ ? body.deleted.filter((item): item is string => typeof item === 'string')
+ : []
+ return new McpServerUninstallIncompleteError(pending, deleted, body)
+}
+
export async function deleteMcpServer(name: string) {
- return apiSend('DELETE', `/api/v1/admin/mcp-servers/${encodeURIComponent(name)}`) as Promise<{
- name: string
- namespace?: string
- }>
+ try {
+ return (await apiSend('DELETE', `/api/v1/admin/mcp-servers/${encodeURIComponent(name)}`)) as {
+ name: string
+ namespace?: string
+ }
+ } catch (err) {
+ throw toMcpServerUninstallIncompleteError(err) ?? err
+ }
}
export async function getMcpServer(name: string) {
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 71a88bf82..72af91309 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.660",
+ "version": "0.1.661",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.660",
+ "version": "0.1.661",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --git a/control-ui/package.json b/control-ui/package.json
index 3aeb2ef84..ea503d970 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.660",
+ "version": "0.1.661",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/control-ui/test/fixtures/__tests__/mcpServerUninstall.contract.test.ts b/control-ui/test/fixtures/__tests__/mcpServerUninstall.contract.test.ts
new file mode 100644
index 000000000..f9137bb28
--- /dev/null
+++ b/control-ui/test/fixtures/__tests__/mcpServerUninstall.contract.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest'
+import { isMcpServerUninstallStage } from '../../../lib/api'
+import { ALL_PENDING_BODIES } from '../mcpServerUninstall'
+
+describe('MCP server uninstall producer golden contract', () => {
+ it('knows every pending stage the producer emits in its golden wire bodies', () => {
+ const stages = [...new Set(ALL_PENDING_BODIES.flatMap(body => body.pending))]
+
+ expect(stages.sort()).toEqual(['dynamic_client', 'mcp_server', 'oauth_grants', 'secrets'])
+ expect(stages.filter(stage => !isMcpServerUninstallStage(stage))).toEqual([])
+ })
+
+ it('reads the error and outcome codes the client recognises', () => {
+ for (const body of ALL_PENDING_BODIES) {
+ expect(body.error).toBe('mcp_server_uninstall_incomplete')
+ expect(body.outcome).toBe('repair_required')
+ }
+ })
+})
diff --git a/control-ui/test/fixtures/mcpServerUninstall.ts b/control-ui/test/fixtures/mcpServerUninstall.ts
new file mode 100644
index 000000000..0ba0d0e85
--- /dev/null
+++ b/control-ui/test/fixtures/mcpServerUninstall.ts
@@ -0,0 +1,56 @@
+/**
+ * Producer fixtures — the 503 body `DELETE /admin/mcp-servers/:name` returns when the
+ * uninstall stops at a failing cleanup step with the CR still present.
+ *
+ * control-api is not importable from this package, so the bodies are the golden wire
+ * files control-api's own route test asserts its real responses against
+ * (control-api/test/routes.mcpServerUninstall.repairRequired.test.ts →
+ * control-api/test/fixtures/wire/mcpServerUninstallIncomplete.*.json). Loading the
+ * same bytes means a producer change breaks the golden there before it can drift here.
+ *
+ * `pending` lists every stage the failing step left undone: one element for the
+ * Context, Secret and CR steps, and both OAuth stages when the teardown fails on
+ * both.
+ */
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+export type ProducerMcpServerUninstallIncompleteBody = {
+ error: string
+ outcome: string
+ pending: string[]
+ deleted: string[]
+}
+
+const WIRE_DIR = resolve(__dirname, '../../../control-api/test/fixtures/wire')
+
+function loadGolden(stage: string): ProducerMcpServerUninstallIncompleteBody {
+ return JSON.parse(
+ readFileSync(resolve(WIRE_DIR, `mcpServerUninstallIncomplete.${stage}.json`), 'utf8')
+ )
+}
+
+/** Secret delete failed after the Context strip: CR and Secret still present. */
+export const SECRETS_PENDING_BODY = loadGolden('secrets')
+
+/** Every dependency cleaned, the CR delete itself failed. */
+export const MCP_SERVER_PENDING_BODY = loadGolden('mcp_server')
+
+/** DB outage during the OAuth teardown: both OAuth stages pending. */
+export const OAUTH_PENDING_BODY = loadGolden('oauth')
+
+export const ALL_PENDING_BODIES = [
+ SECRETS_PENDING_BODY,
+ MCP_SERVER_PENDING_BODY,
+ OAUTH_PENDING_BODY,
+]
+
+/** Response as control-ui's fetch client sees it through the proxy. */
+export function uninstallIncompleteResponse(body: unknown): Response {
+ return {
+ ok: false,
+ status: 503,
+ statusText: 'Service Unavailable',
+ text: async () => JSON.stringify(body),
+ } as unknown as Response
+}