Kubernetes Resource Cleanup Mechanism in MCP Server: How It Works
The MCP server implements a comprehensive cleanup mechanism that tracks every created Kubernetes object in memory and deletes them in reverse creation order when the cleanup tool is invoked, ensuring no orphaned resources remain.
The flux159/mcp-server-kubernetes repository provides a Model Context Protocol (MCP) server for managing Kubernetes resources through AI assistants. Its cleanup mechanism prevents resource leaks by automatically tracking and removing every pod, deployment, service, and cronjob created during a session.
Core Architecture of the Cleanup System
The cleanup mechanism consists of three tightly coupled components working together to guarantee resource reclamation.
1. Resource Tracking with KubernetesManager
Every operation that creates a Kubernetes object calls KubernetesManager.trackResource. The manager maintains an in-memory array (this.resources) that stores the kind, name, and namespace of each created resource.
In src/utils/kubernetes-manager.ts (lines 76-78), the tracking method appends resource metadata:
await k8sManager.trackResource("deployment", "my-app", "default");
// This deployment is now registered for later cleanup
2. The Cleanup Tool Definition
The server exposes a non-interactive "cleanup" tool through the MCP API. This tool schema is declared in src/config/cleanup-config.ts, making the cleanup operation available to AI clients without requiring parameters.
When an MCP request with name === "cleanup" arrives, the dispatcher in src/index.ts (lines 87-95) routes the request to the cleanup routine and returns a JSON success response.
3. Executing the Central Cleanup Routine
When invoked, KubernetesManager.cleanup() in src/utils/kubernetes-manager.ts (lines 54-74) executes a three-phase destruction sequence:
- Stop active watches – Calls
watch.abort.abort()to terminate all Kubernetes watch streams - Delete tracked resources – Iterates over the
resourcesarray in reverse creation order, calling the appropriate deletion API (deleteNamespacedPod,deleteNamespacedDeployment, etc.) for each object. Errors during individual deletions are logged but do not halt the overall process - Clear tracking state – Empties the internal
resourcesarray after successful deletions
This reverse-order deletion ensures that dependent resources (like pods owned by deployments) are removed before their parent objects, preventing Kubernetes finalizer deadlocks.
Additional Housekeeping Operations
Beyond the primary resource cleanup mechanism, the server implements secondary cleanup routines for auxiliary system resources.
Temporary Kubeconfig Cleanup
The createTempKubeconfigFromYaml method (lines 67-89 in src/utils/kubernetes-manager.ts) writes temporary kubeconfig files for kubectl subprocesses. To prevent credential leaks, it registers process event listeners on process.exit, SIGINT, SIGTERM, SIGUSR1, and SIGUSR2 that immediately delete these temporary files when the server stops.
Port-Forward Session Management
While not part of the primary cleanup tool, port-forward sessions are recorded via trackPortForward and can be terminated individually through removePortForward. These sessions are also automatically stopped when the process exits, preventing orphaned network tunnels.
Practical Usage Examples
Invoking Cleanup from an MCP Client
// Assume `client` is an MCP transport that sends tool requests
await client.request({
name: "cleanup",
input: {} // No parameters required
});
Manual Cleanup in Custom Code
import { KubernetesManager } from "./src/utils/kubernetes-manager";
const manager = new KubernetesManager();
await manager.cleanup(); // Stops watches and deletes all tracked resources
Creating Trackable Resources
const k8sManager = new KubernetesManager();
// Create a deployment and register it for cleanup
await k8sManager.trackResource("deployment", "api-server", "production");
// When cleanup runs, this deployment will be deleted automatically
// in reverse order relative to other tracked resources
Summary
- Automatic tracking – Every created Kubernetes object is registered via
KubernetesManager.trackResourcewith kind, name, and namespace metadata stored in memory - Reverse-order deletion – The cleanup routine deletes resources in reverse creation order to handle dependency chains correctly
- Fault-tolerant execution – Individual deletion failures are logged but do not stop the cleanup process, ensuring maximum resource reclamation
- Process-level cleanup – Temporary kubeconfig files and port-forward sessions are cleaned up via process event listeners (
SIGINT,SIGTERM, etc.) - Zero-parameter tool – The cleanup tool requires no input parameters and returns a simple success confirmation via the MCP protocol
Frequently Asked Questions
What happens if a Kubernetes resource deletion fails during cleanup?
Errors during individual resource deletions are caught and logged, but the cleanup process continues to the next resource in the queue. According to the implementation in src/utils/kubernetes-manager.ts, the loop iterates through all tracked resources regardless of individual API failures, ensuring that transient errors with one object do not leave other resources orphaned.
In what order are Kubernetes resources deleted during cleanup?
Resources are deleted in reverse creation order (last created, first deleted). This sequencing, implemented in the cleanup method (lines 54-74), ensures that dependent objects like pods are removed before their parent deployments or replica sets, preventing Kubernetes from attempting to recreate resources during the cleanup phase.
Are temporary kubeconfig files cleaned up automatically?
Yes. The createTempKubeconfigFromYaml method registers listeners for process.exit, SIGINT, SIGTERM, SIGUSR1, and SIGUSR2 events that delete temporary credential files immediately upon server shutdown. This mechanism operates independently of the main cleanup tool to ensure no sensitive files remain on disk after the process terminates.
Does the cleanup mechanism affect resources not created by the MCP server?
No. The cleanup mechanism only removes resources explicitly tracked through trackResource calls. It does not scan namespaces or perform wildcard deletions. If a resource was created outside the MCP server's context or was not registered via the tracking method, it remains unaffected by the cleanup routine.
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 →