Cover image
Try Now
2025-04-14

3 years

Works with Finder

0

Github Watches

0

Github Forks

0

Github Stars

Kubernetes MCP Server

A flexible Machine Communication Protocol (MCP) server that provides Kubernetes management capabilities with support for custom extension scripts.

Features

  • Implements the Model Context Protocol (MCP) using the official MCP SDK
  • Provides a wide range of Kubernetes management operations through tabular output
  • Supports dynamic loading and auto-detection of custom extension scripts
  • Automatic script parameter detection and validation
  • Clean, modular architecture with Pydantic models for type safety

Directory Structure

  • bin/: Contains main executable components

    • k8s_mcp_wrapper.py: The main MCP server executable
  • scripts/: Contains plugin scripts for the MCP server

    • Add your custom scripts here to extend functionality

Prerequisites

  • Python 3.10 or higher (required by MCP SDK)
  • kubectl installed and configured
  • Required Python packages (see requirements.txt)

Installation

Using pip

  1. Clone this repository:

    git clone https://github.com/yourusername/k8s-mcp-server.git
    cd k8s-mcp-server
    
  2. (Optional) Create a virtual environment:

    python3.10 -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
    
  3. Install dependencies:

    pip install -r requirements.txt
    

Using uv (faster installation)

  1. Install uv if not already installed:

    pip install uv
    
  2. Clone the repository:

    git clone https://github.com/yourusername/k8s-mcp-server.git
    cd k8s-mcp-server
    
  3. Create a virtual environment and install dependencies using uv:

    uv venv
    source .venv/bin/activate  # On Windows: .venv\Scripts\activate
    uv pip install -r requirements.txt
    

Usage

Running the MCP Server

Execute the MCP server from the bin directory:

cd bin
python3 k8s_mcp_wrapper.py

For development mode with web server (useful for debugging):

cd bin
python3 k8s_mcp_wrapper.py --dev --dev-port 8000

The server will:

  1. Check if kubectl is available
  2. Discover and register scripts from the scripts/ directory
  3. Start listening for MCP protocol commands

Available Tools

The MCP server provides the following built-in tools:

Tool Name Description
get_pods Get a list of pods in the specified namespace
get_services Get a list of services in the specified namespace
get_deployments Get a list of deployments in the specified namespace
get_namespaces Get a list of all namespaces in the cluster
describe_resource Describe a Kubernetes resource in detail
get_pod_logs Get logs from a pod in the specified namespace
create_namespace Create a new namespace in the Kubernetes cluster
delete_resource Delete a Kubernetes resource
scale_deployment Scale a deployment to the specified number of replicas
get_events Get events from the Kubernetes cluster
get_current_context Get the current kubectl context
get_available_contexts Get the list of available kubectl contexts
switch_context Switch the kubectl context
list_scripts List all available scripts with their parameters

Additionally, all scripts in the scripts/ directory are automatically registered as tools with the prefix script_.

Creating Custom Scripts

You can extend the MCP server's functionality by adding custom scripts to the scripts/ directory.

Script Requirements

  1. Scripts must be Python files with a .py extension
  2. Scripts should use argparse for parameter definitions (they will be auto-detected)
  3. Scripts should support receiving arguments via a JSON file with the --args-file flag

Improving Script Detection

