Skip to content

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

TypeScript
47.7 KB
Raw Blame
'use client'

import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { ExistingConnectorSecretFields } from '@components/ExistingConnectorSecretFields'
import {
  buildAttachPayload,
  validateCredentialAttach,
  verifyExistingCredentialSelection,
} from '@lib/connectorCredentials'
import type { ExistingCredentialSelection } from '@lib/connectorCredentials.types'
import { CreateFlowPanel } from '@/components/CreateFlowPanel'
import { CreateStepFlow } from '@/components/CreateStepFlow'
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 {
  McpServerUninstallIncompleteError,
  createMcpSecret,
  createMcpServer,
  deleteMcpSecret,
  deleteMcpServer,
  getAgentTeams,
  getAgentUsers,
  getContext,
  getHosts,
  getMcpSecretRollbackRepairIdentity,
  listOrgImages,
  updateContext,
} from '@/lib/api'
import type {
  EgressBinding,
  EnvSecretKeyMapping,
  EnvVar,
  HostResource,
  OrgImage,
  SecretIdentity,
} from '@/lib/api'
import { connectorContextAssignmentError } from '@/lib/connectorOAuthAccess'
import { buildContextUpdatePayload } from '@/lib/contextMutation'
import type { EgressEditorStatus } from '@/lib/egressModel'
import { createPrivateContext } from '@/lib/privateContext'
import { EgressEditor } from '../EgressEditor'
import { DEFAULT_REGISTRY_HOST, buildImageCoordinate } from '../PublisherView/dockerCredential'
import { MCP_SERVER_NAME_PATTERN, TRANSPORT_TYPES } from './constants'
import type { CreateMcpServerFormProps, TransportType } from './types'

const STEPS = ['Connector', 'Access', 'Secrets'] as const

const STEP_DETAILS = [
  {
    description: 'Name, image, and runtime',
    title: 'Connector identity',
    subtitle: 'Register the connector name, image, and runtime configuration.',
  },
  {
    description: 'Choose connector access',
    title: 'Access',
    subtitle: 'Optionally choose the agents that can use this connector right away.',
  },
  {
    description: 'Environment and credentials',
    title: 'Secrets and environment',
    subtitle: 'Add environment variables and optional Secret-backed credentials.',
  },
] as const

type AccessPreview = {
  teams: Array<{ id: string; label: string }>
  users: Array<{ id: string; label: string }>
}

const EMPTY_ACCESS_PREVIEW: AccessPreview = { teams: [], users: [] }

const ACCESS_PREVIEW_GROUPS: Array<{ key: keyof AccessPreview; title: string }> = [
  { key: 'users', title: 'Users' },
  { key: 'teams', title: 'Teams' },
]

type AgentAccessTarget = {
  name: string
  label: string
  contextRef: string
}

type OrgImageOption = {
  value: string
  label: string
  description: string
}

function ImageReferenceCombobox({
  disabled,
  onChange,
  options,
  value,
}: {
  disabled: boolean
  onChange: (value: string) => void
  options: OrgImageOption[]
  value: string
}) {
  const [open, setOpen] = useState(false)
  const rootRef = useRef<HTMLDivElement>(null)
  const matchingOptions = useMemo(() => {
    const query = value.trim().toLowerCase()
    if (!query) return options
    return options.filter(option =>
      [option.label, option.description].some(candidate => candidate.toLowerCase().includes(query))
    )
  }, [options, value])

  useEffect(() => {
    if (!open) return
    function closeOnOutsideClick(event: MouseEvent) {
      if (!rootRef.current?.contains(event.target as Node)) setOpen(false)
    }
    function closeOnEscape(event: KeyboardEvent) {
      if (event.key === 'Escape') setOpen(false)
    }
    document.addEventListener('mousedown', closeOnOutsideClick)
    document.addEventListener('keydown', closeOnEscape)
    return () => {
      document.removeEventListener('mousedown', closeOnOutsideClick)
      document.removeEventListener('keydown', closeOnEscape)
    }
  }, [open])

  return (
    <div className="cu-selection-dropdown cu-image-reference-combobox" ref={rootRef}>
      <TextInput
        aria-autocomplete="list"
        aria-controls="organization-image-options"
        aria-expanded={open && matchingOptions.length > 0}
        aria-haspopup="listbox"
        monospace
        onChange={event => {
          onChange(event.target.value)
          setOpen(true)
        }}
        onFocus={() => setOpen(true)}
        placeholder="us-central1-docker.pkg.dev/my-project/repo/mcp-server:latest"
        disabled={disabled}
        role="combobox"
        value={value}
      />
      {open && matchingOptions.length > 0 ? (
        <div className="cu-selection-dropdown__menu">
          <div
            className="cu-selection-dropdown__list"
            id="organization-image-options"
            role="listbox"
          >
            {matchingOptions.map(option => (
              <button
                key={option.value}
                type="button"
                className="cu-selection-dropdown__option"
                role="option"
                aria-label={option.label}
                aria-selected={option.value === value}
                data-selected={option.value === value ? 'true' : undefined}
                onClick={() => {
                  onChange(option.value)
                  setOpen(false)
                }}
              >
                <span className="cu-selection-dropdown__option-copy">
                  <span className="cu-selection-dropdown__option-label">{option.label}</span>
                  <span className="cu-selection-dropdown__option-description">
                    {option.description}
                  </span>
                </span>
              </button>
            ))}
          </div>
        </div>
      ) : null}
    </div>
  )
}

