Skip to content

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

TypeScript

fix(control-ui): enforce registry access contracts

Miguelon Peluchon368b35cb851d
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 49284f613..d052d9440 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.432",
+ "version": "0.1.433",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.432",
+ "version": "0.1.433",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-api/package.json b/control-api/package.json
index 62a5d275c..e2b561351 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.432",
+ "version": "0.1.433",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/test/routes.resources.test.ts b/control-api/test/routes.resources.test.ts
index a0daa3bf9..cb0e07f8d 100644
--- a/control-api/test/routes.resources.test.ts
+++ b/control-api/test/routes.resources.test.ts
@@ -119,6 +119,74 @@ describe('routes/resources', () => {
expect(listRes.body.items[0].spec.contextRef).toBe('ctx-a')
})
+ it('produces the Context list shape consumed by the control UI, including resourceVersion', async () => {
+ const gateway = new MockGateway('mcp-server')
+ const context = {
+ metadata: {
+ name: 'research',
+ namespace: 'mcp-server',
+ resourceVersion: 'rv-context-read',
+ },
+ spec: {
+ contextId: 'research',
+ description: 'Research tools',
+ mcpServers: ['search'],
+ sharedFileSystems: [{ name: 'docs', mountPath: '/docs' }],
+ },
+ status: { sharedFileSystems: [] },
+ }
+ vi.spyOn(gateway, 'listResource').mockResolvedValueOnce([context] as never)
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminResourcesRouter(gateway as never))
+
+ const response = await request(app).get('/admin/contexts').expect(200)
+
+ expect(response.body).toEqual({ items: [context] })
+ })
+
+ it('rejects a stale Context membership replacement without changing the winning spec', async () => {
+ const gateway = new MockGateway('mcp-server')
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminResourcesRouter(gateway as never))
+ await gateway.createResource(
+ 'contexts',
+ {
+ metadata: { name: 'research' },
+ spec: { contextId: 'research', mcpServers: ['winner-connector'] },
+ },
+ config.contextsNamespace
+ )
+
+ const realUpdate = gateway.updateResource.bind(gateway)
+ vi.spyOn(gateway, 'updateResource').mockImplementation(
+ async (plural, name, body, namespace) => {
+ const resourceVersion = (body.metadata as { resourceVersion?: string } | undefined)
+ ?.resourceVersion
+ if (plural === 'contexts' && resourceVersion === 'rv-stale') {
+ throw new K8sConflictError('contexts/research changed since it was read')
+ }
+ return realUpdate(plural, name, body, namespace)
+ }
+ )
+
+ await request(app)
+ .put('/admin/contexts/research')
+ .send({
+ metadata: { resourceVersion: 'rv-stale' },
+ spec: { contextId: 'research', mcpServers: ['stale-connector'] },
+ })
+ .expect(409, { error: 'conflict', reason: 'resource_changed' })
+
+ const stored = (await gateway.getResource(
+ 'contexts',
+ 'research',
+ config.contextsNamespace
+ )) as { spec: { mcpServers: string[] } }
+ expect(stored.spec.mcpServers).toEqual(['winner-connector'])
+ })
+
it('filters communication channels by confirmed user id when requested', async () => {
const gateway = new MockGateway('channels')
const app = express()
diff --git a/control-api/test/routes.secrets.test.ts b/control-api/test/routes.secrets.test.ts
index 607d2fc06..7d23371fd 100644
--- a/control-api/test/routes.secrets.test.ts
+++ b/control-api/test/routes.secrets.test.ts
@@ -6,7 +6,10 @@ import { createAdminSecretsRouter } from '../src/routes/admin/secrets.js'
function createGateway() {
return {
listSecrets: vi.fn(async () => [
- { metadata: { name: 's1', namespace: 'ns1', labels: { 'clerum.io/host-secret': 'true' } } },
+ {
+ metadata: { name: 's1', namespace: 'ns1', labels: { 'clerum.io/host-secret': 'true' } },
+ keys: ['openai-api-key'],
+ },
{ metadata: { name: 's2', namespace: 'ns1', labels: {} } },
{ metadata: { name: 's3', namespace: 'ns1', labels: { 'clerum.io/host-secret': 'false' } } },
]),
@@ -31,8 +34,11 @@ describe('routes/secrets', () => {
app.use(createAdminSecretsRouter(gateway as never))
const filtered = await request(app).get('/admin/secrets').expect(200)
- expect(filtered.body.items).toHaveLength(1)
- expect(filtered.body.items[0].name).toBe('s1')
+ // Producer-backed contract consumed by control-ui listLlmHostSecrets/SecretsTable.
+ // Secret values and Kubernetes metadata must never cross this boundary.
+ expect(filtered.body).toEqual({
+ items: [{ name: 's1', keys: ['openai-api-key'] }],
+ })
const filteredNames = (filtered.body.items || []).map((item: { name?: string }) => item.name)
expect(filteredNames).not.toContain('s2')
expect(filteredNames).not.toContain('s3')
diff --git a/control-ui/app/contexts/[name]/page.tsx b/control-ui/app/contexts/[name]/page.tsx
index a669f8fb0..11a6b3c22 100644
--- a/control-ui/app/contexts/[name]/page.tsx
+++ b/control-ui/app/contexts/[name]/page.tsx
@@ -13,6 +13,7 @@ import type { TableHeaderColumn } from '@components/TableHeaderRow/types'
import { useToast } from '@components/Toast'
import { CONTROL_ROUTES } from '@constants/routes'
import { getAgentDisplayName } from '@lib/agentName'
+import { buildContextUpdatePayload, contextMutationError } from '@lib/contextMutation'
import { DashboardLayout } from '../../../components/DashboardLayout'
import { IconFolder, IconGroupWork } from '../../../components/Sidebar/icons'
import { IconMoreHorizontal, IconX } from '../../../components/icons'
@@ -177,6 +178,7 @@ export default function ContextDetailsPage() {
const [contextUsers, setContextUsers] = useState<ContextUser[]>([])
const [contextTeams, setContextTeams] = useState<ContextTeam[]>([])
const [resolvedContextId, setResolvedContextId] = useState(isNew ? '' : routeName)
+ const [contextResourceVersion, setContextResourceVersion] = useState<string | undefined>()
const [contextNameDraft, setContextNameDraft] = useState(isNew ? '' : routeName)
const [descriptionDraft, setDescriptionDraft] = useState('')
@@ -268,6 +270,7 @@ export default function ContextDetailsPage() {
const metadata = (context.metadata || {}) as ContextResource['metadata']
const resolvedName = metadata?.name || spec.contextId || routeName
const resolvedContext = spec.contextId || resolvedName
+ setContextResourceVersion(metadata?.resourceVersion)
setContextNameDraft(resolvedName)
setSavedContextName(resolvedName)
setResolvedContextId(resolvedContext)
@@ -419,7 +422,11 @@ export default function ContextDetailsPage() {
const nextName = encodeURIComponent(contextNameDraft.trim())
router.replace(CONTROL_ROUTES.contexts.detail(nextName))
} else {
- await updateContext(routeName, payload)
+ const updated = await updateContext(
+ routeName,
+ buildContextUpdatePayload(contextResourceVersion, payload.spec)
+ )
+ setContextResourceVersion(updated.metadata?.resourceVersion ?? contextResourceVersion)
setResolvedContextId(payload.spec.contextId)
setSavedDescription(descriptionDraft)
setSavedContextName(contextNameDraft)
@@ -427,7 +434,7 @@ export default function ContextDetailsPage() {
}
showToast('Context saved.', { tone: 'success' })
} catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to save context')
+ setError(contextMutationError(e, 'Failed to save context'))
} finally {
setBusy(false)
}
@@ -437,18 +444,20 @@ export default function ContextDetailsPage() {
setBusy(true)
setError('')
try {
- await updateContext(routeName, {
- spec: {
+ const updated = await updateContext(
+ routeName,
+ buildContextUpdatePayload(contextResourceVersion, {
contextId: resolvedContextId,
description: descriptionDraft.trim(),
mcpServers: nextServers,
sharedFileSystems: sharedFileSystemsDraft,
- },
- })
+ })
+ )
+ setContextResourceVersion(updated.metadata?.resourceVersion ?? contextResourceVersion)
setMcpServersDraft(nextServers)
showToast('Connectors updated.', { tone: 'success' })
} catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to update connectors')
+ setError(contextMutationError(e, 'Failed to update connectors'))
} finally {
setBusy(false)
}
@@ -458,18 +467,20 @@ export default function ContextDetailsPage() {
setBusy(true)
setError('')
try {
- await updateContext(routeName, {
- spec: {
+ const updated = await updateContext(
+ routeName,
+ buildContextUpdatePayload(contextResourceVersion, {
contextId: resolvedContextId,
description: descriptionDraft.trim(),
mcpServers: mcpServersDraft,
sharedFileSystems: nextRefs,
- },
- })
+ })
+ )
+ setContextResourceVersion(updated.metadata?.resourceVersion ?? contextResourceVersion)
setSharedFileSystemsDraft(nextRefs)
showToast('Shared filesystems updated.', { tone: 'success' })
} catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to update shared filesystems')
+ setError(contextMutationError(e, 'Failed to update shared filesystems'))
} finally {
setBusy(false)
}
diff --git a/control-ui/app/mcp-servers/[name]/edit/page.tsx b/control-ui/app/mcp-servers/[name]/edit/page.tsx
index dac10d911..ee8229148 100644
--- a/control-ui/app/mcp-servers/[name]/edit/page.tsx
+++ b/control-ui/app/mcp-servers/[name]/edit/page.tsx
@@ -20,8 +20,26 @@ import {
} from '@constants/connectorEdit'
import { CONTROL_ROUTES } from '@constants/routes'
import { getAgentDisplayName } from '@lib/agentName'
-import { getContextTeams, getContextUsers, getHosts, getMcpServer, updateMcpServer } from '@lib/api'
-import type { EgressBinding, EnvSecret, EnvSecretKeyMapping, McpServerResource } from '@lib/api'
+import {
+ getContextTeams,
+ getContextUsers,
+ getContexts,
+ getHosts,
+ getMcpServer,
+ updateMcpServer,
+} from '@lib/api'
+import type {
+ ContextResource,
+ EgressBinding,
+ EnvSecret,
+ EnvSecretKeyMapping,
+ McpServerResource,
+} from '@lib/api'
+import {
+ contextNamesForConnector,
+ mergeAccessSummaries,
+ sortAccessPrincipals,
+} from '@lib/connectorAccess'
import type { EgressEditorStatus } from '@lib/egressModel'
/**
@@ -95,6 +113,7 @@ export default function EditMcpServerPage() {
const [egressBindings, setEgressBindings] = useState<EgressBinding[] | undefined>(undefined)
const [egressStatus, setEgressStatus] = useState<EgressEditorStatus | null>(null)
const [contextAccess, setContextAccess] = useState<ContextAccess>(EMPTY_CONTEXT_ACCESS)
+ const [contextNames, setContextNames] = useState<string[]>([])
const [contextAccessError, setContextAccessError] = useState('')
const [loadingContextAccess, setLoadingContextAccess] = useState(false)
@@ -124,9 +143,12 @@ export default function EditMcpServerPage() {
setLoading(true)
setLoadError('')
try {
- const result = await getMcpServer(name)
+ const [result, contextsResult] = await Promise.all([getMcpServer(name), getContexts()])
if (cancelled) return
setServer(result)
+ setContextNames(
+ contextNamesForConnector((contextsResult.items ?? []) as ContextResource[], name)
+ )
setEgressBindings((result.spec?.egressBindings as EgressBinding[] | undefined) ?? undefined)
} catch (error) {
if (!cancelled) {
@@ -142,11 +164,8 @@ export default function EditMcpServerPage() {
}
}, [name])
- const contextRef =
- typeof server?.spec?.contextRef === 'string' ? server.spec.contextRef.trim() : ''
-
useEffect(() => {
- if (!contextRef) {
+ if (contextNames.length === 0) {
setContextAccess(EMPTY_CONTEXT_ACCESS)
setContextAccessError('')
setLoadingContextAccess(false)
@@ -158,39 +177,60 @@ export default function EditMcpServerPage() {
setContextAccessError('')
void (async () => {
- const [usersResult, teamsResult, hostsResult] = await Promise.allSettled([
- getContextUsers(contextRef),
- getContextTeams(contextRef),
- getHosts(),
+ const [hostsResults, contextResults] = await Promise.all([
+ Promise.allSettled([getHosts()]),
+ Promise.all(
+ contextNames.map(async contextName => {
+ const [usersResult, teamsResult] = await Promise.allSettled([
+ getContextUsers(contextName),
+ getContextTeams(contextName),
+ ])
+ return { contextName, usersResult, teamsResult }
+ })
+ ),
])
if (cancelled) return
+ const hostsResult = hostsResults[0]
const failed =
- usersResult.status === 'rejected' ||
- teamsResult.status === 'rejected' ||
- hostsResult.status === 'rejected'
- setContextAccess({
- users:
- usersResult.status === 'fulfilled'
- ? (usersResult.value.items ?? []).map(user => ({
- id: user.id,
- label: user.displayName || user.name || user.email || user.id,
- }))
- : [],
- teams:
- teamsResult.status === 'fulfilled'
- ? (teamsResult.value.items ?? []).map(team => ({ id: team.id, label: team.name }))
- : [],
- agents:
- hostsResult.status === 'fulfilled'
- ? (hostsResult.value.items ?? [])
- .filter(host => String(host.spec?.contextRef ?? '').trim() === contextRef)
+ hostsResult.status === 'rejected' ||
+ contextResults.some(
+ result =>
+ result.usersResult.status === 'rejected' || result.teamsResult.status === 'rejected'
+ )
+ const hosts = hostsResult.status === 'fulfilled' ? (hostsResult.value.items ?? []) : []
+ setContextAccess(
+ mergeAccessSummaries(
+ contextResults.map(({ contextName, usersResult, teamsResult }) => ({
+ users:
+ usersResult.status === 'fulfilled'
+ ? sortAccessPrincipals(
+ (usersResult.value.items ?? []).map(user => ({
+ id: user.id,
+ label: user.displayName || user.name || user.email || user.id,
+ }))
+ )
+ : [],
+ teams:
+ teamsResult.status === 'fulfilled'
+ ? sortAccessPrincipals(
+ (teamsResult.value.items ?? []).map(team => ({
+ id: team.id,
+ label: team.name || team.id,
+ }))
+ )
+ : [],
+ agents: sortAccessPrincipals(
+ hosts
+ .filter(host => String(host.spec?.contextRef ?? '').trim() === contextName)
.map(host => {
const agentName = host.metadata?.name || 'unknown'
return { id: agentName, label: getAgentDisplayName(agentName) || agentName }
})
- : [],
- })
+ ),
+ }))
+ )
+ )
setContextAccessError(
failed
? 'Some access information could not be loaded. The lists below may be incomplete.'
@@ -202,7 +242,7 @@ export default function EditMcpServerPage() {
return () => {
cancelled = true
}
- }, [contextRef])
+ }, [contextNames])
async function handleSave(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault()
@@ -308,16 +348,18 @@ export default function EditMcpServerPage() {
Context access
</h2>
<p className="cu-form-section__description">
- This connector is available in the context shown below. Context assignments
- cannot be changed here yet.
+ This connector is available in the contexts shown below. Context assignments
+ are derived from the current Context allowlists and cannot be changed here
+ yet.
</p>
</div>
- <p className="cu-connector-edit-context-name" aria-label="Connector context">
- Context: <strong>{contextRef || 'No context assigned'}</strong>
+ <p className="cu-connector-edit-context-name" aria-label="Connector contexts">
+ Contexts:{' '}
+ <strong>{contextNames.length > 0 ? contextNames.join(', ') : 'None'}</strong>
</p>
- {contextRef ? (
+ {contextNames.length > 0 ? (
loadingContextAccess ? (
<p className="cu-muted">Loading context access…</p>
) : (
@@ -370,10 +412,7 @@ export default function EditMcpServerPage() {
<code>{typeof server.spec?.image === 'string' ? server.spec.image : '-'}</code>
</div>
<div>
- <strong>Context:</strong>{' '}
- <code>
- {typeof server.spec?.contextRef === 'string' ? server.spec.contextRef : '-'}
- </code>
+ <strong>Contexts:</strong> <code>{contextNames.join(', ') || '-'}</code>
</div>
</div>
diff --git a/control-ui/app/mcp-servers/page.tsx b/control-ui/app/mcp-servers/page.tsx
index 09a6f1929..83298079b 100644
--- a/control-ui/app/mcp-servers/page.tsx
+++ b/control-ui/app/mcp-servers/page.tsx
@@ -23,6 +23,12 @@ import {
updateContext,
} from '../../lib/api'
import type { ContextResource, ContextSpec, HostResource, McpServerResource } from '../../lib/api'
+import {
+ contextNamesForConnector,
+ mergeAccessSummaries,
+ sortAccessPrincipals,
+} from '../../lib/connectorAccess'
+import { buildContextUpdatePayload, contextMutationError } from '../../lib/contextMutation'
function resourceName(resource: { metadata?: { name?: string } }): string {
return resource.metadata?.name || 'unknown'
@@ -41,25 +47,8 @@ function getContextRef(resource: { spec?: Record<string, unknown> }): string {
return typeof contextRef === 'string' ? contextRef.trim() : ''
}
-function sortPrincipals(items: ConnectorAccessPrincipal[]): ConnectorAccessPrincipal[] {
- return [...items].sort((a, b) => a.label.localeCompare(b.label))
-}
-
-function mergeAccessSummaries(summaries: ConnectorAccessSummary[]): ConnectorAccessSummary {
- const mergeGroup = (group: keyof ConnectorAccessSummary) => {
- const items = summaries.flatMap(summary => summary[group])
- return sortPrincipals(Array.from(new Map(items.map(item => [item.id, item] as const)).values()))
- }
-
- return {
- agents: mergeGroup('agents'),
- users: mergeGroup('users'),
- teams: mergeGroup('teams'),
- }
-}
-
function agentsForContext(hosts: HostResource[], contextRef: string): ConnectorAccessPrincipal[] {
- return sortPrincipals(
+ return sortAccessPrincipals(
hosts
.filter(host => getContextRef(host) === contextRef)
.map(host => {
@@ -86,7 +75,7 @@ async function loadContextAccess(
}
const users =
usersResult.status === 'fulfilled'
- ? sortPrincipals(
+ ? sortAccessPrincipals(
(usersResult.value.items ?? []).map(user => ({
id: user.id,
label: user.displayName || user.name || user.email || user.id,
@@ -95,7 +84,7 @@ async function loadContextAccess(
: []
const teams =
teamsResult.status === 'fulfilled'
- ? sortPrincipals(
+ ? sortAccessPrincipals(
(teamsResult.value.items ?? []).map(team => ({
id: team.id,
label: team.name || team.id,
@@ -142,12 +131,11 @@ export default function McpServersPage() {
const hosts = (hostsResult.items || []) as HostResource[]
const nextContexts = (contextsResult.items || []) as ContextResource[]
const contextRefs = [
- ...new Set([
- ...connectors.map(connector => getContextRef(connector)).filter(Boolean),
- ...nextContexts
+ ...new Set(
+ nextContexts
.map(context => String(context.metadata?.name || context.spec?.contextId || '').trim())
- .filter(Boolean),
- ]),
+ .filter(Boolean)
+ ),
]
const accessResults = await Promise.all(
contextRefs.map(
@@ -166,19 +154,10 @@ export default function McpServersPage() {
const nextAccessByConnectorKey = connectors.reduce<ConnectorAccessSummaryMap>(
(acc, connector) => {
const connectorName = resourceName(connector)
- const connectorContexts = new Set(
- [
- getContextRef(connector),
- ...nextContexts
- .filter(context => context.spec?.mcpServers?.includes(connectorName))
- .map(context =>
- String(context.metadata?.name || context.spec?.contextId || '').trim()
- ),
- ].filter(Boolean)
- )
- if (connectorContexts.size > 0) {
+ const connectorContexts = contextNamesForConnector(nextContexts, connectorName)
+ if (connectorContexts.length > 0) {
acc[connectorKey(connector)] = mergeAccessSummaries(
- [...connectorContexts].map(
+ connectorContexts.map(
contextRef =>
accessByContext.get(contextRef) ?? { agents: [], users: [], teams: [] }
)
@@ -260,12 +239,13 @@ export default function McpServersPage() {
targets.map(context => {
const name = contextName(context)
const spec = contextSpec(context)
- return updateContext(name, {
- spec: {
+ return updateContext(
+ name,
+ buildContextUpdatePayload(context.metadata?.resourceVersion, {
...spec,
mcpServers: Array.from(new Set([...spec.mcpServers, server.name])),
- },
- })
+ })
+ )
})
)
await loadAll()
@@ -277,7 +257,7 @@ export default function McpServersPage() {
)
} catch (e) {
if (isSilentApiError(e)) return
- setError(e instanceof Error ? e.message : `Failed to add ${server.name} to contexts`)
+ setError(contextMutationError(e, `Failed to add ${server.name} to contexts`))
} finally {
setUpdatingContextMembershipKey(null)
}
@@ -298,17 +278,18 @@ export default function McpServersPage() {
setError('')
try {
const spec = contextSpec(target)
- await updateContext(targetContextName, {
- spec: {
+ await updateContext(
+ targetContextName,
+ buildContextUpdatePayload(target.metadata?.resourceVersion, {
...spec,
mcpServers: spec.mcpServers.filter(name => name !== server.name),
- },
- })
+ })
+ )
await loadAll()
showToast(`Connector ${server.name} removed from ${targetContextName}.`, { tone: 'success' })
} catch (e) {
if (isSilentApiError(e)) return
- setError(e instanceof Error ? e.message : `Failed to remove ${server.name} from context`)
+ setError(contextMutationError(e, `Failed to remove ${server.name} from context`))
} finally {
setUpdatingContextMembershipKey(null)
}
diff --git a/control-ui/components/CreateMcpServerForm/index.tsx b/control-ui/components/CreateMcpServerForm/index.tsx
index 04fad6444..2694cbe58 100644
--- a/control-ui/components/CreateMcpServerForm/index.tsx
+++ b/control-ui/components/CreateMcpServerForm/index.tsx
@@ -7,6 +7,7 @@ import { SelectionDropdown } from '@/components/SelectionDropdown'
import { useToast } from '@/components/Toast'
import { IconX } from '@/components/icons'
import { Button, Field, FormSection, SelectInput, TextInput } from '@/components/ui'
+import { getAgentDisplayName } from '@/lib/agentName'
import {
createMcpSecret,
createMcpServer,
@@ -21,8 +22,8 @@ import {
} from '@/lib/api'
import type { EnvSecretKeyMapping, EnvVar, OrgImage } from '@/lib/api'
import type { EgressBinding } from '@/lib/api'
+import { buildContextUpdatePayload } from '@/lib/contextMutation'
import type { EgressEditorStatus } from '@/lib/egressModel'
-import { getAgentDisplayName } from '@/lib/agentName'
import { EgressEditor } from '../EgressEditor'
import { DEFAULT_REGISTRY_HOST, buildImageCoordinate } from '../PublisherView/dockerCredential'
import { MCP_SERVER_NAME_PATTERN, TRANSPORT_TYPES } from './constants'
@@ -242,8 +243,7 @@ export function CreateMcpServerForm({
!submitting
const connectorComplete = Boolean(name && image && nameValid) && egressValid
const contextComplete = Boolean(contextRef)
- const canContinue =
- step === 0 ? connectorComplete : step === 1 ? contextComplete : egressValid
+ const canContinue = step === 0 ? connectorComplete : step === 1 ? contextComplete : egressValid
const contextOptions = useMemo(
() => contexts.map(context => ({ value: context.name, label: context.name })),
[contexts]
@@ -347,7 +347,9 @@ export function CreateMcpServerForm({
: [],
})
setContextAccessError(
- failed ? 'Some access information could not be loaded. The lists below may be incomplete.' : ''
+ failed
+ ? 'Some access information could not be loaded. The lists below may be incomplete.'
+ : ''
)
setLoadingContextAccess(false)
})()
@@ -547,13 +549,15 @@ export function CreateMcpServerForm({
const existingServers = context.spec?.mcpServers ?? []
if (!existingServers.includes(name)) {
- await updateContext(contextRef, {
- spec: {
+ await updateContext(
+ contextRef,
+ buildContextUpdatePayload(context.metadata?.resourceVersion, {
contextId: context.spec?.contextId ?? contextRef,
description: context.spec?.description,
mcpServers: [...existingServers, name],
- },
- })
+ sharedFileSystems: context.spec?.sharedFileSystems ?? [],
+ })
+ )
}
} catch (contextError) {
setError(
@@ -836,9 +840,7 @@ export function CreateMcpServerForm({
))}
</ul>
) : (
- <p className="cu-muted">
- No {group.title.toLowerCase()} have access.
- </p>
+ <p className="cu-muted">No {group.title.toLowerCase()} have access.</p>
)}
</section>
))}
diff --git a/control-ui/components/EgressEditor.tsx b/control-ui/components/EgressEditor.tsx
index 9d15c652a..c30d91f75 100644
--- a/control-ui/components/EgressEditor.tsx
+++ b/control-ui/components/EgressEditor.tsx
@@ -67,9 +67,14 @@ export function EgressEditor({
<FormSection description={description} title={title}>
<Field
description="Default is closed. Choose exact-host for known APIs or public-web only when hosts are not deterministic."
+ htmlFor="egress-mode"
label="Egress mode"
>
- <SelectInput onChange={event => setMode(event.target.value as EgressMode)} value={mode}>
+ <SelectInput
+ id="egress-mode"
+ onChange={event => setMode(event.target.value as EgressMode)}
+ value={mode}
+ >
<option value="none">No external egress (closed by default)</option>
<option value="exact-host">Exact-host egress</option>
{allowCidr ? <option value="exact-cidr">Exact-CIDR/IP egress</option> : null}
diff --git a/control-ui/components/McpServerTable.tsx b/control-ui/components/McpServerTable.tsx
index 2e61e62c9..93627290b 100644
--- a/control-ui/components/McpServerTable.tsx
+++ b/control-ui/components/McpServerTable.tsx
@@ -134,7 +134,6 @@ function AccessSummary({ summary }: { summary?: ConnectorAccessSummary }) {
function ConnectorContexts({
connectorName,
namespace,
- contextRef,
contexts,
busy,
onOpenContext,
@@ -143,27 +142,13 @@ function ConnectorContexts({
}: {
connectorName: string
namespace: string
- contextRef: string
contexts: ConnectorContextBinding[]
busy: boolean
onOpenContext?: (contextName: string) => void
onAdd?: () => void
onRemove?: McpServerTableProps['onRemoveFromContext']
}) {
- const assignedNames = new Set(contexts.map(context => context.name))
- const linkedContexts = [
- ...(contextRef
- ? [
- {
- name: contextRef,
- removable: assignedNames.has(contextRef),
- },
- ]
- : []),
- ...contexts
- .filter(context => context.name !== contextRef)
- .map(context => ({ name: context.name, removable: true })),
- ]
+ const linkedContexts = contexts.map(context => ({ name: context.name, removable: true }))
return (
<section className="cu-registry-context-access__group" data-kind="contexts">
@@ -324,7 +309,6 @@ export function McpServerTable({
namespace,
name,
spec.image,
- spec.contextRef,
spec.description,
spec.transport?.type,
spec.transport?.url,
@@ -509,7 +493,6 @@ export function McpServerTable({
{filteredRows.map(({ key, namespace, name, item }) => {
const spec = item.spec || {}
const expanded = expandedKeys.has(key)
- const contextRef = spec.contextRef || ''
const assignedContexts = contextsForConnector(name)
const contextMembershipBusy = updatingContextMembershipKey === key
return (
@@ -635,7 +618,6 @@ export function McpServerTable({
<ConnectorContexts
connectorName={name}
namespace={namespace}
- contextRef={contextRef}
contexts={assignedContexts}
busy={contextMembershipBusy}
onOpenContext={onOpenContext}
diff --git a/control-ui/components/__tests__/ConnectorEditContext.test.tsx b/control-ui/components/__tests__/ConnectorEditContext.test.tsx
new file mode 100644
index 000000000..02ac002f8
--- /dev/null
+++ b/control-ui/components/__tests__/ConnectorEditContext.test.tsx
@@ -0,0 +1,69 @@
+import type { ReactNode } from 'react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import EditMcpServerPage from '../../app/mcp-servers/[name]/edit/page'
+import * as api from '../../lib/api'
+
+const replace = vi.fn()
+const push = vi.fn()
+
+vi.mock('next/navigation', () => ({
+ useParams: () => ({ name: 'search', tab: 'context' }),
+ useRouter: () => ({ push, replace }),
+}))
+
+vi.mock('@components/AuthGate', () => ({
+ AuthGate: ({ children }: { children: ReactNode }) => children,
+}))
+
+vi.mock('@components/DashboardLayout', () => ({
+ DashboardLayout: ({ children }: { children: ReactNode }) => children,
+}))
+
+vi.mock('@components/Toast', () => ({
+ useToast: () => ({ showToast: vi.fn() }),
+}))
+
+vi.mock('../../lib/api', async importOriginal => {
+ const actual = await importOriginal<typeof import('../../lib/api')>()
+ return {
+ ...actual,
+ getContexts: vi.fn(),
+ getContextTeams: vi.fn(),
+ getContextUsers: vi.fn(),
+ getHosts: vi.fn(),
+ getMcpServer: vi.fn(),
+ updateMcpServer: vi.fn(),
+ }
+})
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+})
+
+describe('connector edit Context access', () => {
+ it('does not expose a stale legacy contextRef after allowlist membership is removed', async () => {
+ vi.mocked(api.getMcpServer).mockResolvedValue({
+ metadata: { name: 'search' },
+ spec: { contextRef: 'removed-context', image: 'example/search:latest' },
+ })
+ vi.mocked(api.getContexts).mockResolvedValue({
+ items: [
+ {
+ metadata: { name: 'removed-context', resourceVersion: 'rv-2' },
+ spec: { contextId: 'removed-context', mcpServers: [] },
+ },
+ ],
+ })
+
+ render(<EditMcpServerPage />)
+
+ expect(await screen.findByLabelText('Connector contexts')).toHaveTextContent('Contexts: None')
+ expect(screen.queryByText('removed-context')).not.toBeInTheDocument()
+ await waitFor(() => expect(api.getMcpServer).toHaveBeenCalledWith('search'))
+ expect(api.getContextUsers).not.toHaveBeenCalled()
+ expect(api.getContextTeams).not.toHaveBeenCalled()
+ expect(api.getHosts).not.toHaveBeenCalled()
+ })
+})
diff --git a/control-ui/components/__tests__/CreateMcpServerForm.test.tsx b/control-ui/components/__tests__/CreateMcpServerForm.test.tsx
index 2de342aba..e09212d36 100644
--- a/control-ui/components/__tests__/CreateMcpServerForm.test.tsx
+++ b/control-ui/components/__tests__/CreateMcpServerForm.test.tsx
@@ -12,11 +12,18 @@ vi.mock('../../lib/api', () => ({
deleteMcpSecret: vi.fn().mockResolvedValue({ name: 'test-credentials' }),
getContexts: vi.fn().mockResolvedValue({
items: [
- { metadata: { name: 'context1' }, spec: { contextId: 'context1', mcpServers: [] } },
- { metadata: { name: 'research' }, spec: { contextId: 'research', mcpServers: [] } },
+ {
+ metadata: { name: 'context1', resourceVersion: 'rv-context1' },
+ spec: { contextId: 'context1', mcpServers: [] },
+ },
+ {
+ metadata: { name: 'research', resourceVersion: 'rv-research' },
+ spec: { contextId: 'research', mcpServers: [] },
+ },
],
}),
getContext: vi.fn().mockResolvedValue({
+ metadata: { name: 'context1', resourceVersion: 'rv-context1' },
spec: { contextId: 'context1', mcpServers: [] },
}),
getContextTeams: vi.fn().mockResolvedValue({ items: [] }),
@@ -87,7 +94,9 @@ describe('CreateMcpServerForm — render', () => {
await fillIdentity()
fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
- await waitFor(() => expect(screen.getByRole('heading', { name: 'Context access' })).toBeInTheDocument())
+ await waitFor(() =>
+ expect(screen.getByRole('heading', { name: 'Context access' })).toBeInTheDocument()
+ )
const contextSelector = screen.getByRole('button', { name: 'context1' })
fireEvent.click(contextSelector)
@@ -305,6 +314,7 @@ describe('CreateMcpServerForm — submit', () => {
const updateCall = (api.updateContext as ReturnType<typeof vi.fn>).mock.calls[0]
expect(updateCall[0]).toBe('context1')
expect(updateCall[1]).toMatchObject({
+ metadata: { resourceVersion: 'rv-context1' },
spec: { contextId: 'context1', mcpServers: ['brave-search'] },
})
diff --git a/control-ui/components/__tests__/LlmDiscoveryPanel.test.tsx b/control-ui/components/__tests__/LlmDiscoveryPanel.test.tsx
index cd5bd4298..d6c962902 100644
--- a/control-ui/components/__tests__/LlmDiscoveryPanel.test.tsx
+++ b/control-ui/components/__tests__/LlmDiscoveryPanel.test.tsx
@@ -146,7 +146,7 @@ describe('LlmDiscoveryPanel merged lifecycle workflow', () => {
resolveInitialStatus({
ranAt: '2026-07-01T00:00:00.000Z',
- source: 'fallback',
+ source: 'vendored',
added: 99,
updated: 99,
staled: 99,
diff --git a/control-ui/components/__tests__/McpServerTable.test.tsx b/control-ui/components/__tests__/McpServerTable.test.tsx
index d0add8a3b..7cd1ecc0f 100644
--- a/control-ui/components/__tests__/McpServerTable.test.tsx
+++ b/control-ui/components/__tests__/McpServerTable.test.tsx
@@ -360,6 +360,27 @@ describe('McpServerTable — connector access summaries', () => {
})
describe('McpServerTable — context membership', () => {
+ it('does not display a stale legacy contextRef without authoritative allowlist membership', () => {
+ render(
+ <McpServerTable
+ items={[makeItem({ name: 'airtable-server', contextRef: 'removed-context' })]}
+ contexts={[
+ { name: 'removed-context', mcpServers: [] },
+ { name: 'active-context', mcpServers: ['another-server'] },
+ ]}
+ accessByConnectorKey={{}}
+ />
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'Expand connector airtable-server' }))
+
+ expect(screen.queryByText('removed-context')).not.toBeInTheDocument()
+ expect(screen.getByText('No contexts linked.')).toBeInTheDocument()
+ expect(screen.getByText('No agents have access.')).toBeInTheDocument()
+ expect(screen.getByText('No teams have access.')).toBeInTheDocument()
+ expect(screen.getByText('No users have access.')).toBeInTheDocument()
+ })
+
it('shows attached contexts and lets an operator remove the connector from one', async () => {
const onRemoveFromContext = vi.fn().mockResolvedValue(undefined)
const items = [makeItem({ name: 'airtable-server' })]
diff --git a/control-ui/e2e/registry-install.spec.ts b/control-ui/e2e/registry-install.spec.ts
index 923be5309..07db3b404 100644
--- a/control-ui/e2e/registry-install.spec.ts
+++ b/control-ui/e2e/registry-install.spec.ts
@@ -561,7 +561,9 @@ async function submitRegistryInstallForm(
await credentialInputs.nth(i).fill('e2e-test-value')
}
await installForm.getByRole('button', { name: 'Continue' }).click()
- await expect(page.getByLabel('Install summary').getByText(serverName, { exact: true })).toBeVisible({
+ await expect(
+ page.getByLabel('Install summary').getByText(serverName, { exact: true })
+ ).toBeVisible({
timeout: 10_000,
})
const responsePromise = page.waitForResponse(
@@ -1552,7 +1554,7 @@ test.describe('I. Registry Egress Contracts via Control UI', () => {
await openRegistryInstallPackage(page, exactEntryName)
const installForm = await continueToRegistryInstallForm(page)
await expect(installForm.getByText('External Egress')).toBeVisible()
- await expect(installForm.getByDisplayValue('Exact-host egress')).toBeVisible()
+ await expect(installForm.getByLabel('Egress mode')).toHaveValue('exact-host')
await submitRegistryInstallForm(page, installForm, exactServerName, exactEntryName)
@@ -1574,8 +1576,10 @@ test.describe('I. Registry Egress Contracts via Control UI', () => {
await login(page)
await openRegistryInstallPackage(page, publicEntryName)
const installForm = await continueToRegistryInstallForm(page)
- await expect(installForm.getByDisplayValue('Public web egress')).toBeVisible()
- await expect(installForm.getByText(/Public web egress allows outbound TCP 80\/443/i)).toBeVisible()
+ await expect(installForm.getByLabel('Egress mode')).toHaveValue('public-web')
+ await expect(
+ installForm.getByText(/Public web egress allows outbound TCP 80\/443/i)
+ ).toBeVisible()
await submitRegistryInstallForm(page, installForm, publicServerName, publicEntryName)
diff --git a/control-ui/lib/__tests__/connectorAccess.test.ts b/control-ui/lib/__tests__/connectorAccess.test.ts
new file mode 100644
index 000000000..9907cf676
--- /dev/null
+++ b/control-ui/lib/__tests__/connectorAccess.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest'
+import type { ConnectorAccessSummary } from '../../components/McpServerTable.types'
+import { contextNamesForConnector, mergeAccessSummaries } from '../connectorAccess'
+
+function permutations<T>(items: readonly T[]): T[][] {
+ if (items.length <= 1) return [[...items]]
+ return items.flatMap((item, index) =>
+ permutations([...items.slice(0, index), ...items.slice(index + 1)]).map(rest => [item, ...rest])
+ )
+}
+
+describe('mergeAccessSummaries invariants', () => {
+ const summaries: ConnectorAccessSummary[] = [
+ {
+ agents: [{ id: 'agent-b', label: 'Beta' }],
+ teams: [{ id: 'team-1', label: 'Platform' }],
+ users: [{ id: 'user-1', label: 'Grace' }],
+ },
+ {
+ agents: [
+ { id: 'agent-a', label: 'Alpha' },
+ { id: 'agent-b', label: 'Beta duplicate' },
+ ],
+ teams: [{ id: 'team-2', label: 'Research' }],
+ users: [{ id: 'user-2', label: 'Ada' }],
+ },
+ {
+ agents: [],
+ teams: [{ id: 'team-1', label: 'Platform duplicate' }],
+ users: [{ id: 'user-1', label: 'Grace duplicate' }],
+ },
+ ]
+
+ it('preserves every principal id exactly once and orders each group deterministically', () => {
+ const merged = mergeAccessSummaries(summaries)
+
+ expect(merged.agents.map(item => item.id)).toEqual(['agent-a', 'agent-b'])
+ expect(merged.teams.map(item => item.id)).toEqual(['team-1', 'team-2'])
+ expect(merged.users.map(item => item.id)).toEqual(['user-2', 'user-1'])
+ for (const group of Object.values(merged)) {
+ expect(new Set(group.map(item => item.id)).size).toBe(group.length)
+ }
+ })
+
+ it('is stable across input permutations and idempotent after reconciliation', () => {
+ const expected = mergeAccessSummaries(summaries)
+ for (const order of permutations(summaries)) {
+ expect(mergeAccessSummaries(order)).toEqual(expected)
+ }
+ expect(mergeAccessSummaries([expected, expected])).toEqual(expected)
+ })
+})
+
+describe('contextNamesForConnector invariants', () => {
+ const contexts = [
+ {
+ metadata: { name: 'zeta' },
+ spec: { contextId: 'zeta', mcpServers: ['search'] },
+ },
+ {
+ metadata: { name: 'alpha' },
+ spec: { contextId: 'alpha', mcpServers: ['search', 'other'] },
+ },
+ {
+ metadata: { name: 'unused' },
+ spec: { contextId: 'unused', mcpServers: [] },
+ },
+ ]
+
+ it('is unique, sorted, permutation-stable, and ignores legacy connector contextRef state', () => {
+ const expected = ['alpha', 'zeta']
+ for (const order of permutations(contexts)) {
+ expect(contextNamesForConnector(order, 'search')).toEqual(expected)
+ }
+ expect(contextNamesForConnector(contexts, 'removed-from-all-contexts')).toEqual([])
+ })
+})
diff --git a/control-ui/lib/__tests__/contextMutation.test.ts b/control-ui/lib/__tests__/contextMutation.test.ts
new file mode 100644
index 000000000..bd6294b69
--- /dev/null
+++ b/control-ui/lib/__tests__/contextMutation.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest'
+import { buildContextUpdatePayload, contextMutationError } from '../contextMutation'
+
+const spec = {
+ contextId: 'research',
+ description: 'Research tools',
+ mcpServers: ['search'],
+ sharedFileSystems: [],
+}
+
+describe('Context optimistic concurrency payloads', () => {
+ it('carries the resourceVersion from the read into the complete replacement', () => {
+ expect(buildContextUpdatePayload('rv-read', spec)).toEqual({
+ metadata: { resourceVersion: 'rv-read' },
+ spec,
+ })
+ })
+
+ it('fails closed when a read has no resourceVersion', () => {
+ expect(() => buildContextUpdatePayload(undefined, spec)).toThrow(/version is unavailable/i)
+ })
+
+ it('surfaces a stale-writer conflict instead of reporting a successful mutation', () => {
+ const staleWrite = Object.assign(new Error('409 conflict'), { status: 409 })
+ expect(contextMutationError(staleWrite, 'Failed to update connectors')).toMatch(
+ /changed since it was loaded/i
+ )
+ })
+})
diff --git a/control-ui/lib/__tests__/llmProjection.test.ts b/control-ui/lib/__tests__/llmProjection.test.ts
index 7d91d647f..44460367e 100644
--- a/control-ui/lib/__tests__/llmProjection.test.ts
+++ b/control-ui/lib/__tests__/llmProjection.test.ts
@@ -20,6 +20,21 @@ describe('getProvidersWithCompleteCredentials', () => {
it('does not identify a provider with only part of its credential group', () => {
expect(getProvidersWithCompleteCredentials(['aws-access-key-id'])).toEqual([])
})
+
+ it('is unique and stable under duplicate, unknown, and permuted key input', () => {
+ const keys = [
+ 'aws-secret-access-key',
+ 'unknown-key',
+ 'openai-api-key',
+ 'aws-access-key-id',
+ 'openai-api-key',
+ ]
+ const expected = getProvidersWithCompleteCredentials(keys)
+
+ expect(expected).toEqual(['openai', 'bedrock'])
+ expect(new Set(expected).size).toBe(expected.length)
+ expect(getProvidersWithCompleteCredentials([...keys].reverse())).toEqual(expected)
+ })
})
describe('getActiveCredentialKeys (spec Topic 1b — provider-domain projection)', () => {
diff --git a/control-ui/lib/__tests__/registryCredentialDraft.test.ts b/control-ui/lib/__tests__/registryCredentialDraft.test.ts
index ce80a9b8a..52a3b4eb5 100644
--- a/control-ui/lib/__tests__/registryCredentialDraft.test.ts
+++ b/control-ui/lib/__tests__/registryCredentialDraft.test.ts
@@ -55,4 +55,40 @@ describe('registry credential drafts', () => {
expect(areRequiredCredentialRowsComplete(rows, schemaKeys)).toBe(true)
expect(areRequiredCredentialRowsComplete(rows.slice(0, 1), schemaKeys)).toBe(false)
})
+
+ it('is idempotent, unique by schema key, and preserves bound values', () => {
+ const current = [
+ { id: 'secret', secretKey: 'CLIENT_SECRET', value: 'secret-456' },
+ { id: 'client', secretKey: 'CLIENT_ID', value: 'client-123' },
+ { id: 'duplicate-client', secretKey: 'CLIENT_ID', value: 'ignored-duplicate' },
+ { id: 'extra', secretKey: 'OPTIONAL_SCOPE', value: 'read' },
+ ]
+ const reconciled = reconcileCredentialRows(current, schemaKeys)
+
+ expect(reconciled.map(row => row.secretKey)).toEqual([
+ 'CLIENT_ID',
+ 'CLIENT_SECRET',
+ 'OPTIONAL_SCOPE',
+ ])
+ expect(reconciled.find(row => row.secretKey === 'CLIENT_ID')?.value).toBe('client-123')
+ expect(reconcileCredentialRows(reconciled, schemaKeys)).toEqual(reconciled)
+ })
+
+ it('is stable across permutations of uniquely bound schema rows', () => {
+ const client = { id: 'client', secretKey: 'CLIENT_ID', value: 'client-123' }
+ const secret = { id: 'secret', secretKey: 'CLIENT_SECRET', value: 'secret-456' }
+
+ expect(reconcileCredentialRows([client, secret], schemaKeys)).toEqual(
+ reconcileCredentialRows([secret, client], schemaKeys)
+ )
+ })
+
+ it('required completeness is stable under duplicate and reordered input rows', () => {
+ const complete = [
+ { id: 'client', secretKey: 'CLIENT_ID', value: 'client-123' },
+ { id: 'secret', secretKey: 'CLIENT_SECRET', value: 'secret-456' },
+ ]
+ expect(areRequiredCredentialRowsComplete([...complete].reverse(), schemaKeys)).toBe(true)
+ expect(areRequiredCredentialRowsComplete([...complete, complete[0]], schemaKeys)).toBe(true)
+ })
})
diff --git a/control-ui/lib/__tests__/tableSort.test.ts b/control-ui/lib/__tests__/tableSort.test.ts
new file mode 100644
index 000000000..e236bb941
--- /dev/null
+++ b/control-ui/lib/__tests__/tableSort.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest'
+import { compareNullsLast } from '../tableSort'
+
+function permutations<T>(items: readonly T[]): T[][] {
+ if (items.length <= 1) return [[...items]]
+ return items.flatMap((item, index) =>
+ permutations([...items.slice(0, index), ...items.slice(index + 1)]).map(rest => [item, ...rest])
+ )
+}
+
+function sortNumbersNullLast(values: Array<number | null | undefined>, direction: 'asc' | 'desc') {
+ const multiplier = direction === 'asc' ? 1 : -1
+ return [...values].sort((left, right) => {
+ const nullOrder = compareNullsLast(left, right)
+ return nullOrder ?? ((left as number) - (right as number)) * multiplier
+ })
+}
+
+describe('compareNullsLast invariants', () => {
+ const values = [7, null, 2, undefined, 5]
+
+ it('keeps nullish values last in both directions without losing values', () => {
+ expect(sortNumbersNullLast(values, 'asc')).toEqual([2, 5, 7, null, undefined])
+ expect(sortNumbersNullLast(values, 'desc')).toEqual([7, 5, 2, null, undefined])
+ })
+
+ it('produces the same ordered non-null projection for every input permutation', () => {
+ for (const order of permutations([7, null, 2, 5])) {
+ expect(sortNumbersNullLast(order, 'asc')).toEqual([2, 5, 7, null])
+ expect(sortNumbersNullLast(order, 'desc')).toEqual([7, 5, 2, null])
+ }
+ })
+
+ it('is antisymmetric for null ordering and neutral for two nullish values', () => {
+ expect(compareNullsLast(null, 1)).toBe(-compareNullsLast(1, null)!)
+ expect(compareNullsLast(null, undefined)).toBe(0)
+ expect(compareNullsLast(1, 2)).toBeNull()
+ })
+})
diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.ts
index cc61cf0da..664044b0e 100644
--- a/control-ui/lib/api.ts
+++ b/control-ui/lib/api.ts
@@ -1018,7 +1018,10 @@ export async function createContext(payload: { metadata: { name: string }; spec:
return apiSend('POST', '/api/v1/admin/contexts', payload) as Promise<ContextResource>
}
-export async function updateContext(name: string, payload: { spec: ContextSpec }) {
+export async function updateContext(
+ name: string,
+ payload: { metadata: { resourceVersion: string }; spec: ContextSpec }
+) {
return apiSend(
'PUT',
`/api/v1/admin/contexts/${encodeURIComponent(name)}`,
diff --git a/control-ui/lib/connectorAccess.ts b/control-ui/lib/connectorAccess.ts
new file mode 100644
index 000000000..56da1794f
--- /dev/null
+++ b/control-ui/lib/connectorAccess.ts
@@ -0,0 +1,51 @@
+import type {
+ ConnectorAccessPrincipal,
+ ConnectorAccessSummary,
+} from '../components/McpServerTable.types'
+import type { ContextResource } from './api'
+
+function comparePrincipals(
+ left: ConnectorAccessPrincipal,
+ right: ConnectorAccessPrincipal
+): number {
+ return left.label.localeCompare(right.label) || left.id.localeCompare(right.id)
+}
+
+export function sortAccessPrincipals(
+ items: readonly ConnectorAccessPrincipal[]
+): ConnectorAccessPrincipal[] {
+ return [...items].sort(comparePrincipals)
+}
+
+export function mergeAccessSummaries(
+ summaries: readonly ConnectorAccessSummary[]
+): ConnectorAccessSummary {
+ const mergeGroup = (group: keyof ConnectorAccessSummary): ConnectorAccessPrincipal[] => {
+ const byId = new Map<string, ConnectorAccessPrincipal>()
+ for (const principal of summaries.flatMap(summary => summary[group])) {
+ const current = byId.get(principal.id)
+ if (!current || comparePrincipals(principal, current) < 0) byId.set(principal.id, principal)
+ }
+ return sortAccessPrincipals([...byId.values()])
+ }
+
+ return {
+ agents: mergeGroup('agents'),
+ users: mergeGroup('users'),
+ teams: mergeGroup('teams'),
+ }
+}
+
+export function contextNamesForConnector(
+ contexts: readonly ContextResource[],
+ connectorName: string
+): string[] {
+ return Array.from(
+ new Set(
+ contexts
+ .filter(context => context.spec?.mcpServers?.includes(connectorName))
+ .map(context => String(context.metadata?.name || context.spec?.contextId || '').trim())
+ .filter(Boolean)
+ )
+ ).sort((left, right) => left.localeCompare(right))
+}
diff --git a/control-ui/lib/contextMutation.ts b/control-ui/lib/contextMutation.ts
new file mode 100644
index 000000000..1b6eba4ae
--- /dev/null
+++ b/control-ui/lib/contextMutation.ts
@@ -0,0 +1,24 @@
+import type { ContextSpec } from './api'
+
+export type ContextUpdatePayload = {
+ metadata: { resourceVersion: string }
+ spec: ContextSpec
+}
+
+export function buildContextUpdatePayload(
+ resourceVersion: string | undefined,
+ spec: ContextSpec
+): ContextUpdatePayload {
+ const version = resourceVersion?.trim()
+ if (!version) {
+ throw new Error('Context version is unavailable. Reload before changing membership.')
+ }
+ return { metadata: { resourceVersion: version }, spec }
+}
+
+export function contextMutationError(error: unknown, fallback: string): string {
+ if ((error as { status?: unknown } | null)?.status === 409) {
+ return 'This Context changed since it was loaded. Reload it before applying your changes.'
+ }
+ return error instanceof Error ? error.message : fallback
+}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 940466ab9..c555b1a8f 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.391",
+ "version": "0.1.392",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.391",
+ "version": "0.1.392",
"dependencies": {
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
diff --git a/control-ui/package.json b/control-ui/package.json
index e73705849..3ac24d536 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.391",
+ "version": "0.1.392",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",