Skip to main content
Glama
yanmxa

Multi-Cluster MCP Server

by yanmxa

connect_cluster

Generates and binds a KUBECONFIG file to a specified ClusterRole, enabling secure access to a target Kubernetes cluster via the Multi-Cluster MCP Server.

Instructions

Generates the 'KUBECONFIG' for the managed cluster and binds it to the specified ClusterRole (default: cluster-admin).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
clusterYesThe target cluster where the ServiceAccount will be created for the KUBECONFIG.
cluster_roleNoThe ClusterRole defining permissions to access the cluster.cluster-admin

Implementation Reference

  • Python MCP tool handler for 'connect_cluster': decorates the function and implements logic to create ManagedServiceAccount, RBAC via ManifestWork, retrieve token secret, and generate kubeconfig file.
    @mcp.tool(description="Generates the 'KUBECONFIG' for the managed cluster and binds it to the specified ClusterRole (default: cluster-admin).")
    def connect_cluster(
        cluster: Annotated[str, Field(description="The target cluster where the ServiceAccount will be created for the KUBECONFIG.")],
        cluster_role: Annotated[str, Field(description="The ClusterRole defining permissions to access the cluster.")] = "cluster-admin",
    ) -> Annotated[str, Field(description="A message indicating the kubeconfig file or failure of the operation.")]:
        return setup_cluster_access(cluster, cluster_role=cluster_role)
    
    def setup_cluster_access(cluster: str, cluster_role: str = "cluster-admin", mcp_server: str = server_name):
        logger.debug(f"Setting up ManagedServiceAccount and RBAC for cluster: {cluster}")
        
        msa_result = create_or_update_managed_service_account(cluster, mcp_server)
        if not msa_result:
            logger.error("Failed to set up ManagedServiceAccount. Skipping RBAC setup.")
            return None
        
        rbac_result = create_or_update_rbac(cluster, mcp_server, cluster_role)
        if not rbac_result:
            logger.error("RBAC (ManifestWork) setup failed.")
            return None
          
        server_url = get_managed_cluster_url(cluster_name=cluster)
        if not server_url:
            logger.error(f"API server URL not found for ManagedCluster '{cluster}'.")
            return None
        
        token_secret = get_secret_with_timeout(cluster, mcp_server)
        if not token_secret:
          logger.error(f"Failed to get the service account token for cluster: {cluster}")
          return None
        
        kubeconfig_path_or_error = generate_kubeconfig_file_from_secret(token_secret, server_url, mcp_server)
        if not kubeconfig_path_or_error.startswith("/tmp/"):
            logger.error(kubeconfig_path_or_error)
            return None
          
        logger.debug(f"Generate the kubeconfig file: {kubeconfig_path_or_error}")
        return kubeconfig_path_or_error
  • TypeScript MCP tool handler for 'connect_cluster': async function that applies ManagedServiceAccount, ManagedClusterAddOn, ClusterRoleBinding via ManifestWork, polls for token secret, and generates KUBECONFIG.
    export async function connectCluster({ cluster, clusterRole = "cluster-admin" }: {
      cluster: string, clusterRole?: string
    }): Promise<CallToolResult> {
      // https://open-cluster-management.io/docs/getting-started/integration/managed-serviceaccount/
      const mcpServerName = "multicluster-mcp-server"
      const msa = {
        apiVersion: 'authentication.open-cluster-management.io/v1beta1',
        kind: 'ManagedServiceAccount',
        metadata: {
          name: mcpServerName,
          namespace: cluster,
        },
        spec: {
          rotation: {},
        },
      }
    
      const mca = {
        apiVersion: 'addon.open-cluster-management.io/v1alpha1',
        kind: 'ManagedClusterAddOn',
        metadata: {
          name: "managed-serviceaccount",
          namespace: cluster,
        },
      }
    
      let result = `Successfully connected to cluster ${cluster} using ServiceAccount ${mcpServerName}, with the ${clusterRole} ClusterRole assigned.`;
    
      let isErrored = false
      try {
    
        const [applyMsa, getMca, getClusters] = await Promise.all([
          client.patch<k8s.KubernetesObject>(
            msa,
            undefined,
            undefined,
            mcpServerName,
            true,
            k8s.PatchStrategy.ServerSideApply
          ),
          client.read(mca),
          listClusters({})
        ]);
    
    
        if (!applyMsa) {
          console.warn(`Patched ManagedServiceAccount ${msa.metadata.namespace}/${msa.metadata.name} with empty response`);
        }
    
        const saNamespace = (getMca as any)?.status?.namespace;
        if (!saNamespace) {
          throw new Error(`ManagedServiceAccount ${mca.metadata.namespace}/${mca.metadata.name} not found in the cluster`);
        }
    
        const clusterRoleBinding = {
          apiVersion: "rbac.authorization.k8s.io/v1",
          kind: "ClusterRoleBinding",
          metadata: {
            name: `${mcpServerName}-clusterrolebinding`,
          },
          roleRef: {
            apiGroup: "rbac.authorization.k8s.io",
            kind: "ClusterRole",
            name: clusterRole, // default clusterRole name for kubernetes admin - "cluster-admin"
          },
          subjects: [
            {
              kind: "ServiceAccount",
              name: mcpServerName,
              namespace: saNamespace,
            },
          ],
        };
    
        // create manifestWork to binding the clusterRole into the serviceAccount
        const bindingPermissionManifestWork = {
          apiVersion: 'work.open-cluster-management.io/v1',
          kind: 'ManifestWork',
          metadata: {
            name: mcpServerName,
            namespace: cluster,
          },
          spec: {
            workload: {
              manifests: [
                clusterRoleBinding,
              ]
            }
          },
        }
    
        const [tokenSecret, applyRBACManifest, appliedStatusErrMessage] = await Promise.all([
          getSecretWithRetry(cluster, mcpServerName),
          // createKubeConfigFile(acmMCPServer, cluster),
          client.patch<k8s.KubernetesObject>(
            bindingPermissionManifestWork, undefined, undefined, mcpServerName, true,
            k8s.PatchStrategy.ServerSideApply),
          // get the status
          manifestWorkAppliedErrorMessage(client, mcpServerName, cluster)
        ]);
    
        // error token
        if (typeof tokenSecret == 'string') {
          throw new Error(tokenSecret)
        }
    
        // error status
        if (appliedStatusErrMessage != "") {
          throw new Error(appliedStatusErrMessage)
        }
    
        const kubeConfigErrMessage = generateKubeconfig(tokenSecret, clusterToServerAPIMap);
        if (kubeConfigErrMessage) {
          throw new Error(kubeConfigErrMessage)
        }
    
      } catch (err: any) {
        isErrored = true
        result = `Failed to generate KUBECONFIG for ${cluster}: ${err}`
      }
    
      // return manifestsResponse
      return {
        content: [{
          type: "text",
          text: result
        }],
        isErrored: isErrored
      }
    }
  • src/index.ts:31-35 (registration)
    Explicit registration of the 'connect_cluster' tool in the MCP server using server.tool() with description, args schema, and handler.
      "connect_cluster",
      connectClusterDesc,
      connectClusterArgs,
      async (args, extra) => connectCluster(args) // ensure connectCluster matches (args, extra) => ...
    )
  • Zod schema definition for connect_cluster tool parameters (cluster and optional clusterRole) and tool description.
    export const connectClusterArgs = {
      cluster: z.string().describe("The target cluster where the ServiceAccount will be created for the KUBECONFIG."),
      clusterRole: z.string().default('cluster-admin').describe("The ClusterRole defining permissions to access the cluster")
    }
    
    export const connectClusterDesc = "Generates the KUBECONFIG for the managed cluster and binds it to the specified ClusterRole (default: cluster-admin)."
  • Import of connect_cluster tool in __main__.py, which triggers auto-registration via @mcp.tool decorator when mcp.run() is called.
    from multicluster_mcp_server.tools.connect import connect_cluster
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions generating and binding actions but lacks critical details: whether this creates resources (e.g., ServiceAccount), requires specific permissions, has side effects, or what the output entails. For a tool that likely involves cluster access configuration, this is a significant gap.

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 a single, efficient sentence that front-loads the core action. Every word contributes directly to explaining the tool's function without redundancy or unnecessary elaboration.

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 cluster management tools, no annotations, and no output schema, the description is insufficient. It doesn't cover what the generated KUBECONFIG contains, how it's returned, security implications, or error conditions. For a tool with potential high-impact operations, more context is needed.

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 both parameters thoroughly. The description adds minimal value beyond the schema: it implies the 'cluster_role' parameter defaults to 'cluster-admin', which is already in the schema's default field. No additional semantic context is provided.

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: 'Generates the KUBECONFIG for the managed cluster and binds it to the specified ClusterRole.' It specifies the verb (generates), resource (KUBECONFIG), and scope (managed cluster), though it doesn't explicitly differentiate from sibling tools like 'clusters' or 'kube_executor'.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives like 'clusters' or 'kube_executor'. It mentions a default ClusterRole but doesn't explain prerequisites, when-not-to-use scenarios, or how it relates to other tools in the context.

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