If your scripts aren't being properly detected by the MCP server, try these improvements:

  1. Add detailed docstrings at the module level with parameter descriptions:

    """
    My Script Name
    
    Description of what this script does.
    
    Parameters:
        --param1: Description of parameter 1 (required)
        --param2: Description of parameter 2 (default: default_value)
    """
    
  2. Use detailed argparse help texts that match your docstrings:

    parser.add_argument(
        "--param1",
        type=str,
        required=True,
        help="Description of parameter 1 (required)"
    )
    
  3. Use ArgumentDefaultsHelpFormatter to include default values in help texts:

    parser = argparse.ArgumentParser(
        description="Description of the script",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    
  4. Make your script executable with proper permissions:

    chmod +x scripts/your_script.py
    

Script Template

Here's a basic template for creating a new script:

#!/usr/bin/env python3
"""
Script Name

Brief description of what the script does.

Parameters:
    --param1: Description of parameter 1 (required)
    --param2: Description of parameter 2 (default: default_value)
"""

import argparse
import json
import sys
import os

def main():
    """
    Main function that parses arguments and executes the script.
    
    This function demonstrates how to properly structure a script 
    for the Kubernetes MCP Server with clear parameter definitions.
    
    Returns:
        dict: A dictionary with the execution results
    """
    parser = argparse.ArgumentParser(
        description="Description of the script",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    
    # Define your parameters with detailed docstrings
    parser.add_argument(
        "--param1", 
        type=str, 
        required=True, 
        help="Description of parameter 1 (required)"
    )
    
    parser.add_argument(
        "--param2", 
        type=int,
        default=42, 
        help="Description of parameter 2"
    )
    
    # Check if the --args-file flag is present
    parser.add_argument("--args-file", help="JSON file containing arguments")
    args, _ = parser.parse_known_args()
    
    if args.args_file:
        # Load arguments from the file
        with open(args.args_file, 'r') as f:
            arguments = json.load(f)
            
        # Convert the loaded JSON arguments into a namespace
        for arg_name, arg_value in arguments.items():
            setattr(args, arg_name, arg_value)
    else:
        # Parse all arguments normally for CLI usage
        args = parser.parse_args()
    
    # Use your arguments here
    print(f"Parameter 1: {args.param1}")
    print(f"Parameter 2: {args.param2}")
    
    # Implement your script logic here
    
if __name__ == "__main__":
    main()

Environment Variables

  • SCRIPTS_DIR: Override the default scripts directory location
    SCRIPTS_DIR=/path/to/scripts python3 bin/k8s_mcp_wrapper.py
    

Architecture

The system consists of the following components:

  1. MCP Server: Uses the FastMCP SDK to implement the MCP protocol
  2. Kubernetes Client: Handles direct interactions with kubectl using Pydantic models
  3. Extension Scripts: Provide specialized functionality with auto-detected parameters

Pydantic Models

The system uses Pydantic for:

  • Type-safe models for Kubernetes resources
  • Automatic validation of data structures
  • Better IDE integration and error detection

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

相关推荐

  • av
  • Ejecute sin esfuerzo LLM Backends, API, frontends y servicios con un solo comando.

  • 1Panel-dev
  • 🔥 1Panel proporciona una interfaz web intuitiva y un servidor MCP para administrar sitios web, archivos, contenedores, bases de datos y LLM en un servidor de Linux.

  • WangRongsheng
  • 🧑‍🚀 全世界最好的 llM 资料总结(数据处理、模型训练、模型部署、 O1 模型、 MCP 、小语言模型、视觉语言模型) | Resumen de los mejores recursos del mundo.

  • rulego
  • ⛓️Rulego es un marco de motor de regla de orquestación de componentes de alta generación de alto rendimiento, de alto rendimiento y de alto rendimiento para GO.

  • sigoden
  • Cree fácilmente herramientas y agentes de LLM utilizando funciones Plain Bash/JavaScript/Python.

  • hkr04
  • SDK liviano C ++ MCP (Protocolo de contexto del modelo)

  • RockChinQ
  • 😎简单易用、🧩丰富生态 - 大模型原生即时通信机器人平台 | 适配 Qq / 微信(企业微信、个人微信) / 飞书 / 钉钉 / Discord / Telegram / Slack 等平台 | 支持 Chatgpt 、 Deepseek 、 DiFy 、 Claude 、 Gemini 、 Xai 、 PPIO 、 Ollama 、 LM Studio 、阿里云百炼、火山方舟、 Siliconflow 、 Qwen 、 Moonshot 、 Chatglm 、 SillyTraven 、 MCP 等 LLM 的机器人 / Agente | Plataforma de bots de mensajería instantánea basada en LLM, admite Discord, Telegram, WeChat, Lark, Dingtalk, QQ, Slack

  • dmayboroda
  • Trapo conversacional local con contenedores configurables

  • modelscope
  • Iniciar aplicaciones de múltiples agentes empoderadas con Building LLM de manera más fácil.

  • paulwing
  • Un repositorio de pruebas creado con el servicio MCP

    Reviews

    3.6 (14)
    Avatar
    user_iABriNqG
    2025-04-24

    As an avid user of the k8s_mcp_server by wakeupworld, I am thoroughly impressed with its functionality and reliability. This server has significantly streamlined our Kubernetes management, making it an indispensable tool in our infrastructure. The setup was straightforward, and the overall performance exceeded our expectations. Highly recommended for anyone looking to optimize their Kubernetes operations!

    Avatar
    user_XFEUuyOu
    2025-04-24

    As a devoted user of MCP applications, I have to say that the k8s_mcp_server by wakeupworld is phenomenal. Its seamless integration with Kubernetes and impeccable server performance make it a must-have. The user experience is top-notch, bolstered by thoughtful design and robust functionality. Highly recommend!

    Avatar
    user_UlXbm4iZ
    2025-04-24

    I am genuinely impressed with the k8s_mcp_server by wakeupworld. This application has significantly simplified managing my Kubernetes clusters. The interface is user-friendly, and the features are robust, ensuring a smooth and efficient workflow. Highly recommended for anyone looking to streamline their Kubernetes management!

    Avatar
    user_3M1sBhNL
    2025-04-24

    As a dedicated user of k8s_mcp_server by wakeupworld, I am thoroughly impressed by its seamless integration and robust performance. The user-friendly interface and the powerful capabilities it offers for managing Kubernetes clusters have significantly enhanced my efficiency. This tool is a game-changer for anyone serious about optimizing their cloud operations. Highly recommended!

    Avatar
    user_3TzJ24CV
    2025-04-24

    As a loyal user of the k8s_mcp_server by wakeupworld, I can confidently say it excels in managing Kubernetes clusters efficiently. It's an essential tool for anyone looking to optimize their containerized applications with ease. I highly recommend checking it out for streamlined operations and reliable performance.

    Avatar
    user_01ENjrAi
    2025-04-24

    As a dedicated user of the k8s_mcp_server by wakeupworld, I am thoroughly impressed with its performance and functionality. This product has significantly streamlined my Kubernetes cluster management, making deployments and scalability seamless. Highly recommend k8s_mcp_server for anyone looking to optimize their Kubernetes operations!

    Avatar
    user_tJFgTLzI
    2025-04-24

    As a loyal user of the k8s_mcp_server by wakeupworld, I am thoroughly impressed with its performance and reliability. This product has significantly streamlined our Kubernetes management, providing a seamless and efficient experience. The support and documentation are top-notch, making the setup process straightforward. Highly recommended for anyone looking to optimize their server operations!

    Avatar
    user_SHPHz1jl
    2025-04-24

    I have been using k8s_mcp_server by wakeupworld and I am thoroughly impressed. The seamless integration and efficient management of Kubernetes clusters make it an essential tool for anyone serious about container orchestration. The user interface is intuitive and the features are robust, ensuring reliable performance and scalability. Highly recommended for developers and IT professionals alike!

    Avatar
    user_NMqumH0j
    2025-04-24

    K8s MCP Server is an outstanding tool by Wakeupworld. It significantly simplifies the management of Kubernetes clusters with its intuitive interface. As a loyal MCP user, I can confidently say that this product enhances efficiency and control. Highly recommend it to anyone in the DevOps field.

    Avatar
    user_Gqvbl6Ce
    2025-04-24

    I've been using k8s_mcp_server by wakeupworld for a few months now, and it has exceeded my expectations. Its seamless integration with Kubernetes and robust performance make managing clusters a breeze. Highly recommend it to anyone looking for an efficient MCP solution!

    Avatar
    user_qJ9P1SvY
    2025-04-24

    As a dedicated user of the k8s_mcp_server by wakeupworld, I am thoroughly impressed. This product has significantly streamlined my Kubernetes cluster management. The seamless integration, combined with its user-friendly interface, allows for efficient monitoring and control. It has unquestionably enhanced my workflow and productivity. Highly recommend!

    Avatar
    user_vf63MAbe
    2025-04-24

    As an avid user of the k8s_mcp_server by wakeupworld, I must say it's an outstanding tool for managing Kubernetes clusters through an MCP interface. The intuitive design, seamless integration, and reliable performance make it a must-have for any DevOps toolkit. Highly recommended!

    Avatar
    user_eq2rHSKb
    2025-04-24

    As a dedicated user of the k8s_mcp_server by wakeupworld, I must say it's an exceptional tool! It streamlines managing Kubernetes clusters effortlessly, significantly boosting my productivity. The intuitive interface and robust performance make it indispensable for cloud operations. Highly recommend for anyone in DevOps!

    Avatar
    user_R4GTAvto
    2025-04-24

    I've been using the k8s_mcp_server by wakeupworld and it has truly revolutionized how I manage my Kubernetes clusters. The seamless integration and intuitive user interface make it a standout product in the market. It significantly streamlines the deployment process and optimizes cluster performance. Highly recommended for anyone looking to enhance their Kubernetes management efficiency.