Skip to main content
Glama
yanmxa

OCM MCP Server

by yanmxa

connect_cluster

Generate KUBECONFIG for managed clusters and bind to specified ClusterRoles to enable secure cluster access and management.

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.
clusterRoleNoThe ClusterRole defining permissions to access the clustercluster-admin

Implementation Reference

  • The core handler function for the 'connect_cluster' tool. It creates a ManagedServiceAccount, applies ClusterRoleBinding via ManifestWork, retrieves the service account token secret, and generates a KUBECONFIG for the specified cluster.
    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
      }
    }
  • Zod schema and description for the 'connect_cluster' tool inputs.
    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)."
  • src/index.ts:31-35 (registration)
    Registration of the 'connect_cluster' tool on the MCP server using server.tool().
      "connect_cluster",
      connectClusterDesc,
      connectClusterArgs,
      async (args, extra) => connectCluster(args) // ensure connectCluster matches (args, extra) => ...
    )
  • Python implementation of the connect_cluster tool handler, decorated with @mcp.tool and delegating to setup_cluster_access.
    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)
  • Import of the connect_cluster tool in the main entrypoint, where tools decorated with @mcp.tool are automatically registered when mcp.run() is called.
    from multicluster_mcp_server.tools.cluster import clusters
    from multicluster_mcp_server.tools.connect import connect_cluster
    from multicluster_mcp_server.tools.kubectl import kube_executor
    from multicluster_mcp_server.tools.prometheus import prometheus
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. While it describes the core action (generates KUBECONFIG and binds to ClusterRole), it doesn't mention important behavioral aspects like whether this creates persistent resources, what permissions are required, whether it's idempotent, or what happens if the cluster doesn't exist. For a tool that likely creates service accounts and binds roles, 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 clearly states the tool's purpose. It's appropriately sized and front-loaded with the essential information. There's no wasted verbiage 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 this is a tool that likely creates Kubernetes resources (service accounts, role bindings) with no annotations and no output schema, the description is incomplete. It doesn't explain what the tool returns (presumably a KUBECONFIG file or content), what side effects occur, or how to use the generated configuration. For a cluster management tool with potential security implications, 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?

The description adds minimal parameter semantics beyond what the schema provides. It mentions the default ClusterRole is 'cluster-admin', which is already in the schema's default field. With 100% schema description coverage, the baseline is 3, and the description doesn't significantly enhance understanding of parameter usage or constraints beyond what's already documented in the schema.

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'. This specifies both the action (generates KUBECONFIG) and the resource (managed cluster), though it doesn't explicitly differentiate from sibling tools like 'clusters' or 'kubectl' which might have related but different functions.

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 'kubectl'. It mentions a default ClusterRole but doesn't explain when you'd choose a different role or what prerequisites exist for using this tool. No explicit when/when-not scenarios are provided.

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

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

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