internal/cli package¶
This package implements the mcp-runtime CLI commands. Each subsection walks through the files in order of execution and major blocks of lines.
output.go¶
- L1 declares package and imports; L9-L16 define ANSI color helpers used for readable console output.
- L18-L33:
printSection/printStep/printSuccess/printError/printWarn/printInfoformat labeled messages to stdout/stderr for consistent UX.
bootstrap.go¶
- L1-L10: Package and imports for cobra/zap and stdlib helpers used by the preflight workflow.
- L16-L72:
NewBootstrapCmdwires thebootstrapcobra command. Flags:--apply(default false; only automated for k3s) and--provider(defaultauto). TheRunEbody detects the provider, runsrunBootstrapPreflight, and — only when--applyis set — branches per provider: k3s applies the bundled CoreDNS and local-path manifests; everything else (rke2,kubeadm,generic) prints a warning that apply is not yet automated. - L74-L88:
detectProvidershells out tokubectl get nodes -o jsonpath=...kubeletVersionand substring-matchesk3s/rke2, returninggenericotherwise. - L90-L120:
runBootstrapPreflightchecks kubectl connectivity, a CoreDNS deployment inkube-system, a default StorageClass annotation, thetraefikIngressClass, and themetallb-systemnamespace. Missing pieces produce warnings (not errors) so users can decide what to install. - L122-L138:
checkDeploymentExistsandcheckHasDefaultStorageClasshelpers used by the preflight loop. - L140-L181:
bootstrapApplyK3sis the only automated apply path. It confirms the k3s server-node manifests exist on disk under/var/lib/rancher/k3s/server/manifests, applies them viakubectl, then waits for the CoreDNS and local-path-provisioner rollouts. Best-effort, it also prints node disk-pressure status. - L183-L189:
kubectlOutputthin wrapper that builds a kubectl command via the runner and returns its captured output.
access.go¶
- L1-L15: Package, imports, and the resource constants
accessGrantResource(mcpaccessgrant) andaccessSessionResource(mcpagentsession) used throughout the file. - L17-L28:
AccessManagerstruct,NewAccessManagerconstructor, andDefaultAccessManagerfactory bound to the package-levelkubectlClient. - L30-L46:
NewAccessCmdandNewAccessCmdWithManagerbuild theaccessroot command and attach thegrantandsessionsubtrees. - L48-L78:
newAccessGrantCmdandnewAccessSessionCmdwire thelist / get / apply / delete / disable|enableandlist / get / apply / delete / revoke|unrevokesubcommands respectively, sharing the helper builders below. - L80-L96:
newAccessListCmdregisters alistcommand with--namespaceand--all-namespaces(defaulting to all-namespaces). CallsListAccessResources. - L98-L113:
newAccessGetCmdregistersget [name](single-arg) with a--namespaceflag defaulting toNamespaceMCPServers. CallsGetAccessResource. - L115-L130:
newAccessApplyCmdregistersapply --file <manifest>(file is required). CallsApplyAccessResource. - L132-L147:
newAccessDeleteCmdregistersdelete [name]with namespace flag. CallsDeleteAccessResource. - L149-L164:
newAccessToggleCmdis the shared builder for the four toggle commands (disable/enableon grants,revoke/unrevokeon sessions). It captures the boolean value to set and callsToggleAccessResource. - L166-L183:
ListAccessResourcesrunskubectl get <resource>with namespace scoping and streams output through the kubectl client. - L185-L201:
GetAccessResourcevalidates the name/namespace pair, then runskubectl get <resource> <name> -n <ns> -o yaml. - L203-L211:
ApplyAccessResourcedelegates toapplyManifestFromFileso the user-supplied YAML/JSON is applied via the kubectl client. - L213-L229:
DeleteAccessResourcerunskubectl delete <resource> <name> -n <ns>after the same input validation. - L231-L267:
ToggleAccessResourcebuilds a strategic merge patch —spec.disabled=<value>for grants,spec.revoked=<value>for sessions — marshals it to JSON, then runskubectl patch ... --type merge --patch <json>. Unknown resource kinds error out. - L269-L283:
validateAccessInputenforces the shared name regex (validServerName) and usesvalidateManifestValueto scrub name/namespace before they reach kubectl.
status.go¶
- L1-L17: command wiring for
mcp-runtime statusthat prints operator/registry/server health. - L19-L74:
checkPlatformStatusshells out tokubectlto fetch operator pods, registry pods, CRD presence, and lists MCPServer resources. It streams outputs directly to stdout/stderr and returns errors when kubectl fails.
cluster.go¶
- L1-L32: imports, default cluster name, and ingress option struct used by setup/config commands.
- L34-L48:
NewClusterCmddefines theclusterroot command and attaches subcommands. - L50-L78:
newClusterInitCmdwires theinitsubcommand; collects kubeconfig/context flags and callsinitCluster. - L80-L99:
newClusterStatusCmddefinescluster statusthat delegates tocheckClusterStatus. - L101-L132:
newClusterConfigCmddefinescluster configto install ingress controllers usingconfigureClusterand ingress flags. - L134-L167:
newClusterProvisionCmdwires theprovisionsubcommand for creating clusters via provider-specific helpers. - L169-L216:
initClusterresolves kubeconfig (defaulting to~/.kube/config), ensures it exists, optionally switches context, applies the MCP CRD manifest, creates namespacesmcp-runtimeandmcp-servers, and logs progress. - L218-L249:
checkClusterStatusrunskubectlcommands to show cluster info, nodes, CRD status, and operator pods, streaming output. - L251-L305:
configureClustervalidates ingress mode, detects existing ingress classes unless forced, chooses manifest path (files or kustomize directories), applies viakubectl, and logs completion. - L306-L362:
provisionClusterdispatches to provider-specific provisioning helpers (Kind/GKE/EKS/AKS) and errors on unknown providers. - L364-L394:
provisionKindClusterbuilds a temporary kind cluster config based on node count, writes it to a temp file, runskind create cluster, and cleans up the temp file. - L396-L421:
provisionGKECluster,provisionEKSCluster, andprovisionAKSClustercurrently return informative errors describing how to create clusters manually. - L423-L431:
ensureNamespaceapplies a simple Namespace manifest piped tokubectl apply -f -.
build.go¶
- L1-L20: imports CLI/logging helpers, metadata package, and YAML marshalling.
- L22-L51:
newBuildImageCmddefinespipeline imagesubcommand flags (dockerfile, metadata file/dir, registry URL, tag, context) and callsbuildImagewith optional server name argument. - L53-L110:
buildImageloads metadata from a file or directory, determines registry URL (defaults to platform registry), determines tag (git SHA orlatest), filters servers by name if provided, and for each server builds a Docker image withdocker build -t <registry>/<name>:<tag>; logs success and attempts to update metadata with the new image/tag. - L112-L170:
updateMetadataImagelocates the metadata YAML containing the target server (searches directory if necessary), loads it, updates the server image/tag fields, marshals YAML, and writes back to disk. - L172-L197:
getPlatformRegistryURLtries to resolve the in-cluster registry service IP/port viakubectl; falls back toregistry.registry.svc.cluster.local:5000if detection fails. - L199-L208:
getGitTagreturns a short git SHA viagit rev-parse --short HEADorlateston failure.
pipeline.go¶
- L1-L28: imports and
NewPipelineCmdroot wiring for pipeline-related commands. - L30-L73:
newPipelineGenerateCmddefinespipeline generatewith flags for metadata dir/output dir; loads metadata viapkg/metadataand writes CRD YAML for each server usingGenerateCRDsFromRegistry. - L75-L130:
newPipelineDeployCmddefinespipeline deployto apply generated manifests from a directory viakubectl apply -f. - L132-L195:
newPipelineRenderCmddefinespipeline renderto render CRDs to stdout instead of files, loading metadata and marshalling each CRD using the metadata generator. - L197-L216:
writeCRDshelper ensures the output dir exists and writes CRD YAML content for each server by callingmetadata.GenerateCRDsFromRegistry(for file output) or direct marshal when rendering.
registry.go¶
- L1-L22: imports and top-level registry command registration (
NewRegistryCmd) attaching status/info/provision/push subcommands. - L24-L60:
newRegistryStatusCmdwiresregistry statuswhich callscheckRegistryStatuswith namespace flag. - L62-L77:
newRegistryInfoCmdprints registry connection info viashowRegistryInfo. - L79-L129:
newRegistryProvisionCmdhandles external registry configuration: merges flag/env/config, saves config YAML under~/.mcp-runtime/registry.yaml, optionally performsdocker login, and optionally builds/pushes the operator image to that registry. - L131-L196:
newRegistryPushCmdretags and pushes an image to the platform/provisioned registry; resolves target registry precedence, parses source image into repo/tag, derives target name, and dispatches to direct or in-cluster push strategies (pushDirectvspushInCluster). - L198-L230:
ExternalRegistryConfigstruct plus helpersregistryConfigPathandsaveExternalRegistryConfigfor persisting config to disk. - L232-L264:
resolveExternalRegistryConfigloads registry config from flags, env vars, or config file and returns nil when nothing is configured. - L266-L292:
checkRegistryStatuscallskubectl getto display pods and services in the registry namespace and prints ingress/ingressClass resources. - L294-L339:
showRegistryInfoprints platform registry service endpoints and tips for pushing/pulling; uses kubectl to grab service details. - L341-L389:
deployRegistryapplies or updates a Docker registry deployment using kustomize or plain manifest path and patches the PVC size when provided. - L391-L421:
waitForDeploymentAvailablepolls deployment readiness until timeout usingkubectl wait. - L423-L466:
pushDirectperformsdocker taganddocker push, then reports success. - L468-L547:
pushInClusterspins up a temporary Kubernetes Job in the helper namespace running thequay.io/skopeo/stableimage to copy from local Docker daemon to target registry using skopeo; it builds a YAML manifest with inline credentials when provided, applies it, tails logs, waits for completion, fetches job logs, and cleans up the job. - L549-L584:
splitImageanddropRegistryPrefixhelpers parse image references. - L586-L637:
loginRegistryrunsdocker loginnon-interactively using provided credentials. - L639-L665:
buildOperatorImagebuilds the operator Dockerfile usingmake -f Makefile.operator docker-build-operator IMG=<image>. - L667-L680:
pushOperatorImagetags/pushes the operator image via Docker. - L682-L733:
pushOperatorImageToInternalRegistryuses an in-cluster helper job plus a temporary secret to push the operator image into the platform registry, cleaning up resources afterward. - L735-L749:
printDeploymentDiagnosticsprints describe/get output for deployments/services when setup fails.
server.go¶
- L1-L22: imports and
NewServerCmdwhich provides server CRUD commands and nests build helpers. - L24-L46:
newServerBuildCmdexposes image build vianewBuildImageCmd(push is handled byregistry push). - L48-L76:
newServerListCmdlists MCPServers in a namespace viakubectl get. - L78-L103:
newServerGetCmdfetches a single MCPServer as YAML. - L105-L146:
newServerCreateCmdcreates a server either from inline flags (image/tag/namespace) or a provided manifest file; delegates tocreateServerorcreateServerFromFile. - L148-L174:
newServerDeleteCmddeletes a server resource by name/namespace usingkubectl delete mcpserver. - L176-L204:
newServerLogsCmdstreams pod logs for a server label selector, optionally following output. - L206-L233:
newServerStatusCmdcallsserverStatusto show deployments, pods, images, and pull secrets for all MCPServers in a namespace. - L235-L303:
createServervalidates inputs, constructs a minimal MCPServer manifest with defaults, writes it to/tmp, and applies it withkubectl apply;createServerFromFilejust applies a provided YAML file. - L305-L322:
deleteServerwrapskubectl delete mcpserverwith logging. - L324-L345:
viewServerLogsbuildskubectl logsargs with label selectors and optional-f. - L347-L402:
serverStatusprints MCPServer/Deployment/Pod listings, then iterates MCPServer specs to show image and registry flags plus pull secrets discovered from deployments. - L404-L429: Manifest struct definitions (
mcpServerManifest,manifestMetadata,manifestSpec) used bycreateServer;validateManifestValuetrims/validates fields to avoid invalid YAML content.
setup.go¶
- L1-L25: imports, constants, and
defaultRegistrySecretNamefor provisioned registry credentials. - L27-L63:
NewSetupCmdwires the top-levelsetupcommand with flags for registry type/storage, ingress mode/manifest, TLS overlay, and test mode. - L65-L152:
setupPlatformexecutes the end-to-end setup: prints steps, loads external registry config, initializes cluster (initCluster), configures ingress (configureCluster), deploys registry (internal or external login), waits for readiness, shows registry info, builds/pushes operator image (or uses test-mode kind-loaded image), deploys operator manifests, configures provisioned registry env on operator, restarts deployment, verifies setup, and prints success. - L154-L205:
getOperatorImagepicks a default operator image (local tag or provisioned registry override) depending on external registry/test mode flags. - L207-L257:
deployOperatorManifestsuses kustomize to render operator manifests, substitutes the operator image, applies them viakubectl, and patches the deployment image when needed. - L259-L293:
restartDeploymenttriggers a rollout restart on the operator deployment to pick up env changes. - L295-L333:
verifySetupcallscheckClusterStatusandcheckRegistryStatus, ensuring registry ingress routes resolve; on external registry, it requires external config. - L335-L373:
resolveExternalRegistryConfigvariant for setup reads config/env/flags to decide whether to use an external registry. - L375-L436:
configureProvisionedRegistryEnvpatches operator deployment env vars with provisioned registry credentials usingkubectl set envand creates the pull secret in themcp-runtimenamespace. - L438-L455:
waitForPodsDeletedpolls until pods with a label selector disappear after restarts. - L457-L516:
pushOperatorImageToInternalRegistryhelper reuses registry push logic to move the operator image inside the cluster, then logs the internal image reference. - L518-L547:
getDeploymentImagefetches a deployment's current image viakubectl get -o jsonpath. - L549-L623:
deployRegistryandprintDeploymentDiagnosticsare re-used; setup.go calls into registry helpers above when needed.
pipeline/build/server/status tests¶
output_test.go,registry_test.go,server_test.go,controller_test.go, andpipeline/build-related tests validate the CLI wiring and behaviors using mocks, golden output snapshots, or stub command executions.