Skip to main content
Glama
yanmxa

Multi-Cluster MCP Server

by yanmxa

kube_executor

Execute kubectl commands or apply YAML configurations securely across multiple Kubernetes clusters using the Multi-Cluster MCP Server for streamlined cluster management.

Instructions

Securely run a kubectl command or apply YAML. Provide either 'command' or 'yaml'.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
clusterNoThe cluster name in a multi-cluster environment. Defaults to the hub cluster.default
commandNoThe full kubectl command to execute. Must start with 'kubectl'.
yamlNoYAML configuration to apply, provided as a string.

Implementation Reference

  • The core handler function `kube_executor` decorated with `@mcp.tool`. It executes kubectl commands or applies YAML manifests on specified clusters, handling kubeconfig setup, validation, and subprocess execution.
    @mcp.tool(description="Securely run a kubectl command or apply YAML. Provide either 'command' or 'yaml'.")
    def kube_executor(
        cluster: Annotated[str, Field(description="The cluster name in a multi-cluster environment. Defaults to the hub cluster.")] = "default",
        command: Annotated[Optional[str], Field(description="The full kubectl command to execute. Must start with 'kubectl'.")] = None,
        yaml: Annotated[Optional[str], Field(description="YAML configuration to apply, provided as a string.")] = None,
    ) -> Annotated[str, Field(description="The execution result")]:
        try:
            if not command and not yaml:
                raise ValueError("Either 'command' or 'yaml' must be provided.")
            if command and yaml:
                raise ValueError("Provide only one of 'command' or 'yaml', not both.")
    
            kubeconfig_file = None
            if cluster and cluster != "default":
                kubeconfig_file = get_kubeconfig_file(cluster)
                if not validate_kubeconfig_file(kubeconfig_file):
                    kubeconfig_file = setup_cluster_access(cluster=cluster)
                    if not kubeconfig_file:
                        raise FileNotFoundError(f"KUBECONFIG for cluster '{cluster}' does not exist.")
    
            if command:
                if not isinstance(command, str) or not is_valid_kubectl_command(command):
                    raise ValueError("Invalid command: Only 'kubectl' commands are allowed.")
                final_command = command
            else:
                # Write YAML to a temp file
                if not isinstance(yaml, str) or not yaml.strip():
                    raise ValueError("Invalid YAML content.")
                with tempfile.NamedTemporaryFile("w", delete=False, suffix=".yaml") as temp_file:
                    temp_file.write(yaml)
                    temp_file_path = temp_file.name
                final_command = f"kubectl apply -f {temp_file_path}"
    
            # Add --kubeconfig if needed
            if kubeconfig_file:
                final_command = inject_kubeconfig(final_command, kubeconfig_file)
    
            print(f"[debug] Executing: {final_command}")
            result = subprocess.run(final_command, shell=True, capture_output=True, text=True, timeout=10)
    
            output = result.stdout or result.stderr or "Run kube executor successfully, but no output returned."
            return output
        except Exception as e:
            return f"Error running kube executor: {str(e)}"
  • Import of the kube_executor tool in the main entrypoint, which registers it via the decorator when the module is loaded before mcp.run().
    from multicluster_mcp_server.tools.kubectl import kube_executor
  • Pydantic-based input schema defined via Annotated Fields in the function signature, including cluster, command, yaml parameters and output type.
    def kube_executor(
        cluster: Annotated[str, Field(description="The cluster name in a multi-cluster environment. Defaults to the hub cluster.")] = "default",
        command: Annotated[Optional[str], Field(description="The full kubectl command to execute. Must start with 'kubectl'.")] = None,
        yaml: Annotated[Optional[str], Field(description="YAML configuration to apply, provided as a string.")] = None,
    ) -> Annotated[str, Field(description="The execution result")]:
  • Helper function to validate that the provided command starts with 'kubectl '.
    def is_valid_kubectl_command(command: str) -> bool:
        return command.strip().startswith("kubectl ")
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'Securely run,' which hints at safety but doesn't detail what that entails (e.g., authentication needs, rate limits, or potential destructive effects). For a tool that executes kubectl commands (which can be highly destructive), this lack of behavioral context is a significant gap, as it doesn't warn about risks like modifying or deleting resources.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise and front-loaded: two sentences that directly state the purpose and key usage rule. There is no wasted language, and every sentence earns its place by providing essential information without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of executing kubectl commands (which can have significant side effects) and the lack of annotations and output schema, the description is incomplete. It doesn't cover behavioral risks, response formats, or error handling. For a tool with no structured safety hints, this minimal description leaves critical gaps in understanding how to use it safely and effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all three parameters ('cluster', 'command', 'yaml') with details like defaults and constraints. The description adds minimal value beyond the schema by noting the exclusive choice between 'command' or 'yaml', but it doesn't provide additional semantics (e.g., examples or edge cases). This meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Securely run a kubectl command or apply YAML.' It specifies the verb ('run'/'apply') and resource ('kubectl command'/'YAML'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from sibling tools like 'clusters' or 'connect_cluster', which likely serve different purposes in Kubernetes management.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides some usage guidance: 'Provide either 'command' or 'yaml',' indicating an exclusive choice between parameters. However, it doesn't explain when to use this tool versus alternatives like 'clusters' (which might list clusters) or 'prometheus' (which might handle monitoring). No explicit when-not-to-use or prerequisite information is given, leaving usage context implied rather than fully clarified.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

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/yanmxa/multicluster-mcp-server'

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