function parseCommaSeparated(input: string): string[] {
  if (!input.trim()) return []

  return input
    .split(',')
    .map(segment => segment.trim())
    .filter(Boolean)
}

function formatCreateError(err: unknown): string {
  const message = err instanceof Error ? err.message : String(err)
  const bodyStart = message.indexOf(' - ')
  if (bodyStart === -1) return message || 'Failed to create connector'

  const body = message.slice(bodyStart + 3).trim()
  try {
    const parsed = JSON.parse(body) as { message?: string }
    if (parsed?.message) return parsed.message
  } catch {
    // Fall through to the raw apiSend error when the response body is not JSON.
  }
  return message
}

export function CreateMcpServerForm({
  mode = 'inline',
  onCancel,
  onCreated,
  pageHeader,
}: CreateMcpServerFormProps) {
  const { showToast } = useToast()
  const [step, setStep] = useState(0)
  const [name, setName] = useState('')
  const [image, setImage] = useState('')
  const [transportType, setTransportType] = useState<TransportType>('streamableHttp')
  const [port, setPort] = useState(3000)
  const [description, setDescription] = useState('')
  const [selectedAgentNames, setSelectedAgentNames] = useState<string[]>([])
  const [agentTargets, setAgentTargets] = useState<AgentAccessTarget[]>([])
  const [agentsLoading, setAgentsLoading] = useState(true)
  const [agentsError, setAgentsError] = useState('')
  const [accessPreview, setAccessPreview] = useState<AccessPreview>(EMPTY_ACCESS_PREVIEW)
  const [accessPreviewError, setAccessPreviewError] = useState('')
  const [loadingAccessPreview, setLoadingAccessPreview] = useState(false)
  const [orgImages, setOrgImages] = useState<OrgImage[]>([])
  const [orgImageScope, setOrgImageScope] = useState('')
  const [managed, setManaged] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState('')
  const [envVars, setEnvVars] = useState<EnvVar[]>([])
  const [credentialMode, setCredentialMode] = useState<'secret' | 'existing' | 'none' | null>(null)
  const [existingSelection, setExistingSelection] = useState<ExistingCredentialSelection>({
    rows: [],
    ready: false,
  })
  const [envSecretName, setEnvSecretName] = useState('')
  const [envSecretKeys, setEnvSecretKeys] = useState<EnvSecretKeyMapping[]>([])
  const [secretValues, setSecretValues] = useState<string[]>([])
  const [command, setCommand] = useState('')
  const [args, setArgs] = useState('')
  const [egressBindings, setEgressBindings] = useState<EgressBinding[] | undefined>(undefined)
  const [egressStatus, setEgressStatus] = useState<EgressEditorStatus | null>(null)

  const nameValid = MCP_SERVER_NAME_PATTERN.test(name) && name.length <= 63
  const egressValid = !egressStatus || egressStatus.errors.length === 0
  const useEnvSecret = credentialMode === 'secret'
  const hasCompleteSecretMapping = envSecretKeys.some((row, index) => {
    return Boolean(row.secretKey.trim() && row.envVar.trim() && (secretValues[index] ?? '').trim())
  })
  const hasIncompleteSecretMapping = envSecretKeys.some((row, index) => {
    const values = [row.secretKey.trim(), row.envVar.trim(), (secretValues[index] ?? '').trim()]
    return values.some(Boolean) && !values.every(Boolean)
  })
  const existingServer = useMemo(() => ({ spec: { env: envVars } }), [envVars])
  const existingValid =
    existingSelection.ready &&
    Boolean(existingSelection.secret) &&
    !validateCredentialAttach(
      'use-existing',
      existingSelection.secret?.name ?? '',
      existingSelection.rows,
      existingServer,
      existingSelection.secret,
      { storedKeysOnly: true }
    )
  const credentialsConfigured =
    credentialMode === 'none' ||
    (credentialMode === 'existing' && existingValid) ||
    (credentialMode === 'secret' &&
      Boolean(envSecretName.trim()) &&
      hasCompleteSecretMapping &&
      !hasIncompleteSecretMapping)
  const canSubmit =
    Boolean(name && image) && nameValid && egressValid && credentialsConfigured && !submitting
  const connectorComplete = Boolean(name && image && nameValid) && egressValid
  // The Access step is optional: a connector with no agents selected is valid
  // and simply is not reachable by any agent until one is granted from the
  // Installed Connectors list.
  const canContinue = step === 0 ? connectorComplete : true
  const orgImageOptions = useMemo<OrgImageOption[]>(() => {
    if (!orgImageScope) return []

    return orgImages.flatMap(orgImage => {
      const tags = orgImage.tags ?? []
      if (tags.length === 0) {
        const coordinate = `${DEFAULT_REGISTRY_HOST}/${orgImageScope.replace(/^@/, '')}/${orgImage.name}`
        return [{ value: coordinate, label: orgImage.name, description: coordinate }]
      }
      return tags.map(tag => {
        const coordinate = buildImageCoordinate(
          DEFAULT_REGISTRY_HOST,
          orgImageScope,
          orgImage.name,
          tag
        )
        return { value: coordinate, label: `${orgImage.name}:${tag}`, description: coordinate }
      })
    })
  }, [orgImageScope, orgImages])

  useEffect(() => {
    let cancelled = false
    setAgentsLoading(true)
    setAgentsError('')

    getHosts()
      .then(result => {
        if (cancelled) return
        const targets = ((result.items ?? []) as HostResource[])
          .map(host => {
            const agentName = host.metadata?.name || ''
            const contextRef = String(host.spec?.contextRef ?? '').trim()
            const label = getAgentDisplayName(agentName) || agentName
            return { name: agentName, label, contextRef }
          })
          .filter(target => target.name && target.contextRef)
          .sort((left, right) => left.label.localeCompare(right.label))
        setAgentTargets(targets)
      })
      .catch(loadError => {
        if (cancelled) return
        setAgentTargets([])
        setAgentsError(
          loadError instanceof Error ? loadError.message : 'Failed to load available agents'
        )
      })
      .finally(() => {
        if (!cancelled) setAgentsLoading(false)
      })

    return () => {
      cancelled = true
    }
  }, [])

  // Preview: the users/teams that already have access to the selected agents.
  // Adding this connector makes it usable by exactly those people.
  useEffect(() => {
    if (selectedAgentNames.length === 0) {
      setAccessPreview(EMPTY_ACCESS_PREVIEW)
      setAccessPreviewError('')
      setLoadingAccessPreview(false)
      return
    }

    let cancelled = false
    setLoadingAccessPreview(true)
    setAccessPreviewError('')

    void (async () => {
      const results = await Promise.all(
        selectedAgentNames.map(async agentName => {
          const [usersResult, teamsResult] = await Promise.allSettled([
            getAgentUsers(agentName),
            getAgentTeams(agentName),
          ])
          return { usersResult, teamsResult }
        })
      )
      if (cancelled) return

      const failed = results.some(
        result =>
          result.usersResult.status === 'rejected' || result.teamsResult.status === 'rejected'
      )
      const users = results.flatMap(result =>
        result.usersResult.status === 'fulfilled'
          ? (result.usersResult.value.items ?? []).map(user => ({
              id: user.id,
              label: user.displayName || user.name || user.email || user.id,
            }))
          : []
      )
      const teams = results.flatMap(result =>
        result.teamsResult.status === 'fulfilled'
          ? (result.teamsResult.value.items ?? []).map(team => ({
              id: team.id,
              label: team.name || team.id,
            }))
          : []
      )
      const byLabel = (left: { label: string }, right: { label: string }) =>
        left.label.localeCompare(right.label)
      const dedupe = <T extends { id: string }>(items: T[]): T[] =>
        Array.from(new Map(items.map(item => [item.id, item])).values())
      setAccessPreview({
        users: dedupe(users).sort(byLabel),
        teams: dedupe(teams).sort(byLabel),
      })
      setAccessPreviewError(
        failed
          ? 'Some access information could not be loaded. The lists below may be incomplete.'
          : ''
      )
      setLoadingAccessPreview(false)
    })()

    return () => {
      cancelled = true
    }
  }, [selectedAgentNames])

  useEffect(() => {
    let cancelled = false

    listOrgImages()
      .then(result => {
        if (cancelled) return
        setOrgImageScope(result.org)
        setOrgImages(result.images ?? [])
      })
      .catch(() => {
        if (!cancelled) {
          // Image selection is a convenience. Creating a connector with a
          // manual image coordinate must still work if registry listing is off.
          setOrgImageScope('')
          setOrgImages([])
        }
      })

    return () => {
      cancelled = true
    }
  }, [])

  function canSelectStep(targetStep: number) {
    if (targetStep <= step) return true
    return connectorComplete
  }

  const handleEgressChange = useCallback(
    (nextBindings: EgressBinding[] | undefined, nextStatus: EgressEditorStatus) => {
      setEgressBindings(nextBindings)
      setEgressStatus(nextStatus)
    },
    []
  )

  function addEnvVar() {
    setEnvVars(previous => [...previous, { name: '', value: '' }])
  }

  function removeEnvVar(index: number) {
    setEnvVars(previous => previous.filter((_, itemIndex) => itemIndex !== index))
  }

  function updateEnvVar(index: number, field: 'name' | 'value', value: string) {
    setEnvVars(previous =>
      previous.map((row, itemIndex) => (itemIndex === index ? { ...row, [field]: value } : row))
    )
  }

  function addSecretKey() {
    setEnvSecretKeys(previous => [...previous, { secretKey: '', envVar: '' }])
    setSecretValues(previous => [...previous, ''])
  }

  function removeSecretKey(index: number) {
    setEnvSecretKeys(previous => previous.filter((_, itemIndex) => itemIndex !== index))
    setSecretValues(previous => previous.filter((_, itemIndex) => itemIndex !== index))
  }

  function updateSecretKey(index: number, field: 'secretKey' | 'envVar', value: string) {
    setEnvSecretKeys(previous =>
      previous.map((row, itemIndex) => (itemIndex === index ? { ...row, [field]: value } : row))
    )
  }

  function updateSecretValue(index: number, value: string) {
    setSecretValues(previous =>
      previous.map((row, itemIndex) => (itemIndex === index ? value : row))
    )
  }

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (step < STEPS.length - 1) {
      if (canContinue) setStep(current => Math.min(STEPS.length - 1, current + 1))
      return
    }

    if (credentialMode === null) {
      setError('Choose whether this connector needs credentials before creating it.')
      return
    }
    if (!canSubmit) return

    // New Secrets require values; existing references use metadata-only validation.
    if (useEnvSecret && envSecretName.trim()) {
      const builtSecretData: Record<string, string> = {}
      envSecretKeys.forEach((row, index) => {
        const key = row.secretKey.trim()
        const value = secretValues[index] ?? ''
        if (key && value) {
          builtSecretData[key] = value
        }
      })

      if (hasIncompleteSecretMapping) {
        setError('Complete every Secret key, environment variable, and value before creating it.')
        return
      }
      if (Object.keys(builtSecretData).length === 0) {
        setError('Add at least one key-value pair or disable envSecret')
        return
      }
    }

    setSubmitting(true)
    setError('')

    if (credentialMode === 'existing') {
      try {
        await verifyExistingCredentialSelection(
          existingSelection.secret?.name ?? '',
          existingSelection.rows,
          existingSelection.secret,
          existingServer
        )
      } catch {
        setError(
          'The selected Secret or its keys could not be verified. Refresh Secrets and review the selection before creating the connector.'
        )
        setExistingSelection(current => ({ ...current, ready: false }))
        setSubmitting(false)
        return
      }
    }

    // Resolve the write targets: the distinct private scopes of the selected
    // agents. With no selection the connector gets its own private scope (an
    // implementation detail, same as Marketplace installs) so the resource
    // contract stays satisfied without exposing any concept to the user.
    const selectedTargets = selectedAgentNames
      .map(agentName => agentTargets.find(target => target.name === agentName))
      .filter((target): target is AgentAccessTarget => Boolean(target))
    const selectedContextRefs = Array.from(
      new Set(selectedTargets.map(target => target.contextRef))
    )

    let primaryContextRef: string
    try {
      primaryContextRef =
        selectedContextRefs[0] ??
        (await createPrivateContext(
          {
            subject: name,
            description: `Connector access scope for ${name}`,
            mcpServers: [name],
          },
          'We couldn’t finish creating this connector — please try again.'
        ))
    } catch (scopeError) {
      setError(formatCreateError(scopeError))
      setSubmitting(false)
      return
    }

    const spec: Parameters<typeof createMcpServer>[0]['spec'] = {
      image,
      contextRef: primaryContextRef,
      description: description || undefined,
      enabled: true,
      managed,
      transport: {
        type: transportType,
        ...(transportType !== 'stdio' ? { port } : {}),
        ...(transportType !== 'stdio'
          ? { url: `http://${name}.mcp-server.svc.cluster.local:${port}/mcp` }
          : {}),
      },
    }

    const filteredEnv = envVars.filter(row => row.name.trim() !== '')
    if (filteredEnv.length > 0) {
      spec.env = filteredEnv
    }

    if (useEnvSecret) {
      const filteredKeys = envSecretKeys.filter(
        row => row.secretKey.trim() !== '' && row.envVar.trim() !== ''
      )
      if (envSecretName.trim() && filteredKeys.length > 0) {
        spec.envSecret = { name: envSecretName.trim(), keys: filteredKeys }
      }
    }

    if (credentialMode === 'existing') {
      spec.envSecret = buildAttachPayload(
        existingSelection.secret!.name,
        existingSelection.rows
      ).reference
    }

    const parsedCommand = parseCommaSeparated(command)
    if (parsedCommand.length > 0) {
      spec.command = parsedCommand
    }

    const parsedArgs = parseCommaSeparated(args)
    if (parsedArgs.length > 0) {
      spec.args = parsedArgs
    }

    if (egressBindings && egressBindings.length > 0) {
      spec.egressBindings = egressBindings
    }

    // Pre-compute the Secret payload once so rollback and creation agree on
    // "did we actually create a Secret?".
    const secretData: Record<string, string> = {}
    if (useEnvSecret && envSecretName.trim()) {
      envSecretKeys.forEach((row, index) => {
        const value = secretValues[index] || ''
        if (row.secretKey.trim() && value) {
          secretData[row.secretKey.trim()] = value
        }
      })
    }
    const willCreateSecret =
      useEnvSecret && envSecretName.trim().length > 0 && Object.keys(secretData).length > 0

    let createdSecretName: string | null = null
    let createdSecretIdentity: SecretIdentity | undefined
    try {
      if (willCreateSecret) {
        const secretName = envSecretName.trim()
        const created = await createMcpSecret(secretName, secretData)
        createdSecretName = secretName
        if (created.uid && created.resourceVersion) {
          createdSecretIdentity = { uid: created.uid, resourceVersion: created.resourceVersion }
        }
      }

      const createdServer = await createMcpServer({
        metadata: { name },
        spec,
      })

      const oauthScopeError = connectorContextAssignmentError(
        createdServer.spec,
        selectedContextRefs
      )
      if (oauthScopeError) {
        const rollbackFailures: string[] = []
        let incompleteUninstall: McpServerUninstallIncompleteError | null = null
        try {
          await deleteMcpServer(name)
        } catch (rollbackError) {
          if (rollbackError instanceof McpServerUninstallIncompleteError) {
            incompleteUninstall = rollbackError
          } else {
            rollbackFailures.push('connector')
          }
        }
        if (createdSecretName) {
          try {
            await deleteMcpSecret(createdSecretName, createdSecretIdentity)
            createdSecretName = null
            createdSecretIdentity = undefined
          } catch {
            rollbackFailures.push('Secret')
          }
        }
        const rollbackNotes = [
          incompleteUninstall
            ? `Automatic cleanup of connector "${name}" is incomplete${incompleteUninstall.pendingSummary}; it ${incompleteUninstall.installState}. Delete it from the Installed Connectors list to finish.`
            : '',
          rollbackFailures.length > 0
            ? `Automatic cleanup failed for the ${rollbackFailures.join(' and ')}; remove it before retrying.`
            : '',
        ].filter(Boolean)
        setError([oauthScopeError, ...rollbackNotes].join(' '))
        return
      }

      // Give the selected agents access. Each agent's private scope gets an
      // additive write with its own loaded resourceVersion; failures are
      // collected so the operator knows the connector itself was created.
      const failedAgents: string[] = []
      await Promise.all(
        selectedContextRefs.map(async contextRef => {
          try {
            const context = await getContext(contextRef)
            const existingServers = context.spec?.mcpServers ?? []

            if (!existingServers.includes(name)) {
              await updateContext(
                contextRef,
                buildContextUpdatePayload(context.metadata?.resourceVersion, {
                  contextId: context.spec?.contextId ?? contextRef,
                  description: context.spec?.description,
                  mcpServers: [...existingServers, name],
                  sharedFileSystems: context.spec?.sharedFileSystems ?? [],
                })
              )
            }
          } catch {
            const affected = selectedTargets
              .filter(target => target.contextRef === contextRef)
              .map(target => target.label)
            failedAgents.push(...affected)
          }
        })
      )

      if (failedAgents.length > 0) {
        setError(
          `Connector created, but we couldn't give access to ${failedAgents.join(', ')}. ` +
            `Grant "${name}" to those agents from the Installed Connectors list.`
        )
        setSubmitting(false)
        return
      }

      showToast('Connector created successfully.', { tone: 'success' })
      window.setTimeout(() => {
        onCreated()
      }, 600)
    } catch (submitError) {
      // Roll back only a Secret this submission created. A successful legacy
      // create may use the bounded bodyless-delete compatibility path. A
      // rejected create is eligible only when its exact repair response gives
      // us a complete CAS identity; incomplete repair data never falls back to
      // a bodyless delete.
      let cleanupError: unknown
      let cleanupSecretName = createdSecretName
      let cleanupSecretIdentity = createdSecretIdentity
      if (!cleanupSecretName && willCreateSecret) {
        const repairIdentity = getMcpSecretRollbackRepairIdentity(submitError, envSecretName.trim())
        if (repairIdentity) {
          cleanupSecretName = repairIdentity.name
          cleanupSecretIdentity = {
            uid: repairIdentity.uid,
            resourceVersion: repairIdentity.resourceVersion,
          }
        }
      }
      if (cleanupSecretName) {
        try {
          await deleteMcpSecret(cleanupSecretName, cleanupSecretIdentity)
        } catch (error) {
          cleanupError = error
        }
      }
      const primaryError = formatCreateError(submitError)
      // The message names the object it refers to. Telling an operator to
      // review the leftover Secret is only actionable once they know which one
      // was left behind.
      setError(
        cleanupError
          ? `${primaryError} Cleanup of the created Secret "${cleanupSecretName}" also failed: ${formatCreateError(
              cleanupError
            )}. Refresh the page and review the Secret before taking further action.`
          : primaryError
      )
    } finally {
      setSubmitting(false)
    }
  }

  const formContent = (
    <>
      {mode === 'inline' ? (
        <div className="cu-modal-panel__head">
          <div>
            <h3 className="cu-form-section__title">Create connector</h3>
            <p className="cu-form-section__description">
              Register a new connector and optionally create its managed deployment metadata.
            </p>
          </div>
          <Button
            aria-label="Close"
            className="cu-btn--icon"
            disabled={submitting}
            onClick={onCancel}
            variant="ghost"
          >
            <IconX height={18} width={18} />
          </Button>
        </div>
      ) : null}

      <form onSubmit={handleSubmit}>
        <CreateStepFlow
          ariaLabel="Create connector steps"
          className="cu-create-step-flow--3"
          currentStep={step}
          onStepChange={setStep}
          canSelectStep={canSelectStep}
          steps={STEP_DETAILS}
          stepLabels={STEPS}
          titleId="create-connector-step-title"
        >
          {step === 0 ? (
            <div className="cu-form-stack cu-agent-form-stack">
              <Field
                description="Kubernetes resource name: lowercase alphanumeric and hyphens, max 63 chars."
                error={
                  name.length > 0 && !nameValid
                    ? 'Name must match the Kubernetes DNS label format.'
                    : undefined
                }
                label="Name"
                required
              >
                <TextInput
                  invalid={name.length > 0 && !nameValid}
                  monospace
                  onChange={event =>
                    setName(event.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))
                  }
                  placeholder="my-mcp-server"
                  disabled={submitting}
                  autoFocus
                  value={name}
                />
              </Field>

              <Field label="Description">
                <TextInput
                  onChange={event => setDescription(event.target.value)}
                  placeholder="Optional description of this connector"
                  disabled={submitting}
                  value={description}
                />
              </Field>

              <Field
                description="Choose one of your organization’s images or enter another container image URL."
                label="Image"
                required
              >
                <ImageReferenceCombobox
                  disabled={submitting}
                  onChange={setImage}
                  options={orgImageOptions}
                  value={image}
                />
              </Field>

              <details className="cu-advanced-details">
                <summary>Advanced options</summary>
                <p className="cu-advanced-details__hint">
                  Runtime, container overrides, and network egress. The defaults work for most
                  connectors.
                </p>
                <div className="cu-form-stack cu-agent-form-stack">
                  <div className="cu-form-grid cu-form-grid--2">
                    <Field label="Transport Type">
                      <SelectInput
                        onChange={event => setTransportType(event.target.value as TransportType)}
                        disabled={submitting}
                        value={transportType}
                      >
                        {TRANSPORT_TYPES.map(option => (
                          <option key={option.value} value={option.value}>
                            {option.label}
                          </option>
                        ))}
                      </SelectInput>
                    </Field>

                    {transportType !== 'stdio' ? (
                      <Field description="Port the connector listens on." label="Port">
                        <TextInput
                          narrow
                          onChange={event => setPort(parseInt(event.target.value, 10) || 3000)}
                          type="number"
                          disabled={submitting}
                          value={port}
                        />
                      </Field>
                    ) : null}
                  </div>

                  <Field
                    description={
                      <>
                        <strong>Managed:</strong> Evenfire creates the Deployment, Service, and
                        NetworkPolicies. <strong>Not managed:</strong> you deploy the pod yourself
                        and Evenfire only registers it for discovery.
                      </>
                    }
                    label="Managed"
                  >
                    <SelectInput
                      onChange={event => setManaged(event.target.value === 'true')}
                      disabled={submitting}
                      value={managed ? 'true' : 'false'}
                    >
                      <option value="true">
                        Yes — Evenfire creates and manages the Deployment, Service, and
                        NetworkPolicies
                      </option>
                      <option value="false">
                        No — I will deploy the pod myself (discovery only)
                      </option>
                    </SelectInput>
                  </Field>

                  <FormSection
                    description="Optional container entrypoint and command overrides."
                    title="Container Overrides"
                  >
                    <Field
                      description='Comma-separated values, for example "node, server.js".'
                      label="Command"
                    >
                      <TextInput
                        monospace
                        onChange={event => setCommand(event.target.value)}
                        placeholder="node, server.js"
                        disabled={submitting}
                        value={command}
                      />
                    </Field>

                    <Field
                      description='Comma-separated values, for example "--port, 3000, --headless".'
                      label="Args"
                    >
                      <TextInput
                        monospace
                        onChange={event => setArgs(event.target.value)}
                        placeholder="--port, 3000, --headless"
                        disabled={submitting}
                        value={args}
                      />
                    </Field>
                  </FormSection>

                  <div className="cu-form-stack cu-agent-form-stack cu-agent-form-stack--wide">
                    <EgressEditor allowCidr onChange={handleEgressChange} />
                  </div>
                </div>
              </details>
            </div>
          ) : null}

          {step === 1 ? (
            <div className="cu-form-stack cu-agent-form-stack cu-agent-form-stack--wide">
              <section className="cu-form-section">
                <div className="cu-form-section__header">
                  <h3 className="cu-form-section__title">Agent access</h3>
                  <p className="cu-form-section__description">
                    Optionally choose the agents that can use this connector right away. You can
                    also grant access later from the Installed Connectors list.
                  </p>
                </div>
                <Field
                  description={
                    agentsLoading
                      ? 'Loading available agents...'
                      : selectedAgentNames.length > 0
                        ? 'The connector will be usable by everyone who already has access to the selected agents.'
                        : 'No agents selected: the connector is created but cannot be used by any agent until you grant access.'
                  }
                  error={agentsError || undefined}
                  label="Agents"
                >
                  <SelectionDropdown
                    id="create-connector-agents"
                    multiple
                    onChange={setSelectedAgentNames}
                    disabled={submitting || agentsLoading}
                    value={selectedAgentNames}
                    options={agentTargets.map(target => ({
                      value: target.name,
                      label: target.label,
                    }))}
                    placeholder={agentsLoading ? 'Loading agents...' : 'Select agents...'}
                    searchPlaceholder="Search agents..."
                    emptyLabel="No agents available."
                    selectionLabel="Selected agents"
                  />
                </Field>

                {loadingAccessPreview ? (
                  <p className="cu-muted">Loading agent access…</p>
                ) : selectedAgentNames.length > 0 ? (
                  <>
                    {accessPreviewError ? (
                      <p className="cu-banner cu-banner--warn" role="status">
                        {accessPreviewError}
                      </p>
                    ) : null}
                    <div className="cu-entity-access__intro">
                      <span>Access preview</span>
                      <p>
                        These people already have access to the selected agents and will be able to
                        use this connector.
                      </p>
                    </div>
                    <section className="cu-entity-access" aria-label="Agent access preview">
                      <section className="cu-entity-access__group" data-kind="agents">
                        <div className="cu-entity-access__heading">
                          <h4>Agents</h4>
                          <span>{selectedAgentNames.length}</span>
                        </div>
                        <ul className="cu-entity-access__list">
                          {selectedAgentNames.map(agentName => {
                            const target = agentTargets.find(
                              candidate => candidate.name === agentName
                            )
                            return (
                              <li key={agentName}>
                                <span>{target?.label ?? agentName}</span>
                              </li>
                            )
                          })}
                        </ul>
                      </section>
                      {ACCESS_PREVIEW_GROUPS.map(group => (
                        <section
                          className="cu-entity-access__group"
                          data-kind={group.key}
                          key={group.key}
                        >
                          <div className="cu-entity-access__heading">
                            <h4>{group.title}</h4>
                            <span>{accessPreview[group.key].length}</span>
                          </div>
                          {accessPreview[group.key].length > 0 ? (
                            <ul className="cu-entity-access__list">
                              {accessPreview[group.key].map(principal => (
                                <li key={principal.id}>
                                  <span>{principal.label}</span>
                                </li>
                              ))}
                            </ul>
                          ) : (
                            <p className="cu-muted">
                              No {group.title.toLowerCase()} have access yet.
                            </p>
                          )}
                        </section>
                      ))}
                    </section>
                  </>
                ) : null}
              </section>
            </div>
          ) : null}

          {step === 2 ? (
            <div className="cu-form-stack cu-agent-form-stack cu-agent-form-stack--wide">
              <FormSection
                description="Additional environment variables injected into the container."
                title="Environment Variables"
              >
                {envVars.length > 0 ? (
                  <div className="cu-form-grid">
                    {envVars.map((row, index) => (
                      <div className="cu-form-inline" key={`env-${index}`}>
                        <TextInput
                          className="cu-input--monospace"
                          onChange={event => updateEnvVar(index, 'name', event.target.value)}
                          placeholder="NAME"
                          disabled={submitting}
                          value={row.name}
                        />
                        <TextInput
                          className="cu-input--monospace"
                          onChange={event => updateEnvVar(index, 'value', event.target.value)}
                          placeholder="value"
                          disabled={submitting}
                          value={row.value}
                        />
                        <button
                          type="button"
                          className="cu-btn cu-btn--icon cu-btn--danger-icon"
                          onClick={() => removeEnvVar(index)}
                          disabled={submitting}
                          aria-label={`Remove environment variable row ${index + 1}`}
                          title={`Remove environment variable row ${index + 1}`}
                        >
                          <IconX width={16} height={16} />
                        </button>
                      </div>
                    ))}
                  </div>
                ) : null}

                <Button onClick={addEnvVar} size="sm" disabled={submitting}>
                  Add Env Var
                </Button>
              </FormSection>

              <FormSection
                description="Choose this explicitly so keyless connectors are not confused with connectors missing credentials."
                title="Credentials"
              >
                <div className="cu-agent-radio-group" role="radiogroup" aria-label="Credentials">
                  <label className="cu-agent-radio cu-agent-radio--card">
                    <input
                      name="credential-mode"
                      type="radio"
                      checked={credentialMode === 'secret'}
                      disabled={submitting}
                      onChange={() => setCredentialMode('secret')}
                    />
                    <span className="cu-agent-radio__copy">
                      <span className="cu-agent-radio__title">Create Kubernetes Secret</span>
                      <span className="cu-agent-radio__description">
                        Enter API keys or tokens now. Evenfire creates the Secret before the
                        connector.
                      </span>
                    </span>
                  </label>
                  <label className="cu-agent-radio cu-agent-radio--card">
                    <input
                      name="credential-mode"
                      type="radio"
                      checked={credentialMode === 'existing'}
                      disabled={submitting}
                      onChange={() => setCredentialMode('existing')}
                    />
                    <span className="cu-agent-radio__copy">
                      <span className="cu-agent-radio__title">Use an existing Secret</span>
                      <span className="cu-agent-radio__description">
                        Reuse stored credentials from Secrets → Connectors and map their keys.
                      </span>
                    </span>
                  </label>
                  <label className="cu-agent-radio cu-agent-radio--card">
                    <input
                      name="credential-mode"
                      type="radio"
                      checked={credentialMode === 'none'}
                      disabled={submitting}
                      onChange={() => setCredentialMode('none')}
                    />
                    <span className="cu-agent-radio__copy">
                      <span className="cu-agent-radio__title">No credentials required</span>
                      <span className="cu-agent-radio__description">
                        Use this only for keyless connectors, such as Playwright or public
                        documentation MCPs.
                      </span>
                    </span>
                  </label>
                </div>

                {credentialMode === null ? (
                  <p className="cu-form-section__description">
                    Choose an option to enable Create connector.
                  </p>
                ) : null}

                {credentialMode === 'existing' ? (
                  <ExistingConnectorSecretFields
                    server={existingServer}
                    disabled={submitting}
                    onChange={setExistingSelection}
                  />
                ) : null}

                {useEnvSecret ? (
                  <>
                    <Field
                      description={
                        <>
                          Name for the new Secret. Choose “Use an existing Secret” to reuse stored
                          credentials.
                        </>
                      }
                      label="Kubernetes Secret Name"
                      htmlFor="connector-new-secret-name"
                    >
                      <TextInput
                        monospace
                        id="connector-new-secret-name"
                        onChange={event => setEnvSecretName(event.target.value)}
                        placeholder="brave-search-credentials"
                        disabled={submitting}
                        value={envSecretName}
                      />
                    </Field>

                    <div className="cu-form-grid">
                      {envSecretKeys.map((row, index) => (
                        <div className="cu-form-inline" key={`secret-${index}`}>
                          <TextInput
                            monospace
                            onChange={event =>
                              updateSecretKey(index, 'secretKey', event.target.value)
                            }
                            placeholder="api-key"
                            disabled={submitting}
                            value={row.secretKey}
                          />
                          <TextInput
                            monospace
                            onChange={event => updateSecretKey(index, 'envVar', event.target.value)}
                            placeholder="BRAVE_API_KEY"
                            disabled={submitting}
                            value={row.envVar}
                          />
                          <TextInput
                            autoComplete="off"
                            monospace
                            onChange={event => updateSecretValue(index, event.target.value)}
                            placeholder="sk-..."
                            type="password"
                            disabled={submitting}
                            value={secretValues[index] || ''}
                          />
                          <button
                            type="button"
                            className="cu-btn cu-btn--icon cu-btn--danger-icon"
                            onClick={() => removeSecretKey(index)}
                            disabled={submitting}
                            aria-label={`Remove secret key mapping row ${index + 1}`}
                            title={`Remove secret key mapping row ${index + 1}`}
                          >
                            <IconX width={16} height={16} />
                          </button>
                        </div>
                      ))}
                    </div>

                    <Button onClick={addSecretKey} size="sm" disabled={submitting}>
                      Add Key Mapping
                    </Button>

                    <p className="cu-form-section__description">
                      Enter each value to create a reusable Secret before the connector. To use
                      credentials already stored in Secrets → Connectors, choose “Use an existing
                      Secret”.
                    </p>
                  </>
                ) : null}
              </FormSection>
            </div>
          ) : null}

          {error ? (
            <div role="alert" className="cu-banner cu-banner--error">
              {error}
            </div>
          ) : null}

          <div className={mode === 'page' ? 'cu-create-actions' : 'cu-modal-panel__foot'}>
            <Button
              disabled={submitting}
              onClick={() => (step === 0 ? onCancel() : setStep(current => current - 1))}
              size="sm"
              variant="ghost"
            >
              {step === 0 ? 'Cancel' : 'Back'}
            </Button>
            {step < STEPS.length - 1 ? (
              <Button
                disabled={submitting || !canContinue}
                onClick={() => setStep(current => Math.min(STEPS.length - 1, current + 1))}
                size="sm"
                variant="primary"
              >
                Continue
              </Button>
            ) : (
              <Button disabled={!canSubmit} size="sm" type="submit" variant="primary">
                {submitting ? 'Creating…' : 'Create connector'}
              </Button>
            )}
          </div>
        </CreateStepFlow>
      </form>
    </>
  )

  if (mode === 'page' && pageHeader) {
    return <CreateFlowPanel header={pageHeader}>{formContent}</CreateFlowPanel>
  }

  return (
    <div className={mode === 'page' ? 'cu-agent-create-panel' : 'cu-form-section'}>
      {formContent}
    </div>
  )
}