KubernetesManager Kubeconfig Loading and Authentication Priority Guide
The KubernetesManager class in flux159/mcp-server-kubernetes implements a strict seven-tier priority chain for kubeconfig loading, evaluating environment variables in descending order from inline YAML/JSON configurations down to default local files, with automatic temporary file creation for secure credential handling.
The KubernetesManager serves as the central orchestration layer for all Kubernetes interactions in the flux159/mcp-server-kubernetes MCP server. Understanding how this class handles kubeconfig loading and authentication priority is essential for deploying the server across diverse environments—from local development workstations to production CI/CD pipelines and in-cluster pod execution.
Seven-Tier Authentication Priority Chain
The constructor in src/utils/kubernetes-manager.ts (lines 21-83) evaluates authentication sources in strict priority order. The implementation uses helper detection methods to identify and load the first valid configuration source, short-circuiting further evaluation once a match is found.
Priority 1: KUBECONFIG_YAML Environment Variable
The highest priority source is the KUBECONFIG_YAML environment variable, which accepts a complete kubeconfig as a YAML string. The implementation calls hasEnvKubeconfigYaml() to detect the variable, then loadEnvKubeconfigYaml() to invoke kc.loadFromString(). Finally, createTempKubeconfigFromYaml() writes the YAML to a secure temporary file with 600 permissions for external kubectl commands.
Priority 2: KUBECONFIG_JSON Environment Variable
When KUBECONFIG_JSON is present, the manager parses the JSON content and loads it via kc.loadFromOptions(). The loadEnvKubeconfigJson() method converts the JSON to a client-side configuration object, then exports it to YAML format using kc.exportConfig() before writing to a temporary file via createTempKubeconfigFromYaml().
Priority 3: Minimal Environment Variables (K8S_SERVER and K8S_TOKEN)
For scenarios requiring minimal configuration, the manager accepts K8S_SERVER and K8S_TOKEN environment variables, with optional K8S_CA_DATA and K8S_SKIP_TLS_VERIFY. The loadEnvMinimalKubeconfig() method programmatically constructs cluster, user, and context objects, then loads them via kc.loadFromOptions(). This configuration is also persisted to a temporary file for command-line tool compatibility.
Priority 4: In-Cluster Service Account
When executing within a Kubernetes pod, the manager detects the service account token at /var/run/secrets/kubernetes.io/serviceaccount/token. The isRunningInCluster() check triggers kc.loadFromCluster(), which uses the pod's service account credentials without requiring additional configuration.
Priority 5: KUBECONFIG_PATH Environment Variable
Users may specify an explicit file path via KUBECONFIG_PATH. The loadEnvKubeconfigPath() method loads this file and sets process.env.KUBECONFIG to the specified path, ensuring external kubectl invocations use the same configuration.
Priority 6: Standard KUBECONFIG Environment Variable
The manager falls back to the standard KUBECONFIG environment variable, loading the file path it references via kc.loadFromFile(process.env.KUBECONFIG!).
Priority 7: Default Local Configuration
Finally, if no other source is detected, the manager invokes kc.loadFromDefault(), which searches standard locations such as ~/.kube/config.
Temporary Kubeconfig File Security
When loading configurations from environment variables (priorities 1-3), the manager writes the configuration to a secure temporary file with 600 permissions (read/write for owner only). The createTempKubeconfigFromYaml() function (lines 44-88) handles this process and registers cleanup handlers for process exit, SIGINT, SIGTERM, and uncaught exceptions to ensure sensitive credentials are not left on disk.
Context Override with K8S_CONTEXT
After initial configuration loading, the constructor checks for the K8S_CONTEXT environment variable (lines 85-96). If present, setCurrentContext() switches the active context and re-initializes the CoreV1Api, AppsV1Api, and BatchV1Api clients to use the specified context. This allows runtime context switching without restarting the server.
Practical Implementation Examples
// Example 1: Using KUBECONFIG_YAML for CI/CD pipelines
import { KubernetesManager } from "./src/utils/kubernetes-manager.js";
process.env.KUBECONFIG_YAML = `
apiVersion: v1
kind: Config
clusters:
- cluster:
server: https://prod-cluster.example.com
name: production
users:
- name: ci-user
user:
token: ${process.env.CI_TOKEN}
contexts:
- context:
cluster: production
user: ci-user
name: prod-context
current-context: prod-context
`;
const manager = new KubernetesManager();
const pods = await manager.getCoreApi().listNamespacedPod("default");
console.log(`Found ${pods.body.items.length} pods in default namespace`);
// Example 2: Minimal environment variable configuration
import { KubernetesManager } from "./src/utils/kubernetes-manager.js";
process.env.K8S_SERVER = "https://k8s.example.com:6443";
process.env.K8S_TOKEN = "eyJhbGciOiJSUzI1NiIs...";
process.env.K8S_CA_DATA = "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t...";
process.env.K8S_CONTEXT = "production";
const manager = new KubernetesManager();
console.log("Current context:", manager.getKubeConfig().currentContext);
const deployments = await manager.getAppsApi().listDeploymentForAllNamespaces();
// Example 3: Runtime context switching
import { KubernetesManager } from "./src/utils/kubernetes-manager.js";
const manager = new KubernetesManager();
// Switch to staging environment at runtime
manager.setCurrentContext("staging-cluster");
// All subsequent API calls use the new context
const services = await manager.getCoreApi().listServiceForAllNamespaces();
console.log(`Services in staging: ${services.body.items.length}`);
Key Source Files
| File | Purpose |
|---|---|
src/utils/kubernetes-manager.ts |
Core implementation of the KubernetesManager class, handling the seven-tier priority chain, temporary file creation, and API client initialization. |
src/tools/kubectl-context.ts |
MCP tool implementation providing runtime context switching capabilities via setCurrentContext. |
tests/kubernetes-manager.test.ts |
Test suite validating the authentication priority order and environment variable handling. |
src/prompts/index.ts |
Integration layer connecting the manager to the MCP server request/response flow. |
Summary
- The
KubernetesManagerimplements a strict seven-tier priority chain for kubeconfig loading, starting with inline YAML/JSON environment variables and falling back to default local configuration files. - Environment variable configurations (priorities 1-3) are automatically persisted to secure temporary files with 600 permissions to ensure external
kubectlcommands use identical credentials. - The
K8S_CONTEXTenvironment variable andsetCurrentContext()method enable runtime context switching without server restarts, re-initializing Core, Apps, and Batch API clients. - In-cluster authentication (priority 4) is automatically detected via the service account token path, enabling zero-configuration operation within Kubernetes pods.
Frequently Asked Questions
How does KubernetesManager prioritize multiple kubeconfig sources?
The constructor evaluates sources in a fixed seven-level hierarchy: first KUBECONFIG_YAML, then KUBECONFIG_JSON, followed by minimal env vars (K8S_SERVER/K8S_TOKEN), in-cluster service account, KUBECONFIG_PATH, standard KUBECONFIG, and finally ~/.kube/config. The first valid source wins and short-circuits further evaluation.
What happens when I provide kubeconfig via environment variables?
When using KUBECONFIG_YAML, KUBECONFIG_JSON, or minimal env vars, the manager writes the configuration to a temporary file with 600 permissions (owner read/write only). It sets process.env.KUBECONFIG to this path and registers cleanup handlers for process exit and termination signals to securely delete the temporary credentials.
Can I switch Kubernetes contexts without restarting the MCP server?
Yes. Set the K8S_CONTEXT environment variable before startup, or call setCurrentContext() at runtime. This method updates the KubeConfig current context and re-initializes the CoreV1Api, AppsV1Api, and BatchV1Api clients to use the new context immediately.
How does the manager handle in-cluster authentication?
When running inside a Kubernetes pod, the manager detects the service account token at /var/run/secrets/kubernetes.io/serviceaccount/token. It automatically invokes kc.loadFromCluster() to use the pod's service account credentials, requiring no additional environment variables or kubeconfig files.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →