Skip to content

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

TypeScript

fix(control-ui): add connector detail access tabs

Josuéddce92ea598b
diff --git a/control-ui/app/constants/connectorDetail.ts b/control-ui/app/constants/connectorDetail.ts
index 2aea41287..85f25c9a0 100644
--- a/control-ui/app/constants/connectorDetail.ts
+++ b/control-ui/app/constants/connectorDetail.ts
@@ -1,10 +1,19 @@
export const CONNECTOR_DETAIL_DEFAULT_TAB = 'configuration'
-export const CONNECTOR_DETAIL_TABS = ['configuration', 'runtime'] as const
+export const CONNECTOR_DETAIL_TABS = [
+ 'configuration',
+ 'runtime',
+ 'users',
+ 'teams',
+ 'agents',
+] as const
export type ConnectorDetailTab = (typeof CONNECTOR_DETAIL_TABS)[number]
export const CONNECTOR_DETAIL_TAB_LABELS: Record<ConnectorDetailTab, string> = {
configuration: 'Configuration',
runtime: 'Runtime status',
+ users: 'Users',
+ teams: 'Teams',
+ agents: 'Agents',
}
diff --git a/control-ui/app/mcp-servers/[name]/layout.tsx b/control-ui/app/mcp-servers/[name]/layout.tsx
index d2f8da729..c6609461d 100644
--- a/control-ui/app/mcp-servers/[name]/layout.tsx
+++ b/control-ui/app/mcp-servers/[name]/layout.tsx
@@ -2,6 +2,7 @@
import type { ReactNode } from 'react'
import { useSelectedLayoutSegment } from 'next/navigation'
+import { ConnectorDetailAccessProvider } from '@components/ConnectorDetailAccessProvider'
import { ConnectorDetailProvider } from '@components/ConnectorDetailProvider'
import { CONNECTOR_DETAIL_TABS } from '@constants/connectorDetail'
@@ -10,5 +11,11 @@ export default function ConnectorLayout({ children }: { children: ReactNode }) {
const isDetailRoute =
selectedSegment === null || CONNECTOR_DETAIL_TABS.some(tab => tab === selectedSegment)
- return isDetailRoute ? <ConnectorDetailProvider>{children}</ConnectorDetailProvider> : children
+ return isDetailRoute ? (
+ <ConnectorDetailProvider>
+ <ConnectorDetailAccessProvider>{children}</ConnectorDetailAccessProvider>
+ </ConnectorDetailProvider>
+ ) : (
+ children
+ )
}
diff --git a/control-ui/app/mcp-servers/[name]/page.tsx b/control-ui/app/mcp-servers/[name]/page.tsx
index 596fad422..d11d4a97a 100644
--- a/control-ui/app/mcp-servers/[name]/page.tsx
+++ b/control-ui/app/mcp-servers/[name]/page.tsx
@@ -1,202 +1,3 @@
'use client'
-import { useEffect, useState } from 'react'
-import { useParams, useRouter } from 'next/navigation'
-import { AuthGate } from '@components/AuthGate'
-import { useConnectorDetail } from '@components/ConnectorDetailProvider'
-import { DetailPageShell } from '@components/DetailPageShell'
-import { IconCable } from '@components/Sidebar/icons'
-import { IconRefresh } from '@components/icons'
-import { Button, FormSection } from '@components/ui'
-import {
- CONNECTOR_DETAIL_DEFAULT_TAB,
- CONNECTOR_DETAIL_TABS,
- CONNECTOR_DETAIL_TAB_LABELS,
- type ConnectorDetailTab,
-} from '@constants/connectorDetail'
-import { CONTROL_ROUTES } from '@constants/routes'
-import type { McpServerCondition } from '@lib/api'
-
-function text(value: unknown, fallback = '—'): string {
- return typeof value === 'string' && value.trim() ? value : fallback
-}
-
-function parseConnectorDetailTab(value: string | string[] | undefined): ConnectorDetailTab {
- const candidate = Array.isArray(value) ? value[0] : value
- return CONNECTOR_DETAIL_TABS.find(tab => tab === candidate) ?? CONNECTOR_DETAIL_DEFAULT_TAB
-}
-
-function ConnectorReadOnlyField({
- code = false,
- label,
- value,
- wide = false,
-}: {
- code?: boolean
- label: string
- value: string
- wide?: boolean
-}) {
- return (
- <div className={wide ? 'cu-field cu-connector-detail__field--wide' : 'cu-field'}>
- <span className="cu-field__label">{label}</span>
- <div
- className={
- code
- ? 'cu-readonly-field cu-connector-detail__value cu-connector-detail__value--code'
- : 'cu-readonly-field cu-connector-detail__value'
- }
- >
- {code ? <code>{value}</code> : value}
- </div>
- </div>
- )
-}
-
-function ConnectorRuntimeStatus({ conditions }: { conditions: McpServerCondition[] }) {
- return (
- <FormSection
- title="Runtime status"
- description="Current status reported by the connector runtime."
- >
- {conditions.length ? (
- <ul className="cu-connector-detail__conditions" aria-label="Connector runtime conditions">
- {conditions.map(condition => (
- <li className="cu-connector-detail__condition" key={condition.type}>
- <div className="cu-connector-detail__condition-header">
- <strong>{condition.type}</strong>
- <span>{condition.status}</span>
- </div>
- {condition.message ? (
- <p className="cu-connector-detail__condition-message">{condition.message}</p>
- ) : null}
- </li>
- ))}
- </ul>
- ) : (
- <p className="cu-muted">No runtime conditions have been reported.</p>
- )}
- </FormSection>
- )
-}
-
-export default function McpServerDetailPage() {
- const router = useRouter()
- const params = useParams<{ name: string; tab?: string | string[] }>()
- const name = decodeURIComponent(params?.name ?? '')
- const { server, loading, error, load } = useConnectorDetail()
- const [activeTab, setActiveTab] = useState<ConnectorDetailTab>(() =>
- parseConnectorDetailTab(params?.tab)
- )
-
- function selectTab(next: ConnectorDetailTab) {
- setActiveTab(next)
- }
-
- useEffect(() => {
- setActiveTab(parseConnectorDetailTab(params?.tab))
- }, [params?.tab])
-
- const spec = server?.spec ?? {}
- const conditions = server?.status?.conditions ?? []
- const transport =
- spec.transport && typeof spec.transport === 'object'
- ? (spec.transport as Record<string, unknown>)
- : {}
-
- return (
- <AuthGate>
- <DetailPageShell
- icon={<IconCable />}
- title={`Connector: ${name}`}
- subtitle="Review connector configuration and runtime status. Edit this connector to make changes."
- backLabel="Back to connectors"
- onBack={() => router.push(CONTROL_ROUTES.connectors.root)}
- activeTab={activeTab}
- onTabChange={selectTab}
- tabAriaLabel="Connector detail sections"
- tabs={CONNECTOR_DETAIL_TABS.map(tab => ({
- value: tab,
- label: CONNECTOR_DETAIL_TAB_LABELS[tab],
- href:
- tab === CONNECTOR_DETAIL_DEFAULT_TAB
- ? CONTROL_ROUTES.connectors.detail(name)
- : CONTROL_ROUTES.connectors.detailTab(name, tab),
- onLinkActivate: () => selectTab(tab),
- }))}
- contentMode="plain"
- contentClassName="cu-detail-content-stack--panel-continuation"
- actions={
- <>
- <Button
- icon
- toolbar
- variant="secondary"
- aria-label={loading ? 'Refreshing connector' : 'Refresh connector'}
- disabled={loading}
- onClick={() => void load()}
- >
- <IconRefresh className={loading ? 'cu-spin' : undefined} width={18} height={18} />
- </Button>
- <Button
- size="sm"
- variant="primary"
- disabled={loading || !server}
- onClick={() => router.push(CONTROL_ROUTES.connectors.edit(name))}
- >
- Edit connector
- </Button>
- </>
- }
- error={error || undefined}
- >
- {loading ? (
- <div
- className="cu-body-loading-skeleton"
- role="status"
- aria-busy="true"
- aria-label="Loading connector details"
- >
- <section className="cu-body-loading-skeleton__section">
- <span className="cu-skeleton cu-body-loading-skeleton__heading" />
- <span className="cu-skeleton cu-body-loading-skeleton__line" />
- <div className="cu-body-loading-skeleton__fields">
- <span className="cu-skeleton cu-body-loading-skeleton__field" />
- <span className="cu-skeleton cu-body-loading-skeleton__field" />
- </div>
- </section>
- </div>
- ) : server ? (
- activeTab === 'configuration' ? (
- <FormSection
- title="Configuration"
- description="Connector settings are shown here for review. Use Edit connector to change them."
- >
- <div className="cu-form-grid cu-form-grid--2 cu-connector-detail__grid">
- <ConnectorReadOnlyField label="Name" value={name} />
- <ConnectorReadOnlyField
- label="Namespace"
- value={text(server.metadata?.namespace, 'default')}
- />
- <ConnectorReadOnlyField label="Description" value={text(spec.description)} wide />
- <ConnectorReadOnlyField code label="Image" value={text(spec.image)} wide />
- <ConnectorReadOnlyField
- label="Managed"
- value={spec.managed === false ? 'No' : 'Yes'}
- />
- <ConnectorReadOnlyField
- label="Enabled"
- value={spec.enabled === false ? 'No' : 'Yes'}
- />
- <ConnectorReadOnlyField label="Transport" value={text(transport.type)} />
- <ConnectorReadOnlyField code label="Endpoint" value={text(transport.url)} wide />
- </div>
- </FormSection>
- ) : (
- <ConnectorRuntimeStatus conditions={conditions} />
- )
- ) : null}
- </DetailPageShell>
- </AuthGate>
- )
-}
+export { ConnectorDetailPage as default } from '@components/ConnectorDetailPage'
diff --git a/control-ui/app/mcp-servers/page.tsx b/control-ui/app/mcp-servers/page.tsx
index 47051733a..cbbd481ea 100644
--- a/control-ui/app/mcp-servers/page.tsx
+++ b/control-ui/app/mcp-servers/page.tsx
@@ -8,7 +8,6 @@ import { DashboardLayout } from '../../components/DashboardLayout'
import { McpServerTable } from '../../components/McpServerTable'
import type {
ConnectorAccessPrincipal,
- ConnectorAccessSummary,
ConnectorAccessSummaryMap,
ConnectorAgentBinding,
ConnectorAgentTarget,
@@ -17,150 +16,19 @@ import { useToast } from '../../components/Toast'
import {
McpServerUninstallIncompleteError,
deleteMcpServer,
- getAgentTeams,
- getAgentUsers,
getContexts,
getHosts,
getMcpServers,
isSilentApiError,
- updateContext,
} from '../../lib/api'
-import type { ContextResource, ContextSpec, HostResource, McpServerResource } from '../../lib/api'
-import { mergeAccessSummaries, sortAccessPrincipals } from '../../lib/connectorAccess'
-import { connectorContextAssignmentError } from '../../lib/connectorOAuthAccess'
-import { contextAliases, contextForAlias, contextResourceName } from '../../lib/contextIdentity'
-import { buildContextUpdatePayload, contextMutationError } from '../../lib/contextMutation'
-
-function resourceName(resource: { metadata?: { name?: string } }): string {
- return resource.metadata?.name || 'unknown'
-}
-
-function resourceNamespace(resource: { metadata?: { namespace?: string } }): string {
- return resource.metadata?.namespace || 'default'
-}
-
-function connectorKey(connector: McpServerResource): string {
- return `${resourceNamespace(connector)}/${resourceName(connector)}`
-}
-
-function getContextRef(resource: { spec?: Record<string, unknown> }): string {
- const contextRef = resource.spec?.contextRef
- return typeof contextRef === 'string' ? contextRef.trim() : ''
-}
-
-function contextName(context: ContextResource): string {
- return contextResourceName(context)
-}
-
-function contextSpec(context: ContextResource): ContextSpec {
- const name = contextName(context)
- return {
- contextId: context.spec?.contextId || name,
- description: context.spec?.description,
- mcpServers: Array.isArray(context.spec?.mcpServers) ? context.spec.mcpServers : [],
- sharedFileSystems: context.spec?.sharedFileSystems ?? [],
- }
-}
-
-// The agents an operator can grant connector access to. Each agent resolves to
-// its private context (the write target); the context itself stays invisible.
-function agentTargetsFromHosts(hosts: HostResource[]): ConnectorAgentTarget[] {
- return hosts
- .map(host => {
- const name = resourceName(host)
- const displayName =
- String((host.spec as { host?: string } | undefined)?.host || '').trim() || name
- return { name, label: displayName, contextRef: getContextRef(host) }
- })
- .filter(target => target.contextRef && target.name !== 'unknown')
- .sort((left, right) => left.label.localeCompare(right.label))
-}
-
-// Per-connector write units: every context that carries the connector and is
-// owned by at least one agent becomes one binding listing those agents.
-// Contexts with no owning agent (per-install and workflow-recipe private
-// scopes) are intentionally invisible — they are not user-managed.
-function bindingsByConnectorFromContexts(
- contexts: ContextResource[],
- agentTargets: ConnectorAgentTarget[]
-): Record<string, ConnectorAgentBinding[]> {
- const bindings: Record<string, ConnectorAgentBinding[]> = {}
- for (const context of contexts) {
- const ref = contextName(context)
- const aliases = new Set(contextAliases(context))
- const agents = agentTargets
- .filter(target => aliases.has(target.contextRef))
- .map(target => ({ id: target.name, label: target.label }))
- if (!ref || agents.length === 0) continue
- for (const serverName of context.spec?.mcpServers ?? []) {
- const list = bindings[serverName] ?? []
- list.push({ contextRef: ref, agents: sortAccessPrincipals(agents) })
- bindings[serverName] = list
- }
- }
- for (const list of Object.values(bindings)) {
- list.sort((left, right) =>
- (left.agents[0]?.label ?? '').localeCompare(right.agents[0]?.label ?? '')
- )
- }
- return bindings
-}
-
-// User/team access summaries ride the AGENTS that carry the connector (the
-// same grants operators make in Users & Teams ▸ Access/Agents tabs), not the
-// legacy scope-centric context mappings. Read-only groups in the table.
-async function loadAgentAccess(
- agentName: string
-): Promise<readonly [ConnectorAccessSummary, boolean]> {
- const [usersResult, teamsResult] = await Promise.allSettled([
- getAgentUsers(agentName),
- getAgentTeams(agentName),
- ])
- const accessLoadFailed = usersResult.status === 'rejected' || teamsResult.status === 'rejected'
- if (usersResult.status === 'rejected') {
- console.warn(`Failed to load users for agent ${agentName}:`, usersResult.reason)
- }
- if (teamsResult.status === 'rejected') {
- console.warn(`Failed to load teams for agent ${agentName}:`, teamsResult.reason)
- }
- const users =
- usersResult.status === 'fulfilled'
- ? sortAccessPrincipals(
- (usersResult.value.items ?? []).map(user => ({
- id: user.id,
- label: user.displayName || user.name || user.email || user.id,
- }))
- )
- : []
- const teams =
- teamsResult.status === 'fulfilled'
- ? sortAccessPrincipals(
- (teamsResult.value.items ?? []).map(team => ({
- id: team.id,
- label: team.name || team.id,
- }))
- )
- : []
-
- return [
- {
- agents: [],
- users,
- teams,
- },
- accessLoadFailed,
- ] as const
-}
-
-function connectorAccessMutationError(error: unknown, fallback: string): string {
- if ((error as { status?: unknown } | null)?.status === 409) {
- return 'This connector’s access changed since it was loaded. Reload the page and try again.'
- }
- if (error instanceof Error && /required version is unavailable/i.test(error.message)) {
- return 'This connector’s access is missing a server version. Reload the page and try again.'
- }
- return contextMutationError(error, fallback)
-}
+import type { ContextResource, McpServerResource } from '../../lib/api'
+import {
+ addConnectorToAgentContexts,
+ connectorAccessMutationError,
+ connectorResourceKey,
+ loadConnectorAccessState,
+ removeConnectorFromAgentContext,
+} from '../../lib/connectorAccessManagement'
function agentListLabel(agents: ConnectorAccessPrincipal[]): string {
if (agents.length === 1) return agents[0].label
@@ -196,75 +64,15 @@ export default function McpServersPage() {
getContexts(),
])
const connectors = (serversResult.items || []) as McpServerResource[]
- const hosts = (hostsResult.items || []) as HostResource[]
+ const hosts = hostsResult.items || []
const nextContexts = (contextsResult.items || []) as ContextResource[]
- const nextAgentTargets = agentTargetsFromHosts(hosts)
- const nextBindings = bindingsByConnectorFromContexts(nextContexts, nextAgentTargets)
-
- // Read-only user/team summaries are merged across the AGENTS that
- // carry each connector (bindings), matching the grants operators see
- // in Users & Teams — never the legacy scope-centric mappings.
- const managedAgentNames = [
- ...new Set(
- Object.values(nextBindings)
- .flat()
- .flatMap(binding => binding.agents.map(agent => agent.id))
- ),
- ]
- const accessResults = await Promise.all(
- managedAgentNames.map(
- async agentName => [agentName, await loadAgentAccess(agentName)] as const
- )
- )
- const accessByAgent = new Map(
- accessResults.map(([agentName, [summary]]) => [agentName, summary] as const)
- )
- const accessLoadFailed = accessResults.some(([, [, failed]]) => failed)
- if (accessLoadFailed) {
- setAccessWarning(
- 'Some connector access data could not be loaded. User or team access may be incomplete.'
- )
- }
- const nextAccessByConnectorKey = connectors.reduce<ConnectorAccessSummaryMap>(
- (acc, connector) => {
- const connectorName = resourceName(connector)
- const connectorBindings = nextBindings[connectorName] ?? []
- const bindingAgentNames = connectorBindings.flatMap(binding =>
- binding.agents.map(agent => agent.id)
- )
- if (bindingAgentNames.length > 0) {
- const merged = mergeAccessSummaries(
- bindingAgentNames.map(
- agentName => accessByAgent.get(agentName) ?? { agents: [], users: [], teams: [] }
- )
- )
- // The agents group must reflect the bindings (the write model) so
- // search-by-agent keeps working: accessText in the table's search
- // haystack reads summary.agents.
- const bindingAgents = connectorBindings.flatMap(binding => binding.agents)
- const seenAgentIds = new Set(
- [...bindingAgents, ...merged.agents].map(principal => principal.id)
- )
- const agents = [
- ...bindingAgents,
- ...merged.agents.filter(principal => !seenAgentIds.has(principal.id)),
- ]
- // Re-dedupe by id preserving first occurrence.
- const byId = new Map(agents.map(principal => [principal.id, principal]))
- acc[connectorKey(connector)] = {
- ...merged,
- agents: sortAccessPrincipals([...byId.values()]),
- }
- }
- return acc
- },
- {}
- )
+ const accessState = await loadConnectorAccessState(connectors, nextContexts, hosts)
+ setAccessWarning(accessState.warning)
setMcpServers(connectors)
setContexts(nextContexts)
- setAgentTargets(nextAgentTargets)
- setBindingsByConnectorName(nextBindings)
- setAccessByConnectorKey(nextAccessByConnectorKey)
+ setAgentTargets(accessState.agentTargets)
+ setBindingsByConnectorName(accessState.bindingsByConnectorName)
+ setAccessByConnectorKey(accessState.accessByConnectorKey)
return ''
} catch (e) {
if (isSilentApiError(e)) return ''
@@ -318,40 +126,11 @@ export default function McpServersPage() {
agents: Array<{ name: string; contextRef: string }>
): Promise<boolean> {
const key = `${server.namespace}/${server.name}`
- const contextRefs = [...new Set(agents.map(agent => agent.contextRef))]
- const connector = mcpServers.find(item => connectorKey(item) === key)
- const oauthScopeError = connectorContextAssignmentError(connector?.spec, contextRefs)
- if (oauthScopeError) {
- setError(oauthScopeError)
- return false
- }
- const resolvedTargets = contextRefs.map(contextRef => contextForAlias(contexts, contextRef))
- if (resolvedTargets.some(target => !target)) {
- setError('One or more selected agents could not be resolved. Please refresh and try again.')
- return false
- }
- const targets = Array.from(
- new Map(
- resolvedTargets.map(target => [contextName(target as ContextResource), target] as const)
- ).values()
- ) as ContextResource[]
-
+ const connector = mcpServers.find(item => connectorResourceKey(item) === key)
setUpdatingAgentAccessKey(key)
setError('')
try {
- await Promise.all(
- targets.map(context => {
- const name = contextName(context)
- const spec = contextSpec(context)
- return updateContext(
- name,
- buildContextUpdatePayload(context.metadata?.resourceVersion, {
- ...spec,
- mcpServers: Array.from(new Set([...spec.mcpServers, server.name])),
- })
- )
- })
- )
+ await addConnectorToAgentContexts(server, agents, contexts, connector?.spec)
await loadAll()
showToast(
agents.length === 1
@@ -374,12 +153,6 @@ export default function McpServersPage() {
binding: ConnectorAgentBinding
) {
const key = `${server.namespace}/${server.name}`
- const target = contextForAlias(contexts, binding.contextRef)
- if (!target) {
- setError('This agent’s connector set could not be loaded. Please refresh and try again.')
- return
- }
-
if (binding.agents.length > 1) {
const sharedNames = binding.agents.map(agent => agent.label).join(', ')
const shouldRemove = await confirm({
@@ -394,14 +167,7 @@ export default function McpServersPage() {
setUpdatingAgentAccessKey(key)
setError('')
try {
- const spec = contextSpec(target)
- await updateContext(
- contextName(target),
- buildContextUpdatePayload(target.metadata?.resourceVersion, {
- ...spec,
- mcpServers: spec.mcpServers.filter(name => name !== server.name),
- })
- )
+ await removeConnectorFromAgentContext(server.name, binding, contexts)
await loadAll()
showToast(`Connector ${server.name} removed from ${agentListLabel(binding.agents)}.`, {
tone: 'success',
diff --git a/control-ui/components/ConnectorAgentAccessDialog/index.tsx b/control-ui/components/ConnectorAgentAccessDialog/index.tsx
new file mode 100644
index 000000000..1208d457d
--- /dev/null
+++ b/control-ui/components/ConnectorAgentAccessDialog/index.tsx
@@ -0,0 +1,68 @@
+'use client'
+
+import { useMemo, useState } from 'react'
+import { MultiSelectActionDialog } from '@clerum/frontend-components'
+import { canAssignConnectorToContext } from '@lib/connectorOAuthAccess'
+import type { ConnectorAgentAccessDialogProps } from './types'
+
+export function ConnectorAgentAccessDialog({
+ server,
+ connectorSpec,
+ agentTargets,
+ boundAgentNames,
+ pending = false,
+ onAdd,
+ onDismiss,
+}: ConnectorAgentAccessDialogProps) {
+ const [selectedAgentNames, setSelectedAgentNames] = useState<string[]>([])
+ const [error, setError] = useState('')
+ const boundAgentNamesSet = useMemo(() => new Set(boundAgentNames), [boundAgentNames])
+ const items = useMemo(
+ () =>
+ agentTargets
+ .filter(
+ target =>
+ !boundAgentNamesSet.has(target.name) &&
+ canAssignConnectorToContext(connectorSpec, target.contextRef)
+ )
+ .map(target => ({
+ id: target.name,
+ label: target.label,
+ description: target.name,
+ searchText: `${target.label} ${target.name}`,
+ })),
+ [agentTargets, boundAgentNamesSet, connectorSpec]
+ )
+
+ return (
+ <MultiSelectActionDialog
+ actionLabel={selectedAgentNames.length > 1 ? 'Add to agents' : 'Add to agent'}
+ emptyMessage="No other agents available."
+ error={error || undefined}
+ items={items}
+ noMatchesMessage="No matching agents."
+ onAction={async selectedIds => {
+ const selected = agentTargets.filter(target => selectedIds.includes(target.name))
+ const added = await onAdd(
+ server,
+ selected.map(target => ({ name: target.name, contextRef: target.contextRef }))
+ )
+ if (!added) {
+ setError('Connector access could not be updated. Review the error and retry.')
+ return
+ }
+ setSelectedAgentNames([])
+ setError('')
+ onDismiss()
+ }}
+ onDismiss={onDismiss}
+ onSelectedIdsChange={setSelectedAgentNames}
+ open
+ pending={pending}
+ searchLabel="Search agents"
+ searchPlaceholder="Search agents..."
+ selectedIds={selectedAgentNames}
+ title="Give agents access to this connector"
+ />
+ )
+}
diff --git a/control-ui/components/ConnectorAgentAccessDialog/types.ts b/control-ui/components/ConnectorAgentAccessDialog/types.ts
new file mode 100644
index 000000000..6b67631e9
--- /dev/null
+++ b/control-ui/components/ConnectorAgentAccessDialog/types.ts
@@ -0,0 +1,14 @@
+import type { ConnectorAgentTarget, ServerRef } from '@components/McpServerTable.types'
+
+export type ConnectorAgentAccessDialogProps = {
+ server: ServerRef
+ connectorSpec?: { contextRef?: unknown; oauth?: unknown }
+ agentTargets: ConnectorAgentTarget[]
+ boundAgentNames: string[]
+ pending?: boolean
+ onAdd: (
+ server: ServerRef,
+ agents: Array<Pick<ConnectorAgentTarget, 'name' | 'contextRef'>>
+ ) => Promise<boolean>
+ onDismiss: () => void
+}
diff --git a/control-ui/components/ConnectorDetailAccessPanel/index.tsx b/control-ui/components/ConnectorDetailAccessPanel/index.tsx
new file mode 100644
index 000000000..e7ae0ea99
--- /dev/null
+++ b/control-ui/components/ConnectorDetailAccessPanel/index.tsx
@@ -0,0 +1,191 @@
+'use client'
+
+import { useMemo, useState } from 'react'
+import Link from 'next/link'
+import { DataTable, TableRow, TableStateRow, TableViewport } from '@clerum/frontend-components'
+import { RowActionsMenu } from '@components/RowActionsMenu'
+import { TableHeaderRow } from '@components/TableHeaderRow'
+import type { TableHeaderColumn } from '@components/TableHeaderRow/types'
+import { FormSection } from '@components/ui'
+import { CONTROL_ROUTES } from '@constants/routes'
+import { sortAccessPrincipals } from '@lib/connectorAccess'
+import { connectorUserAndTeamAccess } from '@lib/connectorAccessManagement'
+import type { ConnectorDetailAccessPanelProps, ConnectorDetailAccessRow } from './types'
+
+function boundaryLabel(boundary: ConnectorDetailAccessPanelProps['boundary']): string {
+ return boundary === 'users' ? 'User' : boundary === 'teams' ? 'Team' : 'Agent'
+}
+
+function boundaryTitle(boundary: ConnectorDetailAccessPanelProps['boundary']): string {
+ return boundary === 'users' ? 'Users' : boundary === 'teams' ? 'Teams' : 'Agents'
+}
+
+function routeForPrincipal(
+ boundary: ConnectorDetailAccessPanelProps['boundary'],
+ principalId: string
+): string | undefined {
+ if (boundary === 'users') return CONTROL_ROUTES.usersAndTeams.userTab(principalId, 'agents')
+ if (boundary === 'teams') return CONTROL_ROUTES.usersAndTeams.teamTab(principalId, 'agents')
+ return CONTROL_ROUTES.agents.detail(principalId)
+}
+
+function sourceNote(boundary: ConnectorDetailAccessPanelProps['boundary']): string {
+ if (boundary === 'users') {
+ return 'User access is derived from the agents each user can access. Manage it from the user’s Agents tab.'
+ }
+ if (boundary === 'teams') {
+ return 'Team access is derived from the agents assigned to each team. Manage it from the team’s Agents tab.'
+ }
+ return 'Connector access is assigned to agents. Changes here refresh the derived Users and Teams views.'
+}
+
+export function ConnectorDetailAccessPanel({
+ boundary,
+ server,
+ snapshot,
+ agentBindings,
+ loading,
+ updating,
+ error,
+ notice,
+ onRemove,
+}: ConnectorDetailAccessPanelProps) {
+ const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')
+ const label = boundaryLabel(boundary)
+ const rows = useMemo<ConnectorDetailAccessRow[]>(() => {
+ if (boundary === 'agents') {
+ return agentBindings.map(binding => ({
+ id: binding.contextRef,
+ label: binding.agents.map(agent => agent.label).join(', '),
+ binding,
+ }))
+ }
+ if (!snapshot) return []
+ const access = connectorUserAndTeamAccess(
+ { metadata: { name: server.name, namespace: server.namespace } },
+ snapshot
+ )
+ return sortAccessPrincipals(boundary === 'users' ? access.users : access.teams)
+ }, [agentBindings, boundary, server.name, server.namespace, snapshot])
+ const sortedRows = useMemo(() => {
+ const direction = sortDirection === 'asc' ? 1 : -1
+ return [...rows].sort(
+ (left, right) =>
+ left.label.localeCompare(right.label, undefined, { sensitivity: 'base' }) * direction ||
+ left.id.localeCompare(right.id)
+ )
+ }, [rows, sortDirection])
+ const columns: TableHeaderColumn[] = [
+ {
+ key: 'name',
+ label,
+ activeDirection: sortDirection,
+ onSort: () => setSortDirection(value => (value === 'asc' ? 'desc' : 'asc')),
+ },
+ ...(boundary === 'agents'
+ ? [{ key: 'actions', ariaLabel: 'Actions', align: 'right' as const, width: '3.5rem' }]
+ : []),
+ ]
+ const emptyMessage =
+ boundary === 'agents'
+ ? 'No agents have access to this connector.'
+ : boundary === 'users'
+ ? 'No users have access through an assigned agent.'
+ : 'No teams have access through an assigned agent.'
+ const rowLabel = (row: ConnectorDetailAccessRow) =>
+ boundary === 'agents' && row.binding?.agents.length === 1
+ ? row.binding.agents[0].label
+ : row.label
+
+ return (
+ <FormSection title={boundaryTitle(boundary)} description={sourceNote(boundary)}>
+ {notice ? (
+ <p className="cu-muted" role="status">
+ {notice}
+ </p>
+ ) : null}
+ {boundary !== 'agents' && snapshot?.warning ? (
+ <p className="cu-banner cu-banner--warning" role="status">
+ {snapshot.warning}
+ </p>
+ ) : null}
+ <TableViewport className="cu-table-wrap">
+ <DataTable className="eft-table cu-table cu-table--header-band">
+ <thead>
+ <TableHeaderRow columns={columns} />
+ </thead>
+ <tbody>
+ {loading && !snapshot ? (
+ <TableStateRow colSpan={columns.length} kind="loading" message="Loading access…" />
+ ) : error && !snapshot ? (
+ <TableStateRow colSpan={columns.length} kind="error" message={error} />
+ ) : sortedRows.length === 0 ? (
+ <TableStateRow colSpan={columns.length} message={emptyMessage} />
+ ) : (
+ sortedRows.map(row => {
+ const actionLabel =
+ row.binding?.agents.length === 1
+ ? `Remove from ${row.binding.agents[0].label}`
+ : `Remove from ${row.binding?.agents.length ?? 0} agents`
+ return (
+ <TableRow key={row.id}>
+ <td>
+ {boundary === 'agents' && row.binding ? (
+ row.binding.agents.map((agent, index) => (
+ <span key={agent.id}>
+ {index > 0 ? ', ' : null}
+ <Link href={CONTROL_ROUTES.agents.detail(agent.id)}>{agent.label}</Link>
+ </span>
+ ))
+ ) : routeForPrincipal(boundary, row.id) ? (
+ <Link href={routeForPrincipal(boundary, row.id) as string}>
+ {rowLabel(row)}
+ </Link>
+ ) : (
+ rowLabel(row)
+ )}
+ </td>
+ {boundary === 'agents' ? (
+ <td
+ className="cu-table__cell-actions"
+ onClick={event => event.stopPropagation()}
+ onKeyDown={event => event.stopPropagation()}
+ >
+ <RowActionsMenu
+ ariaLabel={`Actions for connector access to ${rowLabel(row)}`}
+ actions={
+ row.binding
+ ? [
+ {
+ key: 'remove-access',
+ label: actionLabel,
+ danger: true,
+ disabled: updating,
+ onClick: () => onRemove(row.binding!),
+ },
+ ]
+ : []
+ }
+ />
+ </td>
+ ) : null}
+ </TableRow>
+ )
+ })
+ )}
+ </tbody>
+ </DataTable>
+ </TableViewport>
+ {error && snapshot ? (
+ <p className="cu-banner cu-banner--error" role="alert">
+ {error}
+ </p>
+ ) : null}
+ {loading && snapshot ? (
+ <p className="cu-muted" role="status">
+ Refreshing access…
+ </p>
+ ) : null}
+ </FormSection>
+ )
+}
diff --git a/control-ui/components/ConnectorDetailAccessPanel/types.ts b/control-ui/components/ConnectorDetailAccessPanel/types.ts
new file mode 100644
index 000000000..ff90d505b
--- /dev/null
+++ b/control-ui/components/ConnectorDetailAccessPanel/types.ts
@@ -0,0 +1,24 @@
+import type {
+ ConnectorAccessPrincipal,
+ ConnectorAgentBinding,
+ ServerRef,
+} from '@components/McpServerTable.types'
+import type { ConnectorAccessState } from '@lib/connectorAccessManagement'
+
+export type ConnectorAccessBoundary = 'users' | 'teams' | 'agents'
+
+export type ConnectorDetailAccessPanelProps = {
+ boundary: ConnectorAccessBoundary
+ server: ServerRef
+ snapshot: ConnectorAccessState | null
+ agentBindings: ConnectorAgentBinding[]
+ loading: boolean
+ updating: boolean
+ error: string
+ notice?: string
+ onRemove: (binding: ConnectorAgentBinding) => void
+}
+
+export type ConnectorDetailAccessRow = ConnectorAccessPrincipal & {
+ binding?: ConnectorAgentBinding
+}
diff --git a/control-ui/components/ConnectorDetailAccessProvider/index.tsx b/control-ui/components/ConnectorDetailAccessProvider/index.tsx
new file mode 100644
index 000000000..17efcc1b2
--- /dev/null
+++ b/control-ui/components/ConnectorDetailAccessProvider/index.tsx
@@ -0,0 +1,234 @@
+'use client'
+
+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
+import type { ReactNode } from 'react'
+import { useParams, useSelectedLayoutSegment } from 'next/navigation'
+import { useConnectorDetail } from '@components/ConnectorDetailProvider'
+import type { ConnectorAgentBinding, ConnectorAgentTarget } from '@components/McpServerTable.types'
+import { getContexts, getHosts, isSilentApiError } from '@lib/api'
+import {
+ addConnectorToAgentContexts,
+ connectorAccessMutationError,
+ loadConnectorAccessState,
+ removeConnectorFromAgentContext,
+} from '@lib/connectorAccessManagement'
+import type { ConnectorAccessState } from '@lib/connectorAccessManagement'
+import type { ConnectorDetailAccessState } from './types'
+
+const ACCESS_TABS = new Set(['users', 'teams', 'agents'])
+
+const ConnectorDetailAccessContext = createContext<ConnectorDetailAccessState | null>(null)
+
+type LoadedAccessState = {
+ name: string
+ snapshot: ConnectorAccessState | null
+ settled: boolean
+ loading: boolean
+ error: string
+}
+
+export function ConnectorDetailAccessProvider({ children }: { children: ReactNode }) {
+ const params = useParams<{ name: string }>()
+ const name = decodeURIComponent(params?.name ?? '')
+ const selectedSegment = useSelectedLayoutSegment()
+ const accessRouteActive = ACCESS_TABS.has(selectedSegment ?? '')
+ const { server, loading: connectorLoading } = useConnectorDetail()
+ const requestId = useRef(0)
+ const [loaded, setLoaded] = useState<LoadedAccessState>({
+ name: '',
+ snapshot: null,
+ settled: false,
+ loading: false,
+ error: '',
+ })
+ const [updating, setUpdating] = useState(false)
+ const [notice, setNotice] = useState('')
+
+ const load = useCallback(async (): Promise<boolean> => {
+ if (!name || !server) return false
+ const request = ++requestId.current
+ setLoaded(previous => ({
+ name,
+ snapshot: previous.name === name ? previous.snapshot : null,
+ settled: false,
+ loading: true,
+ error: '',
+ }))
+
+ try {
+ const [contextsResult, hostsResult] = await Promise.all([getContexts(), getHosts()])
+ const snapshot = await loadConnectorAccessState(
+ [server],
+ contextsResult.items ?? [],
+ hostsResult.items ?? []
+ )
+ if (request !== requestId.current) return false
+ setLoaded({ name, snapshot, settled: true, loading: false, error: '' })
+ return true
+ } catch (caught) {
+ if (request !== requestId.current) return false
+ if (isSilentApiError(caught)) {
+ setLoaded(previous => ({
+ name,
+ snapshot: previous.name === name ? previous.snapshot : null,
+ settled: true,
+ loading: false,
+ error: '',
+ }))
+ return false
+ }
+ setLoaded(previous => ({
+ name,
+ snapshot: previous.name === name ? previous.snapshot : null,
+ settled: true,
+ loading: false,
+ error: caught instanceof Error ? caught.message : 'Failed to load connector access.',
+ }))
+ return false
+ }
+ }, [name, server])
+
+ useEffect(() => {
+ if (!accessRouteActive || !server || connectorLoading) return
+ if (loaded.name === name && (loaded.settled || loaded.loading)) return
+ void load()
+ }, [accessRouteActive, connectorLoading, load, loaded.name, loaded.snapshot, name, server])
+
+ useEffect(
+ () => () => {
+ requestId.current += 1
+ },
+ []
+ )
+
+ const currentSnapshot = loaded.name === name ? loaded.snapshot : null
+ const serverName = server?.metadata?.name || name
+ const serverNamespace = server?.metadata?.namespace || 'default'
+ const agentBindings = currentSnapshot?.bindingsByConnectorName[serverName] ?? []
+ const agentTargets = currentSnapshot?.agentTargets ?? []
+
+ const refresh = useCallback(async () => {
+ setNotice('')
+ await load()
+ }, [load])
+
+ const addAgents = useCallback(
+ async (agents: Array<Pick<ConnectorAgentTarget, 'name' | 'contextRef'>>) => {
+ if (!server || !currentSnapshot) return false
+ setUpdating(true)
+ setNotice('')
+ setLoaded(previous => ({ ...previous, error: '' }))
+ try {
+ await addConnectorToAgentContexts(
+ { name: serverName, namespace: serverNamespace },
+ agents,
+ currentSnapshot.contexts,
+ server.spec
+ )
+ const refreshed = await load()
+ setNotice(
+ refreshed
+ ? 'Agent access updated. The Users and Teams summaries now reflect this change.'
+ : 'Agent access updated, but the Users and Teams summaries could not be refreshed.'
+ )
+ return true
+ } catch (caught) {
+ if (isSilentApiError(caught)) return false
+ setLoaded(previous => ({
+ ...previous,
+ error: connectorAccessMutationError(
+ caught,
+ `Failed to give agents access to ${serverName}`
+ ),
+ }))
+ return false
+ } finally {
+ setUpdating(false)
+ }
+ },
+ [currentSnapshot, load, server, serverName, serverNamespace]
+ )
+
+ const removeBinding = useCallback(
+ async (binding: ConnectorAgentBinding) => {
+ if (!currentSnapshot) return false
+ setUpdating(true)
+ setNotice('')
+ setLoaded(previous => ({ ...previous, error: '' }))
+ try {
+ await removeConnectorFromAgentContext(serverName, binding, currentSnapshot.contexts)
+ const refreshed = await load()
+ setNotice(
+ refreshed
+ ? 'Agent access updated. The Users and Teams summaries now reflect this change.'
+ : 'Agent access updated, but the Users and Teams summaries could not be refreshed.'
+ )
+ return true
+ } catch (caught) {
+ if (isSilentApiError(caught)) return false
+ setLoaded(previous => ({
+ ...previous,
+ error: connectorAccessMutationError(
+ caught,
+ `Failed to remove ${serverName} from agent access`
+ ),
+ }))
+ return false
+ } finally {
+ setUpdating(false)
+ }
+ },
+ [currentSnapshot, load, serverName]
+ )
+
+ const value = useMemo<ConnectorDetailAccessState>(
+ () => ({
+ snapshot: currentSnapshot,
+ agentBindings,
+ agentTargets,
+ loading:
+ accessRouteActive &&
+ (connectorLoading ||
+ (Boolean(server) && (loaded.name !== name || !loaded.settled || loaded.loading))),
+ updating,
+ error: loaded.name === name ? loaded.error : '',
+ notice,
+ refresh,
+ addAgents,
+ removeBinding,
+ }),
+ [
+ accessRouteActive,
+ addAgents,
+ agentBindings,
+ agentTargets,
+ connectorLoading,
+ currentSnapshot,
+ loaded,
+ name,
+ notice,
+ refresh,
+ removeBinding,
+ server,
+ updating,
+ ]
+ )
+
+ return (
+ <ConnectorDetailAccessContext.Provider value={value}>
+ {children}
+ </ConnectorDetailAccessContext.Provider>
+ )
+}
+
+export function useOptionalConnectorDetailAccess(): ConnectorDetailAccessState | null {
+ return useContext(ConnectorDetailAccessContext)
+}
+
+export function useConnectorDetailAccess(): ConnectorDetailAccessState {
+ const context = useOptionalConnectorDetailAccess()
+ if (!context) {
+ throw new Error('useConnectorDetailAccess must be used within ConnectorDetailAccessProvider')
+ }
+ return context
+}
diff --git a/control-ui/components/ConnectorDetailAccessProvider/types.ts b/control-ui/components/ConnectorDetailAccessProvider/types.ts
new file mode 100644
index 000000000..5f0f7e290
--- /dev/null
+++ b/control-ui/components/ConnectorDetailAccessProvider/types.ts
@@ -0,0 +1,15 @@
+import type { ConnectorAgentBinding, ConnectorAgentTarget } from '@components/McpServerTable.types'
+import type { ConnectorAccessState } from '@lib/connectorAccessManagement'
+
+export type ConnectorDetailAccessState = {
+ snapshot: ConnectorAccessState | null
+ agentBindings: ConnectorAgentBinding[]
+ agentTargets: ConnectorAgentTarget[]
+ loading: boolean
+ updating: boolean
+ error: string
+ notice: string
+ refresh: () => Promise<void>
+ addAgents: (agents: Array<Pick<ConnectorAgentTarget, 'name' | 'contextRef'>>) => Promise<boolean>
+ removeBinding: (binding: ConnectorAgentBinding) => Promise<boolean>
+}
diff --git a/control-ui/components/ConnectorDetailPage/index.tsx b/control-ui/components/ConnectorDetailPage/index.tsx
new file mode 100644
index 000000000..2fe9c7440
--- /dev/null
+++ b/control-ui/components/ConnectorDetailPage/index.tsx
@@ -0,0 +1,297 @@
+'use client'
+
+import { useEffect, useState } from 'react'
+import { useParams, useRouter } from 'next/navigation'
+import { AuthGate } from '@components/AuthGate'
+import { useConfirmDialog } from '@components/ConfirmDialog'
+import { ConnectorAgentAccessDialog } from '@components/ConnectorAgentAccessDialog'
+import { ConnectorDetailAccessPanel } from '@components/ConnectorDetailAccessPanel'
+import { useOptionalConnectorDetailAccess } from '@components/ConnectorDetailAccessProvider'
+import { useConnectorDetail } from '@components/ConnectorDetailProvider'
+import { DetailPageShell } from '@components/DetailPageShell'
+import type { ConnectorAgentBinding } from '@components/McpServerTable.types'
+import { IconCable } from '@components/Sidebar/icons'
+import { IconRefresh } from '@components/icons'
+import { Button, FormSection } from '@components/ui'
+import {
+ CONNECTOR_DETAIL_DEFAULT_TAB,
+ CONNECTOR_DETAIL_TABS,
+ CONNECTOR_DETAIL_TAB_LABELS,
+} from '@constants/connectorDetail'
+import type { ConnectorDetailTab } from '@constants/connectorDetail'
+import { CONTROL_ROUTES } from '@constants/routes'
+import type { McpServerCondition } from '@lib/api'
+
+function text(value: unknown, fallback = '—'): string {
+ return typeof value === 'string' && value.trim() ? value : fallback
+}
+
+function parseConnectorDetailTab(value: string | string[] | undefined): ConnectorDetailTab {
+ const candidate = Array.isArray(value) ? value[0] : value
+ return CONNECTOR_DETAIL_TABS.find(tab => tab === candidate) ?? CONNECTOR_DETAIL_DEFAULT_TAB
+}
+
+function ConnectorReadOnlyField({
+ code = false,
+ label,
+ value,
+ wide = false,
+}: {
+ code?: boolean
+ label: string
+ value: string
+ wide?: boolean
+}) {
+ return (
+ <div className={wide ? 'cu-field cu-connector-detail__field--wide' : 'cu-field'}>
+ <span className="cu-field__label">{label}</span>
+ <div
+ className={
+ code
+ ? 'cu-readonly-field cu-connector-detail__value cu-connector-detail__value--code'
+ : 'cu-readonly-field cu-connector-detail__value'
+ }
+ >
+ {code ? <code>{value}</code> : value}
+ </div>
+ </div>
+ )
+}
+
+function ConnectorRuntimeStatus({ conditions }: { conditions: McpServerCondition[] }) {
+ return (
+ <FormSection
+ title="Runtime status"
+ description="Current status reported by the connector runtime."
+ >
+ {conditions.length ? (
+ <ul className="cu-connector-detail__conditions" aria-label="Connector runtime conditions">
+ {conditions.map(condition => (
+ <li className="cu-connector-detail__condition" key={condition.type}>
+ <div className="cu-connector-detail__condition-header">
+ <strong>{condition.type}</strong>
+ <span>{condition.status}</span>
+ </div>
+ {condition.message ? (
+ <p className="cu-connector-detail__condition-message">{condition.message}</p>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="cu-muted">No runtime conditions have been reported.</p>
+ )}
+ </FormSection>
+ )
+}
+
+function accessBoundary(tab: ConnectorDetailTab): 'users' | 'teams' | 'agents' | null {
+ return tab === 'users' || tab === 'teams' || tab === 'agents' ? tab : null
+}
+
+export function ConnectorDetailPage() {
+ const router = useRouter()
+ const params = useParams<{ name: string; tab?: string | string[] }>()
+ const name = decodeURIComponent(params?.name ?? '')
+ const { server, loading, error, load } = useConnectorDetail()
+ const access = useOptionalConnectorDetailAccess()
+ const { confirm, confirmDialog } = useConfirmDialog()
+ const [activeTab, setActiveTab] = useState<ConnectorDetailTab>(() =>
+ parseConnectorDetailTab(params?.tab)
+ )
+ const [showAddAgents, setShowAddAgents] = useState(false)
+
+ useEffect(() => {
+ setActiveTab(parseConnectorDetailTab(params?.tab))
+ }, [params?.tab])
+
+ const activeBoundary = accessBoundary(activeTab)
+ const spec = server?.spec ?? {}
+ const conditions = server?.status?.conditions ?? []
+ const transport =
+ spec.transport && typeof spec.transport === 'object'
+ ? (spec.transport as Record<string, unknown>)
+ : {}
+ const serverRef = {
+ name: server?.metadata?.name || name,
+ namespace: server?.metadata?.namespace || 'default',
+ }
+
+ function selectTab(next: ConnectorDetailTab) {
+ setActiveTab(next)
+ }
+
+ async function addAgents(
+ _server: { name: string; namespace: string },
+ agents: Array<{ name: string; contextRef: string }>
+ ): Promise<boolean> {
+ if (!access) return false
+ return access.addAgents(agents)
+ }
+
+ async function removeAgentBinding(binding: ConnectorAgentBinding) {
+ if (!access) return
+ if (binding.agents.length > 1) {
+ const sharedNames = binding.agents.map(agent => agent.label).join(', ')
+ const shouldRemove = await confirm({
+ title: 'Remove Connector Access',
+ message: `Remove connector ${serverRef.name} from ${binding.agents.length} agents (${sharedNames})? These agents share one connector set, so the change applies to all of them.`,
+ confirmLabel: 'Remove',
+ tone: 'danger',
+ })
+ if (!shouldRemove) return
+ }
+
+ await access.removeBinding(binding)
+ }
+
+ async function refreshCurrent() {
+ void load()
+ if (activeBoundary) await access?.refresh()
+ }
+
+ const addDialog =
+ showAddAgents && activeTab === 'agents' && access ? (
+ <ConnectorAgentAccessDialog
+ key={serverRef.name}
+ server={serverRef}
+ connectorSpec={server?.spec}
+ agentTargets={access.agentTargets}
+ boundAgentNames={access.agentBindings.flatMap(binding =>
+ binding.agents.map(agent => agent.id)
+ )}
+ pending={access.updating}
+ onAdd={addAgents}
+ onDismiss={() => {
+ if (!access.updating) setShowAddAgents(false)
+ }}
+ />
+ ) : null
+
+ return (
+ <AuthGate>
+ <DetailPageShell
+ icon={<IconCable />}
+ title={`Connector: ${name}`}
+ subtitle="Review connector configuration, access, and runtime status. Edit this connector to make changes."
+ backLabel="Back to connectors"
+ onBack={() => router.push(CONTROL_ROUTES.connectors.root)}
+ activeTab={activeTab}
+ onTabChange={selectTab}
+ tabAriaLabel="Connector detail sections"
+ tabs={CONNECTOR_DETAIL_TABS.map(tab => ({
+ value: tab,
+ label: CONNECTOR_DETAIL_TAB_LABELS[tab],
+ href:
+ tab === CONNECTOR_DETAIL_DEFAULT_TAB
+ ? CONTROL_ROUTES.connectors.detail(name)
+ : CONTROL_ROUTES.connectors.detailTab(name, tab),
+ onLinkActivate: () => selectTab(tab),
+ }))}
+ contentMode="plain"
+ contentClassName="cu-detail-content-stack--panel-continuation"
+ actions={
+ <>
+ <Button
+ icon
+ toolbar
+ variant="secondary"
+ aria-label={loading ? 'Refreshing connector' : 'Refresh connector'}
+ disabled={loading || Boolean(access?.updating)}
+ onClick={() => void refreshCurrent()}
+ >
+ <IconRefresh className={loading ? 'cu-spin' : undefined} width={18} height={18} />
+ </Button>
+ {activeTab === 'agents' ? (
+ <Button
+ size="sm"
+ variant="secondary"
+ disabled={
+ loading ||
+ !server ||
+ !access?.snapshot ||
+ Boolean(access.loading || access.updating)
+ }
+ onClick={() => setShowAddAgents(true)}
+ >
+ Add agent
+ </Button>
+ ) : null}
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={loading || !server}
+ onClick={() => router.push(CONTROL_ROUTES.connectors.edit(name))}
+ >
+ Edit connector
+ </Button>
+ </>
+ }
+ error={error || undefined}
+ overlays={
+ <>
+ {addDialog}
+ {confirmDialog}
+ </>
+ }
+ >
+ {loading ? (
+ <div
+ className="cu-body-loading-skeleton"
+ role="status"
+ aria-busy="true"
+ aria-label="Loading connector details"
+ >
+ <section className="cu-body-loading-skeleton__section">
+ <span className="cu-skeleton cu-body-loading-skeleton__heading" />
+ <span className="cu-skeleton cu-body-loading-skeleton__line" />
+ <div className="cu-body-loading-skeleton__fields">
+ <span className="cu-skeleton cu-body-loading-skeleton__field" />
+ <span className="cu-skeleton cu-body-loading-skeleton__field" />
+ </div>
+ </section>
+ </div>
+ ) : server && activeTab === 'configuration' ? (
+ <FormSection
+ title="Configuration"
+ description="Connector settings are shown here for review. Use Edit connector to change them."
+ >
+ <div className="cu-form-grid cu-form-grid--2 cu-connector-detail__grid">
+ <ConnectorReadOnlyField label="Name" value={name} />
+ <ConnectorReadOnlyField
+ label="Namespace"
+ value={text(server.metadata?.namespace, 'default')}
+ />
+ <ConnectorReadOnlyField label="Description" value={text(spec.description)} wide />
+ <ConnectorReadOnlyField code label="Image" value={text(spec.image)} wide />
+ <ConnectorReadOnlyField
+ label="Managed"
+ value={spec.managed === false ? 'No' : 'Yes'}
+ />
+ <ConnectorReadOnlyField
+ label="Enabled"
+ value={spec.enabled === false ? 'No' : 'Yes'}
+ />
+ <ConnectorReadOnlyField label="Transport" value={text(transport.type)} />
+ <ConnectorReadOnlyField code label="Endpoint" value={text(transport.url)} wide />
+ </div>
+ </FormSection>
+ ) : server && activeTab === 'runtime' ? (
+ <ConnectorRuntimeStatus conditions={conditions} />
+ ) : server && activeBoundary ? (
+ <ConnectorDetailAccessPanel
+ boundary={activeBoundary}
+ server={serverRef}
+ snapshot={access?.snapshot ?? null}
+ agentBindings={access?.agentBindings ?? []}
+ loading={access?.loading ?? true}
+ updating={access?.updating ?? false}
+ error={access?.error ?? ''}
+ notice={access?.notice ?? ''}
+ onRemove={binding => void removeAgentBinding(binding)}
+ />
+ ) : null}
+ </DetailPageShell>
+ </AuthGate>
+ )
+}
diff --git a/control-ui/components/McpServerTable.tsx b/control-ui/components/McpServerTable.tsx
index 466a2e165..7ce14d53a 100644
--- a/control-ui/components/McpServerTable.tsx
+++ b/control-ui/components/McpServerTable.tsx
@@ -3,13 +3,12 @@
import React, { useMemo, useState } from 'react'
import {
DataTable,
- MultiSelectActionDialog,
TableRow,
TableStateRow,
TableViewport,
TruncatedText,
} from '@clerum/frontend-components'
-import { canAssignConnectorToContext } from '../lib/connectorOAuthAccess'
+import { ConnectorAgentAccessDialog } from './ConnectorAgentAccessDialog'
import type {
ConnectorAgentBinding,
McpServerStatus,
@@ -110,9 +109,7 @@ export function McpServerTable({
const [sortKey, setSortKey] = useState<ConnectorSortKey>('name')
const [sortDirection, setSortDirection] = useState<SortDirection>('asc')
const [serverKeyAddingAgents, setServerKeyAddingAgents] = useState<string | null>(null)
- const [addAgentsError, setAddAgentsError] = useState('')
const [serverKeyViewingAccess, setServerKeyViewingAccess] = useState<string | null>(null)
- const [selectedAgentNamesToAdd, setSelectedAgentNamesToAdd] = useState<string[]>([])
const accessDialogRef = React.useRef<HTMLElement | null>(null)
const accessCloseButtonRef = React.useRef<HTMLButtonElement | null>(null)
const accessOpenerRef = React.useRef<HTMLElement | null>(null)
@@ -246,16 +243,7 @@ export function McpServerTable({
return agentBindingsByConnectorName[name] ?? []
}
- function closeAddAgents() {
- if (updatingAgentAccessKey) return
- setAddAgentsError('')
- setSelectedAgentNamesToAdd([])
- setServerKeyAddingAgents(null)
- }
-
function openAddAgents(key: string) {
- setAddAgentsError('')
- setSelectedAgentNamesToAdd([])
setServerKeyAddingAgents(key)
}
@@ -452,57 +440,18 @@ export function McpServerTable({
? (() => {
const row = rows.find(candidate => candidate.key === serverKeyAddingAgents)
if (!row || !onAddToAgents) return null
- const boundAgentNames = new Set(
- bindingsForConnector(row.name).flatMap(binding =>
- binding.agents.map(agent => agent.id)
- )
- )
- const agentOptions = agentTargets
- .filter(
- target =>
- !boundAgentNames.has(target.name) &&
- canAssignConnectorToContext(row.item.spec, target.contextRef)
- )
- .map(target => ({
- id: target.name,
- label: target.label,
- description: target.name,
- searchText: `${target.label} ${target.name}`,
- }))
- const busy = updatingAgentAccessKey === row.key
return (
- <MultiSelectActionDialog
- actionLabel={selectedAgentNamesToAdd.length > 1 ? 'Add to agents' : 'Add to agent'}
- emptyMessage="No other agents available."
- error={addAgentsError || undefined}
- items={agentOptions}
- noMatchesMessage="No matching agents."
- onAction={async selectedIds => {
- const selected = agentTargets.filter(target => selectedIds.includes(target.name))
- const added = await onAddToAgents(
- { namespace: row.namespace, name: row.name },
- selected.map(target => ({
- name: target.name,
- contextRef: target.contextRef,
- }))
- )
- if (!added) {
- setAddAgentsError(
- 'Connector access could not be updated. Review the error and retry.'
- )
- return
- }
- setSelectedAgentNamesToAdd([])
- setServerKeyAddingAgents(null)
- }}
- onDismiss={closeAddAgents}
- onSelectedIdsChange={setSelectedAgentNamesToAdd}
- open
- pending={busy}
- searchLabel="Search agents"
- searchPlaceholder="Search agents..."
- selectedIds={selectedAgentNamesToAdd}
- title="Give agents access to this connector"
+ <ConnectorAgentAccessDialog
+ key={serverKeyAddingAgents}
+ server={{ namespace: row.namespace, name: row.name }}
+ connectorSpec={row.item.spec}
+ agentTargets={agentTargets}
+ boundAgentNames={bindingsForConnector(row.name).flatMap(binding =>
+ binding.agents.map(agent => agent.id)
+ )}
+ pending={updatingAgentAccessKey === row.key}
+ onAdd={onAddToAgents}
+ onDismiss={() => setServerKeyAddingAgents(null)}
/>
)
})()
diff --git a/control-ui/components/__tests__/ConnectorAccessManagement.test.ts b/control-ui/components/__tests__/ConnectorAccessManagement.test.ts
new file mode 100644
index 000000000..e8165d20e
--- /dev/null
+++ b/control-ui/components/__tests__/ConnectorAccessManagement.test.ts
@@ -0,0 +1,189 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { ContextResource, HostResource, McpServerResource } from '@lib/api'
+import * as api from '@lib/api'
+import {
+ addConnectorToAgentContexts,
+ connectorAgentBindingsFromContexts,
+ connectorAgentTargetsFromHosts,
+ loadConnectorAccessState,
+ removeConnectorFromAgentContext,
+} from '@lib/connectorAccessManagement'
+
+vi.mock('@lib/api', async importOriginal => ({
+ ...(await importOriginal<typeof import('@lib/api')>()),
+ getAgentTeams: vi.fn(),
+ getAgentUsers: vi.fn(),
+ updateContext: vi.fn(),
+}))
+
+function makeContext(
+ name: string,
+ contextId: string,
+ mcpServers: string[],
+ resourceVersion = '7'
+): ContextResource {
+ return {
+ metadata: { name, resourceVersion },
+ spec: { contextId, mcpServers, sharedFileSystems: [] },
+ }
+}
+
+function makeHost(name: string, label: string, contextRef: string): HostResource {
+ return { metadata: { name }, spec: { host: label, contextRef } }
+}
+
+function makeConnector(name: string): McpServerResource {
+ return { metadata: { name, namespace: 'mcp-server' }, spec: {} }
+}
+
+describe('connector access management', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('groups agents by their authoritative context and excludes unowned contexts', () => {
+ const targets = connectorAgentTargetsFromHosts([
+ makeHost('agent-b', 'Beta', 'shared-id'),
+ makeHost('agent-a', 'Alpha', 'shared-id'),
+ { metadata: {}, spec: { contextRef: 'missing-name' } },
+ makeHost('agent-no-context', 'No Context', ''),
+ ])
+ const bindings = connectorAgentBindingsFromContexts(
+ [
+ makeContext('shared-resource', 'shared-id', ['search']),
+ makeContext('private-context', 'private-context', ['search']),
+ ],
+ targets
+ )
+
+ expect(targets.map(target => target.label)).toEqual(['Alpha', 'Beta'])
+ expect(bindings.search).toEqual([
+ {
+ contextRef: 'shared-resource',
+ agents: [
+ { id: 'agent-a', label: 'Alpha' },
+ { id: 'agent-b', label: 'Beta' },
+ ],
+ },
+ ])
+ })
+
+ it('derives sorted and deduplicated users and teams from the agents carrying the connector', async () => {
+ vi.mocked(api.getAgentUsers).mockImplementation(async agentName => ({
+ items:
+ agentName === 'agent-a'
+ ? [{ id: 'user-1', displayName: 'Ada' }]
+ : [
+ { id: 'user-1', displayName: 'Ada' },
+ { id: 'user-2', displayName: 'Grace' },
+ ],
+ }))
+ vi.mocked(api.getAgentTeams).mockImplementation(async agentName => ({
+ items:
+ agentName === 'agent-a'
+ ? [{ id: 'team-1', name: 'Growth' }]
+ : [
+ { id: 'team-1', name: 'Growth' },
+ { id: 'team-2', name: 'Research' },
+ ],
+ }))
+ const state = await loadConnectorAccessState(
+ [makeConnector('search')],
+ [
+ makeContext('context-a', 'context-a', ['search']),
+ makeContext('context-b', 'context-b', ['search']),
+ ],
+ [makeHost('agent-a', 'Alpha', 'context-a'), makeHost('agent-b', 'Beta', 'context-b')]
+ )
+
+ expect(state.accessByConnectorKey['mcp-server/search']).toEqual({
+ agents: [
+ { id: 'agent-a', label: 'Alpha' },
+ { id: 'agent-b', label: 'Beta' },
+ ],
+ users: [
+ { id: 'user-1', label: 'Ada' },
+ { id: 'user-2', label: 'Grace' },
+ ],
+ teams: [
+ { id: 'team-1', label: 'Growth' },
+ { id: 'team-2', label: 'Research' },
+ ],
+ })
+ expect(state.warning).toBe('')
+ })
+
+ it('keeps fulfilled access rows and marks the user/team summary incomplete on partial failure', async () => {
+ vi.mocked(api.getAgentUsers).mockResolvedValueOnce({ items: [{ id: 'user-1', name: 'Ada' }] })
+ vi.mocked(api.getAgentUsers).mockRejectedValueOnce(new Error('directory unavailable'))
+ vi.mocked(api.getAgentTeams).mockResolvedValue({ items: [{ id: 'team-1', name: 'Growth' }] })
+ const state = await loadConnectorAccessState(
+ [makeConnector('search')],
+ [
+ makeContext('context-a', 'context-a', ['search']),
+ makeContext('context-b', 'context-b', ['search']),
+ ],
+ [makeHost('agent-a', 'Alpha', 'context-a'), makeHost('agent-b', 'Beta', 'context-b')]
+ )
+
+ expect(state.accessByConnectorKey['mcp-server/search'].users).toEqual([
+ { id: 'user-1', label: 'Ada' },
+ ])
+ expect(state.accessByConnectorKey['mcp-server/search'].teams).toEqual([
+ { id: 'team-1', label: 'Growth' },
+ ])
+ expect(state.warning).toMatch(/may be incomplete/)
+ })
+
+ it('adds through the resolved context using its resource version and keeps unrelated fields', async () => {
+ const context = makeContext('context-resource', 'context-alias', ['other-connector'])
+ await addConnectorToAgentContexts(
+ { name: 'search', namespace: 'mcp-server' },
+ [
+ { name: 'agent-a', contextRef: 'context-alias' },
+ { name: 'agent-b', contextRef: 'context-resource' },
+ ],
+ [context],
+ {}
+ )
+
+ expect(api.updateContext).toHaveBeenCalledTimes(1)
+ expect(api.updateContext).toHaveBeenCalledWith('context-resource', {
+ metadata: { resourceVersion: '7' },
+ spec: {
+ contextId: 'context-alias',
+ mcpServers: ['other-connector', 'search'],
+ sharedFileSystems: [],
+ },
+ })
+ })
+
+ it('preserves the existing context/OAuth restriction and does not write on mismatch', async () => {
+ await expect(
+ addConnectorToAgentContexts(
+ { name: 'search', namespace: 'mcp-server' },
+ [{ name: 'agent-b', contextRef: 'context-b' }],
+ [makeContext('context-a', 'context-a', [])],
+ { contextRef: 'context-a', oauth: { grantScope: 'context' } }
+ )
+ ).rejects.toThrow(/shared OAuth identity/)
+ expect(api.updateContext).not.toHaveBeenCalled()
+ })
+
+ it('removes only the connector from the existing agent context binding', async () => {
+ await removeConnectorFromAgentContext(
+ 'search',
+ { contextRef: 'context-alias', agents: [{ id: 'agent-a', label: 'Alpha' }] },
+ [makeContext('context-resource', 'context-alias', ['search', 'other-connector'])]
+ )
+
+ expect(api.updateContext).toHaveBeenCalledWith('context-resource', {
+ metadata: { resourceVersion: '7' },
+ spec: {
+ contextId: 'context-alias',
+ mcpServers: ['other-connector'],
+ sharedFileSystems: [],
+ },
+ })
+ })
+})
diff --git a/control-ui/components/__tests__/ConnectorDetailAccessPage.test.tsx b/control-ui/components/__tests__/ConnectorDetailAccessPage.test.tsx
new file mode 100644
index 000000000..f9451b5dc
--- /dev/null
+++ b/control-ui/components/__tests__/ConnectorDetailAccessPage.test.tsx
@@ -0,0 +1,263 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import type { ContextResource, HostResource } from '@lib/api'
+import * as api from '@lib/api'
+import { ConnectorDetailAccessProvider } from '../ConnectorDetailAccessProvider'
+import { ConnectorDetailPage } from '../ConnectorDetailPage'
+import { ConnectorDetailProvider } from '../ConnectorDetailProvider'
+
+const navigation = vi.hoisted(() => ({
+ push: vi.fn(),
+ params: { name: 'search', tab: 'agents' } as { name: string; tab?: string },
+ segment: 'agents' as string | null,
+}))
+
+let contexts: ContextResource[] = []
+let hosts: HostResource[] = []
+
+function resetResources() {
+ contexts = [
+ {
+ metadata: { name: 'alpha-context', resourceVersion: '1' },
+ spec: { contextId: 'alpha-context', mcpServers: ['search'], sharedFileSystems: [] },
+ },
+ {
+ metadata: { name: 'beta-context', resourceVersion: '3' },
+ spec: { contextId: 'beta-context', mcpServers: [], sharedFileSystems: [] },
+ },
+ ]
+ hosts = [
+ {
+ metadata: { name: 'agent-alpha' },
+ spec: { host: 'Alpha Agent', contextRef: 'alpha-context' },
+ },
+ {
+ metadata: { name: 'agent-beta' },
+ spec: { host: 'Beta Agent', contextRef: 'beta-context' },
+ },
+ ]
+}
+
+function renderDetail() {
+ return render(
+ <ConnectorDetailProvider>
+ <ConnectorDetailAccessProvider>
+ <ConnectorDetailPage />
+ </ConnectorDetailAccessProvider>
+ </ConnectorDetailProvider>
+ )
+}
+
+vi.mock('next/navigation', () => ({
+ useParams: () => navigation.params,
+ useSelectedLayoutSegment: () => navigation.segment,
+ useRouter: () => ({ push: navigation.push }),
+}))
+vi.mock('@components/AuthGate', () => ({
+ AuthGate: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+}))
+vi.mock('@components/DashboardLayout', () => ({
+ DashboardLayout: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+}))
+vi.mock('@lib/api', async importOriginal => ({
+ ...(await importOriginal<typeof import('@lib/api')>()),
+ getMcpServer: vi.fn(),
+ getContexts: vi.fn(async () => ({ items: contexts })),
+ getHosts: vi.fn(async () => ({ items: hosts })),
+ getAgentUsers: vi.fn(async (name: string) => ({
+ items:
+ name === 'agent-alpha'
+ ? [{ id: 'user-ada', displayName: 'Ada' }]
+ : [{ id: 'user-grace', displayName: 'Grace' }],
+ })),
+ getAgentTeams: vi.fn(async (name: string) => ({
+ items:
+ name === 'agent-alpha'
+ ? [{ id: 'team-growth', name: 'Growth' }]
+ : [{ id: 'team-research', name: 'Research' }],
+ })),
+ updateContext: vi.fn(async (name: string, payload: { spec: { mcpServers: string[] } }) => {
+ contexts = contexts.map(context =>
+ context.metadata?.name === name
+ ? {
+ ...context,
+ metadata: { ...context.metadata, resourceVersion: '2' },
+ spec: { ...context.spec, ...payload.spec },
+ }
+ : context
+ )
+ return contexts.find(context => context.metadata?.name === name)
+ }),
+}))
+
+beforeEach(() => {
+ resetResources()
+ vi.clearAllMocks()
+ navigation.params = { name: 'search', tab: 'agents' }
+ navigation.segment = 'agents'
+ vi.mocked(api.getMcpServer).mockResolvedValue({
+ metadata: { name: 'search', namespace: 'mcp-server' },
+ spec: { description: 'Search the public web' },
+ status: { conditions: [] },
+ })
+})
+
+afterEach(() => cleanup())
+
+describe('connector detail access tabs', () => {
+ it('shows read-only derived User and Team tables without add or remove actions', async () => {
+ const { rerender } = renderDetail()
+ expect(await screen.findByRole('link', { name: 'Alpha Agent' })).toBeVisible()
+
+ navigation.params = { name: 'search', tab: 'users' }
+ navigation.segment = 'users'
+ rerender(
+ <ConnectorDetailProvider>
+ <ConnectorDetailAccessProvider>
+ <ConnectorDetailPage />
+ </ConnectorDetailAccessProvider>
+ </ConnectorDetailProvider>
+ )
+ expect(await screen.findByRole('link', { name: 'Ada' })).toHaveAttribute(
+ 'href',
+ '/users-and-teams/users/user-ada/agents'
+ )
+ expect(screen.getByText(/derived from the agents each user can access/i)).toBeVisible()
+ expect(screen.queryByRole('button', { name: 'Add agent' })).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: /actions for connector access/i })
+ ).not.toBeInTheDocument()
+ expect(screen.queryByRole('menuitem', { name: /remove/i })).not.toBeInTheDocument()
+
+ navigation.params = { name: 'search', tab: 'teams' }
+ navigation.segment = 'teams'
+ rerender(
+ <ConnectorDetailProvider>
+ <ConnectorDetailAccessProvider>
+ <ConnectorDetailPage />
+ </ConnectorDetailAccessProvider>
+ </ConnectorDetailProvider>
+ )
+ expect(await screen.findByRole('link', { name: 'Growth' })).toHaveAttribute(
+ 'href',
+ '/users-and-teams/teams/team-growth/agents'
+ )
+ expect(screen.getByText(/derived from the agents assigned to each team/i)).toBeVisible()
+ expect(screen.queryByRole('button', { name: 'Add agent' })).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: /actions for connector access/i })
+ ).not.toBeInTheDocument()
+ expect(api.getMcpServer).toHaveBeenCalledTimes(1)
+ expect(api.getContexts).toHaveBeenCalledTimes(1)
+ })
+
+ it('adds only through Agents and refreshes the derived user/team summaries without reloading connector details', async () => {
+ const { rerender } = renderDetail()
+ expect(await screen.findByRole('link', { name: 'Alpha Agent' })).toBeVisible()
+ expect(screen.getByRole('button', { name: 'Add agent' })).toBeVisible()
+ fireEvent.click(screen.getByRole('button', { name: 'Add agent' }))
+
+ const dialog = screen.getByRole('dialog', { name: 'Give agents access to this connector' })
+ expect(within(dialog).getByRole('checkbox', { name: /Beta Agent/ })).toBeInTheDocument()
+ fireEvent.click(within(dialog).getByRole('checkbox', { name: /Beta Agent/ }))
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Add to agent' }))
+
+ await waitFor(() => {
+ expect(api.updateContext).toHaveBeenCalledWith(
+ 'beta-context',
+ expect.objectContaining({
+ metadata: { resourceVersion: '3' },
+ spec: expect.objectContaining({ mcpServers: ['search'] }),
+ })
+ )
+ })
+ expect(await screen.findByRole('link', { name: 'Beta Agent' })).toBeVisible()
+ expect(screen.getByRole('status')).toHaveTextContent(/Users and Teams summaries now reflect/)
+
+ navigation.params = { name: 'search', tab: 'users' }
+ navigation.segment = 'users'
+ rerender(
+ <ConnectorDetailProvider>
+ <ConnectorDetailAccessProvider>
+ <ConnectorDetailPage />
+ </ConnectorDetailAccessProvider>
+ </ConnectorDetailProvider>
+ )
+ expect(await screen.findByRole('link', { name: 'Grace' })).toBeVisible()
+
+ navigation.params = { name: 'search', tab: 'teams' }
+ navigation.segment = 'teams'
+ rerender(
+ <ConnectorDetailProvider>
+ <ConnectorDetailAccessProvider>
+ <ConnectorDetailPage />
+ </ConnectorDetailAccessProvider>
+ </ConnectorDetailProvider>
+ )
+ expect(await screen.findByRole('link', { name: 'Research' })).toBeVisible()
+ expect(api.getMcpServer).toHaveBeenCalledTimes(1)
+ expect(api.getContexts).toHaveBeenCalledTimes(2)
+ })
+
+ it('keeps the existing agent removal confirmation for a shared agent context', async () => {
+ contexts = [
+ {
+ metadata: { name: 'shared-context', resourceVersion: '9' },
+ spec: { contextId: 'shared-context', mcpServers: ['search'], sharedFileSystems: [] },
+ },
+ ]
+ hosts.splice(
+ 0,
+ hosts.length,
+ {
+ metadata: { name: 'agent-alpha' },
+ spec: { host: 'Alpha Agent', contextRef: 'shared-context' },
+ },
+ {
+ metadata: { name: 'agent-beta' },
+ spec: { host: 'Beta Agent', contextRef: 'shared-context' },
+ }
+ )
+ const { rerender } = renderDetail()
+ const row = await screen.findByRole('row', { name: /Alpha Agent, Beta Agent/ })
+ fireEvent.click(within(row).getByRole('button', { name: /actions for connector access/i }))
+ fireEvent.click(await screen.findByRole('menuitem', { name: /remove from 2 agents/i }))
+ expect(await screen.findByRole('alertdialog')).toHaveTextContent(
+ /change applies to all of them/
+ )
+ expect(api.updateContext).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Remove' }))
+ await waitFor(() => expect(api.updateContext).toHaveBeenCalledTimes(1))
+ expect(api.updateContext).toHaveBeenCalledWith(
+ 'shared-context',
+ expect.objectContaining({
+ metadata: { resourceVersion: '9' },
+ spec: expect.objectContaining({ mcpServers: [] }),
+ })
+ )
+ expect(await screen.findByText('No agents have access to this connector.')).toBeVisible()
+
+ navigation.params = { name: 'search', tab: 'users' }
+ navigation.segment = 'users'
+ rerender(
+ <ConnectorDetailProvider>
+ <ConnectorDetailAccessProvider>
+ <ConnectorDetailPage />
+ </ConnectorDetailAccessProvider>
+ </ConnectorDetailProvider>
+ )
+ expect(await screen.findByText('No users have access through an assigned agent.')).toBeVisible()
+ })
+
+ it('keeps Add agent disabled when access sources fail before an initial snapshot loads', async () => {
+ vi.mocked(api.getContexts).mockRejectedValueOnce(new Error('Context access is unavailable.'))
+ renderDetail()
+
+ expect(await screen.findByText('Context access is unavailable.')).toBeVisible()
+ expect(screen.getByRole('button', { name: 'Add agent' })).toBeDisabled()
+ expect(
+ screen.queryByRole('dialog', { name: 'Give agents access to this connector' })
+ ).not.toBeInTheDocument()
+ })
+})
diff --git a/control-ui/e2e/connector-detail-access.spec.ts b/control-ui/e2e/connector-detail-access.spec.ts
new file mode 100644
index 000000000..c583b770c
--- /dev/null
+++ b/control-ui/e2e/connector-detail-access.spec.ts
@@ -0,0 +1,164 @@
+import { expect, test } from '@playwright/test'
+
+test('connector detail access tabs manage agents and refresh derived users and teams', async ({
+ page,
+}) => {
+ let connectorDetailRequests = 0
+ let contextReads = 0
+ let contexts = [
+ {
+ metadata: { name: 'alpha-context', resourceVersion: '1' },
+ spec: { contextId: 'alpha-context', mcpServers: ['search'], sharedFileSystems: [] },
+ },
+ {
+ metadata: { name: 'beta-context', resourceVersion: '3' },
+ spec: { contextId: 'beta-context', mcpServers: [], sharedFileSystems: [] },
+ },
+ ]
+
+ await page.addInitScript(() => {
+ window.localStorage.setItem('controlUiAdminToken', 'connector-detail-access-test-token')
+ })
+
+ await page.route('**/api/v1/admin/**', async route => {
+ const request = route.request()
+ const pathname = new URL(request.url()).pathname
+
+ if (pathname.endsWith('/api/v1/admin/auth/me')) {
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ me: { id: 'test-admin', username: 'test-admin', role: 'admin' } }),
+ })
+ return
+ }
+
+ if (pathname.endsWith('/api/v1/admin/mcp-servers/search')) {
+ connectorDetailRequests += 1
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ metadata: { name: 'search', namespace: 'mcp-server' },
+ spec: { description: 'Search the public web' },
+ status: { conditions: [] },
+ }),
+ })
+ return
+ }
+
+ if (pathname.endsWith('/api/v1/admin/contexts') && request.method() === 'GET') {
+ contextReads += 1
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ items: contexts }),
+ })
+ return
+ }
+
+ if (pathname.endsWith('/api/v1/admin/hosts')) {
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ items: [
+ {
+ metadata: { name: 'agent-alpha' },
+ spec: { host: 'Alpha Agent', contextRef: 'alpha-context' },
+ },
+ {
+ metadata: { name: 'agent-beta' },
+ spec: { host: 'Beta Agent', contextRef: 'beta-context' },
+ },
+ ],
+ }),
+ })
+ return
+ }
+
+ if (pathname.endsWith('/api/v1/admin/contexts/beta-context') && request.method() === 'PUT') {
+ const payload = request.postDataJSON()
+ contexts = contexts.map(context =>
+ context.metadata.name === 'beta-context'
+ ? {
+ ...context,
+ metadata: { ...context.metadata, resourceVersion: '4' },
+ spec: { ...context.spec, ...payload.spec },
+ }
+ : context
+ )
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(contexts[1]),
+ })
+ return
+ }
+
+ const userMatch = pathname.match(/\/api\/v1\/admin\/agents\/(agent-(?:alpha|beta))\/users$/)
+ if (userMatch) {
+ const items =
+ userMatch[1] === 'agent-alpha'
+ ? [{ id: 'user-ada', displayName: 'Ada' }]
+ : [{ id: 'user-grace', displayName: 'Grace' }]
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ items }),
+ })
+ return
+ }
+
+ const teamMatch = pathname.match(/\/api\/v1\/admin\/agents\/(agent-(?:alpha|beta))\/teams$/)
+ if (teamMatch) {
+ const items =
+ teamMatch[1] === 'agent-alpha'
+ ? [{ id: 'team-growth', name: 'Growth' }]
+ : [{ id: 'team-research', name: 'Research' }]
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ items }),
+ })
+ return
+ }
+
+ await route.fulfill({ status: 404, contentType: 'application/json', body: '{}' })
+ })
+
+ await page.goto('/connectors/search/agents')
+ await expect(page.getByRole('heading', { name: 'Connector: search' })).toBeVisible()
+ await expect(page.getByRole('link', { name: 'Alpha Agent' })).toBeVisible()
+ await expect(page.getByRole('button', { name: 'Add agent' })).toBeVisible()
+ expect(connectorDetailRequests).toBe(1)
+
+ await page.getByRole('button', { name: 'Add agent' }).click()
+ const dialog = page.getByRole('dialog', { name: 'Give agents access to this connector' })
+ await dialog.getByRole('checkbox', { name: /Beta Agent/ }).check()
+ await dialog.getByRole('button', { name: 'Add to agent' }).click()
+ await expect(page.getByRole('link', { name: 'Beta Agent' })).toBeVisible()
+ await expect(page.getByRole('status')).toContainText(/Users and Teams summaries now reflect/)
+
+ await page.getByRole('tab', { name: 'Users' }).click()
+ await expect(page).toHaveURL(/\/connectors\/search\/users$/)
+ await expect(page.getByRole('link', { name: 'Ada' })).toHaveAttribute(
+ 'href',
+ '/users-and-teams/users/user-ada/agents'
+ )
+ await expect(page.getByRole('link', { name: 'Grace' })).toBeVisible()
+ await expect(page.getByText(/derived from the agents each user can access/i)).toBeVisible()
+ await expect(page.getByRole('button', { name: 'Add agent' })).toHaveCount(0)
+ await expect(page.getByRole('button', { name: /actions for connector access/i })).toHaveCount(0)
+
+ await page.getByRole('tab', { name: 'Teams' }).click()
+ await expect(page).toHaveURL(/\/connectors\/search\/teams$/)
+ await expect(page.getByRole('link', { name: 'Growth' })).toBeVisible()
+ await expect(page.getByRole('link', { name: 'Research' })).toBeVisible()
+ await expect(page.getByText(/derived from the agents assigned to each team/i)).toBeVisible()
+ await expect(page.getByRole('button', { name: 'Add agent' })).toHaveCount(0)
+ await expect(page.getByRole('button', { name: /actions for connector access/i })).toHaveCount(0)
+
+ expect(connectorDetailRequests).toBe(1)
+ expect(contextReads).toBe(2)
+})
diff --git a/control-ui/lib/connectorAccessManagement.ts b/control-ui/lib/connectorAccessManagement.ts
new file mode 100644
index 000000000..f7a8e7ecb
--- /dev/null
+++ b/control-ui/lib/connectorAccessManagement.ts
@@ -0,0 +1,254 @@
+import type {
+ ConnectorAccessPrincipal,
+ ConnectorAccessSummary,
+ ConnectorAccessSummaryMap,
+ ConnectorAgentBinding,
+ ConnectorAgentTarget,
+ ServerRef,
+} from '@components/McpServerTable.types'
+import type { ContextResource, ContextSpec, HostResource, McpServerResource } from './api'
+import { getAgentTeams, getAgentUsers, updateContext } from './api'
+import { mergeAccessSummaries, sortAccessPrincipals } from './connectorAccess'
+import { connectorContextAssignmentError } from './connectorOAuthAccess'
+import { contextAliases, contextForAlias, contextResourceName } from './contextIdentity'
+import { buildContextUpdatePayload, contextMutationError } from './contextMutation'
+
+export type ConnectorAccessState = {
+ contexts: ContextResource[]
+ agentTargets: ConnectorAgentTarget[]
+ bindingsByConnectorName: Record<string, ConnectorAgentBinding[]>
+ accessByConnectorKey: ConnectorAccessSummaryMap
+ warning: string
+}
+
+function resourceName(resource: { metadata?: { name?: string } }): string {
+ return resource.metadata?.name || 'unknown'
+}
+
+function resourceNamespace(resource: { metadata?: { namespace?: string } }): string {
+ return resource.metadata?.namespace || 'default'
+}
+
+export function connectorResourceKey(connector: McpServerResource): string {
+ return `${resourceNamespace(connector)}/${resourceName(connector)}`
+}
+
+function getContextRef(resource: { spec?: Record<string, unknown> }): string {
+ const contextRef = resource.spec?.contextRef
+ return typeof contextRef === 'string' ? contextRef.trim() : ''
+}
+
+function contextSpec(context: ContextResource): ContextSpec {
+ const name = contextResourceName(context)
+ return {
+ contextId: context.spec?.contextId || name,
+ description: context.spec?.description,
+ mcpServers: Array.isArray(context.spec?.mcpServers) ? context.spec.mcpServers : [],
+ sharedFileSystems: context.spec?.sharedFileSystems ?? [],
+ }
+}
+
+export function connectorAgentTargetsFromHosts(
+ hosts: readonly HostResource[]
+): ConnectorAgentTarget[] {
+ return hosts
+ .map(host => {
+ const name = resourceName(host)
+ const displayName =
+ String((host.spec as { host?: string } | undefined)?.host || '').trim() || name
+ return { name, label: displayName, contextRef: getContextRef(host) }
+ })
+ .filter(target => target.contextRef && target.name !== 'unknown')
+ .sort((left, right) => left.label.localeCompare(right.label))
+}
+
+export function connectorAgentBindingsFromContexts(
+ contexts: readonly ContextResource[],
+ agentTargets: readonly ConnectorAgentTarget[]
+): Record<string, ConnectorAgentBinding[]> {
+ const bindings: Record<string, ConnectorAgentBinding[]> = {}
+ for (const context of contexts) {
+ const contextName = contextResourceName(context)
+ const aliases = new Set(contextAliases(context))
+ const agents = agentTargets
+ .filter(target => aliases.has(target.contextRef))
+ .map(target => ({ id: target.name, label: target.label }))
+ if (!contextName || agents.length === 0) continue
+
+ for (const connectorName of context.spec?.mcpServers ?? []) {
+ const list = bindings[connectorName] ?? []
+ list.push({ contextRef: contextName, agents: sortAccessPrincipals(agents) })
+ bindings[connectorName] = list
+ }
+ }
+ for (const list of Object.values(bindings)) {
+ list.sort((left, right) =>
+ (left.agents[0]?.label ?? '').localeCompare(right.agents[0]?.label ?? '')
+ )
+ }
+ return bindings
+}
+
+async function loadAgentAccess(
+ agentName: string
+): Promise<readonly [ConnectorAccessSummary, boolean]> {
+ const [usersResult, teamsResult] = await Promise.allSettled([
+ getAgentUsers(agentName),
+ getAgentTeams(agentName),
+ ])
+ const accessLoadFailed = usersResult.status === 'rejected' || teamsResult.status === 'rejected'
+ const users =
+ usersResult.status === 'fulfilled'
+ ? sortAccessPrincipals(
+ (usersResult.value.items ?? []).map(user => ({
+ id: user.id,
+ label: user.displayName || user.name || user.email || user.id,
+ }))
+ )
+ : []
+ const teams =
+ teamsResult.status === 'fulfilled'
+ ? sortAccessPrincipals(
+ (teamsResult.value.items ?? []).map(team => ({
+ id: team.id,
+ label: team.name || team.id,
+ }))
+ )
+ : []
+
+ return [{ agents: [], users, teams }, accessLoadFailed] as const
+}
+
+export async function loadConnectorAccessState(
+ connectors: readonly McpServerResource[],
+ contexts: readonly ContextResource[],
+ hosts: readonly HostResource[]
+): Promise<ConnectorAccessState> {
+ const agentTargets = connectorAgentTargetsFromHosts(hosts)
+ const bindingsByConnectorName = connectorAgentBindingsFromContexts(contexts, agentTargets)
+ const managedAgentNames = [
+ ...new Set(
+ Object.values(bindingsByConnectorName)
+ .flat()
+ .flatMap(binding => binding.agents.map(agent => agent.id))
+ ),
+ ]
+ const accessResults = await Promise.all(
+ managedAgentNames.map(async agentName => [agentName, await loadAgentAccess(agentName)] as const)
+ )
+ const accessByAgent = new Map(
+ accessResults.map(([agentName, [summary]]) => [agentName, summary] as const)
+ )
+ const accessLoadFailed = accessResults.some(([, [, failed]]) => failed)
+ const accessByConnectorKey = connectors.reduce<ConnectorAccessSummaryMap>((result, connector) => {
+ const name = resourceName(connector)
+ const bindings = bindingsByConnectorName[name] ?? []
+ const bindingAgentNames = bindings.flatMap(binding => binding.agents.map(agent => agent.id))
+ if (bindingAgentNames.length === 0) return result
+
+ const merged = mergeAccessSummaries(
+ bindingAgentNames.map(
+ agentName => accessByAgent.get(agentName) ?? { agents: [], users: [], teams: [] }
+ )
+ )
+ const bindingAgents = bindings.flatMap(binding => binding.agents)
+ const seenAgentIds = new Set(
+ [...bindingAgents, ...merged.agents].map(principal => principal.id)
+ )
+ const agents = [
+ ...bindingAgents,
+ ...merged.agents.filter(principal => !seenAgentIds.has(principal.id)),
+ ]
+ result[connectorResourceKey(connector)] = {
+ ...merged,
+ agents: sortAccessPrincipals([...new Map(agents.map(agent => [agent.id, agent])).values()]),
+ }
+ return result
+ }, {})
+
+ return {
+ contexts: [...contexts],
+ agentTargets,
+ bindingsByConnectorName,
+ accessByConnectorKey,
+ warning: accessLoadFailed
+ ? 'Some connector access data could not be loaded. User or team access may be incomplete.'
+ : '',
+ }
+}
+
+export async function addConnectorToAgentContexts(
+ server: ServerRef,
+ agents: readonly Pick<ConnectorAgentTarget, 'name' | 'contextRef'>[],
+ contexts: readonly ContextResource[],
+ connectorSpec: { contextRef?: unknown; oauth?: unknown } | undefined
+): Promise<void> {
+ const contextRefs = [...new Set(agents.map(agent => agent.contextRef))]
+ const oauthScopeError = connectorContextAssignmentError(connectorSpec, contextRefs)
+ if (oauthScopeError) throw new Error(oauthScopeError)
+
+ const resolvedTargets = contextRefs.map(contextRef => contextForAlias(contexts, contextRef))
+ if (resolvedTargets.some(target => !target)) {
+ throw new Error(
+ 'One or more selected agents could not be resolved. Please refresh and try again.'
+ )
+ }
+ const targets = Array.from(
+ new Map(
+ resolvedTargets.map(
+ target => [contextResourceName(target as ContextResource), target] as const
+ )
+ ).values()
+ ) as ContextResource[]
+
+ await Promise.all(
+ targets.map(context => {
+ const spec = contextSpec(context)
+ return updateContext(
+ contextResourceName(context),
+ buildContextUpdatePayload(context.metadata?.resourceVersion, {
+ ...spec,
+ mcpServers: Array.from(new Set([...spec.mcpServers, server.name])),
+ })
+ )
+ })
+ )
+}
+
+export async function removeConnectorFromAgentContext(
+ serverName: string,
+ binding: ConnectorAgentBinding,
+ contexts: readonly ContextResource[]
+): Promise<void> {
+ const target = contextForAlias(contexts, binding.contextRef)
+ if (!target) {
+ throw new Error('This agent’s connector set could not be loaded. Please refresh and try again.')
+ }
+
+ const spec = contextSpec(target)
+ await updateContext(
+ contextResourceName(target),
+ buildContextUpdatePayload(target.metadata?.resourceVersion, {
+ ...spec,
+ mcpServers: spec.mcpServers.filter(name => name !== serverName),
+ })
+ )
+}
+
+export function connectorAccessMutationError(error: unknown, fallback: string): string {
+ if ((error as { status?: unknown } | null)?.status === 409) {
+ return 'This connector’s access changed since it was loaded. Reload the page and try again.'
+ }
+ if (error instanceof Error && /required version is unavailable/i.test(error.message)) {
+ return 'This connector’s access is missing a server version. Reload the page and try again.'
+ }
+ return contextMutationError(error, fallback)
+}
+
+export function connectorUserAndTeamAccess(
+ connector: McpServerResource,
+ state: ConnectorAccessState
+): { users: ConnectorAccessPrincipal[]; teams: ConnectorAccessPrincipal[] } {
+ const summary = state.accessByConnectorKey[connectorResourceKey(connector)]
+ return { users: summary?.users ?? [], teams: summary?.teams ?? [] }
+}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index b0d529ba0..413ed5ddb 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.724",
+ "version": "0.1.725",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.724",
+ "version": "0.1.725",
"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 d816f2910..c06aa1943 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.724",
+ "version": "0.1.725",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",