Skip to main content
Glama

kubectl_get

Retrieve or list Kubernetes resources like pods, deployments, and services by type, name, and namespace to monitor and manage cluster components.

Instructions

Get or list Kubernetes resources by resource type, name, and optionally namespace

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
resourceTypeYesType of resource to get (e.g., pods, deployments, services, configmaps, events, etc.)
nameYesName of the resource (optional - if not provided, lists all resources of the specified type)
namespaceYesKubernetes namespacedefault
outputNoOutput formatjson
allNamespacesNoIf true, list resources across all namespaces
labelSelectorNoFilter resources by label selector (e.g. 'app=nginx')
fieldSelectorNoFilter resources by field selector (e.g. 'metadata.name=my-pod')
sortByNoSort events by a field (default: lastTimestamp). Only applicable for events.
contextNoKubeconfig Context to use for the command (optional - defaults to null)

Implementation Reference

  • The core handler function for 'kubectl_get' tool. Constructs kubectl 'get' command based on input parameters (resourceType, name, namespace, output format, selectors), executes it using execFileSync, processes and formats the output (JSON parsing for lists, special formatting for events, secrets masking), handles errors like 404, and returns structured MCP response.
    export async function kubectlGet( k8sManager: KubernetesManager, input: { resourceType: string; name?: string; namespace?: string; output?: string; allNamespaces?: boolean; labelSelector?: string; fieldSelector?: string; sortBy?: string; context?: string; } ) { try { const resourceType = input.resourceType.toLowerCase(); const name = input.name || ""; const namespace = input.namespace || "default"; const output = input.output || "json"; const allNamespaces = input.allNamespaces || false; const labelSelector = input.labelSelector || ""; const fieldSelector = input.fieldSelector || ""; const sortBy = input.sortBy; const context = input.context || ""; // Build the kubectl command const command = "kubectl"; const args = ["get", resourceType]; // Add name if provided if (name) { args.push(name); } // For events, default to all namespaces unless explicitly specified const shouldShowAllNamespaces = resourceType === "events" ? input.namespace ? false : true : allNamespaces; // Add namespace flag unless all namespaces is specified if (shouldShowAllNamespaces) { args.push("--all-namespaces"); } else if (namespace && !isNonNamespacedResource(resourceType)) { args.push("-n", namespace); } if (context) { args.push("--context", context); } // Add label selector if provided if (labelSelector) { args.push("-l", labelSelector); } // Add field selector if provided if (fieldSelector) { args.push(`--field-selector=${fieldSelector}`); } // Add sort-by for events if (resourceType === "events" && sortBy) { args.push(`--sort-by=.${sortBy}`); } else if (resourceType === "events") { args.push(`--sort-by=.lastTimestamp`); } // Add output format if (output === "json") { args.push("-o", "json"); } else if (output === "yaml") { args.push("-o", "yaml"); } else if (output === "wide") { args.push("-o", "wide"); } else if (output === "name") { args.push("-o", "name"); } else if (output === "custom") { if (resourceType === "events") { args.push( "-o", "'custom-columns=LASTSEEN:.lastTimestamp,TYPE:.type,REASON:.reason,OBJECT:.involvedObject.name,MESSAGE:.message'" ); } else { args.push( "-o", "'custom-columns=NAME:.metadata.name,NAMESPACE:.metadata.namespace,STATUS:.status.phase,AGE:.metadata.creationTimestamp'" ); } } // Execute the command try { const result = execFileSync(command, args, { encoding: "utf8", maxBuffer: getSpawnMaxBuffer(), env: { ...process.env, KUBECONFIG: process.env.KUBECONFIG }, }); // Apply secrets masking if enabled and dealing with secrets const shouldMaskSecrets = process.env.MASK_SECRETS !== "false" && (resourceType === "secrets" || resourceType === "secret"); let processedResult = result; if (shouldMaskSecrets) { processedResult = maskSecretsData(result, output); } // Format the results for better readability const isListOperation = !name; if (isListOperation && output === "json") { try { // Parse JSON and extract key information const parsed = JSON.parse(processedResult); if (parsed.kind && parsed.kind.endsWith("List") && parsed.items) { if (resourceType === "events") { const formattedEvents = parsed.items.map((event: any) => ({ type: event.type || "", reason: event.reason || "", message: event.message || "", involvedObject: { kind: event.involvedObject?.kind || "", name: event.involvedObject?.name || "", namespace: event.involvedObject?.namespace || "", }, firstTimestamp: event.firstTimestamp || "", lastTimestamp: event.lastTimestamp || "", count: event.count || 0, })); return { content: [ { type: "text", text: JSON.stringify({ events: formattedEvents }, null, 2), }, ], }; } else { const items = parsed.items.map((item: any) => ({ name: item.metadata?.name || "", namespace: item.metadata?.namespace || "", kind: item.kind || resourceType, status: getResourceStatus(item), createdAt: item.metadata?.creationTimestamp, })); return { content: [ { type: "text", text: JSON.stringify({ items }, null, 2), }, ], }; } } } catch (parseError) { // If JSON parsing fails, return the raw output console.error("Error parsing JSON:", parseError); } } return { content: [ { type: "text", text: processedResult, }, ], }; } catch (error: any) { if (error.status === 404 || error.message.includes("not found")) { return { content: [ { type: "text", text: JSON.stringify( { error: `Resource ${resourceType}${ name ? `/${name}` : "" } not found`, status: "not_found", }, null, 2 ), }, ], isError: true, }; } throw new McpError( ErrorCode.InternalError, `Failed to get resource: ${error.message}` ); } } catch (error: any) { throw new McpError( ErrorCode.InternalError, `Failed to execute kubectl get command: ${error.message}` ); } }
  • Input schema definition for the 'kubectl_get' tool, specifying parameters, descriptions, defaults, and required fields for validation.
    export const kubectlGetSchema = { name: "kubectl_get", description: "Get or list Kubernetes resources by resource type, name, and optionally namespace", annotations: { readOnlyHint: true, }, inputSchema: { type: "object", properties: { resourceType: { type: "string", description: "Type of resource to get (e.g., pods, deployments, services, configmaps, events, etc.)", }, name: { type: "string", description: "Name of the resource (optional - if not provided, lists all resources of the specified type)", }, namespace: namespaceParameter, output: { type: "string", enum: ["json", "yaml", "wide", "name", "custom"], description: "Output format", default: "json", }, allNamespaces: { type: "boolean", description: "If true, list resources across all namespaces", default: false, }, labelSelector: { type: "string", description: "Filter resources by label selector (e.g. 'app=nginx')", }, fieldSelector: { type: "string", description: "Filter resources by field selector (e.g. 'metadata.name=my-pod')", }, sortBy: { type: "string", description: "Sort events by a field (default: lastTimestamp). Only applicable for events.", }, context: contextParameter, }, required: ["resourceType", "name", "namespace"], }, } as const;
  • src/index.ts:216-231 (registration)
    Dispatch/registration of the 'kubectl_get' handler in the main CallToolRequestSchema request handler. Matches tool name and invokes the kubectlGet function with KubernetesManager and parsed input.
    if (name === "kubectl_get") { return await kubectlGet( k8sManager, input as { resourceType: string; name?: string; namespace?: string; output?: string; allNamespaces?: boolean; labelSelector?: string; fieldSelector?: string; sortBy?: string; context?: string; } ); }
  • src/index.ts:105-105 (registration)
    Inclusion of kubectlGetSchema in the allTools array for tool listing/discovery in ListToolsRequest.
    kubectlGetSchema,
  • Helper function to mask sensitive data in Kubernetes secrets output, used when processing secret resources.
    /** * Masks sensitive data in Kubernetes secrets by parsing the raw output and replacing * all leaf values in the "data" section with a placeholder value ("***"). * * @param {string} output - The raw output from a `kubectl` command, containing secrets data. * @param {string} format - The format of the output, either "json" or "yaml". * @returns {string} - The masked output in the same format as the input. */ function maskSecretsData(output: string, format: string): string { try { if (format === "json") { const parsed = JSON.parse(output); const masked = maskDataValues(parsed); return JSON.stringify(masked, null, 2); } else if (format === "yaml") { // Parse YAML to JSON, mask, then convert back to YAML const parsed = yaml.load(output); const masked = maskDataValues(parsed); return yaml.dump(masked, { indent: 2, lineWidth: -1, // Don't wrap lines noRefs: true, // Don't use references }); } } catch (error) { console.warn("Failed to parse secrets output for masking:", error); } return output; }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Flux159/mcp-server-kubernetes'

If you have feedback or need assistance with the MCP directory API, please join our Discord server