Skip to main content
Glama
README.md
# k8s-mcp-server

一个基于 [MCP(Model Context Protocol)](https://modelcontextprotocol.io/) 的 Kubernetes 运维助手。它将 K8s 集群的查询与诊断能力封装成标准化的 MCP 工具,让 LLM 客户端(如 ZCode、Claude Desktop、Cursor)能够通过自然语言查看和排查 Kubernetes 集群。

## 功能特性

- 基于 MCP Python SDK,使用 stdio 传输
- 支持多集群切换(本地 k3s / 阿里云 k3s)
- 8 个工具:健康检查、资源查询、Pod 一键诊断
- `diagnose_pod` 组合工具:一次调用聚合 Pod 状态、事件、日志,并通过规则引擎给出初步诊断建议
- 完善的异常处理,错误信息对 LLM 友好
- 输出经过精简格式化,避免返回冗余的 K8s 原始对象
- 所有工具均为只读操作,不会修改集群状态
- 28 个 pytest 单元测试,ruff 代码检查
- Docker 多阶段构建,GitHub Actions CI/CD 自动推送镜像至阿里云 ACR

## 工具列表

| 工具 | 说明 |
|------|------|
| `ping` | 健康检查,返回 pong |
| `list_namespaces` | 列出所有 namespace 及其状态 |
| `list_pods` | 列出指定 namespace 下的 Pod |
| `describe_pod` | 查看 Pod 详情(状态、IP、节点、容器、重启次数、资源) |
| `get_pod_logs` | 获取 Pod 日志(支持 tail_lines 限制行数) |
| `list_nodes` | 列出集群节点及状态、OS、K8s 版本 |
| `list_events` | 列出所有 namespace 的最近事件(按时间倒序) |
| `diagnose_pod` | **一键诊断**:聚合基本信息、容器状态、Warning 事件、日志和规则引擎建议 |

## diagnose_pod 规则引擎

`diagnose_pod` 不依赖 LLM 做确定性判断,而是用 Python 规则引擎检测常见问题:

| 检测项 | 判断依据 | 诊断建议 |
|--------|---------|---------|
| CrashLoopBackOff | `state.waiting.reason == "CrashLoopBackOff"` | 检查日志中的异常堆栈、启动命令和配置 |
| ImagePullBackOff | `state.waiting.reason in ("ImagePullBackOff", "ErrImagePull")` | 检查镜像名、标签和仓库凭证 |
| OOMKilled | `last_state.terminated.reason == "OOMKilled"` | 增加 memory limit 或排查内存泄漏 |
| 频繁重启 | `restart_count > 3` | 查看日志和上次终止原因 |
| 调度失败 | `phase == "Pending"` + 事件中的 `FailedScheduling` | 检查节点资源、亲和性和污点容忍 |

规则引擎负责确定性模式匹配(零延迟、100% 一致),LLM 在此基础上做上下文关联和深度分析,将多次工具调用压缩为一次。

## 环境要求

- Python 3.12+
- [uv](https://docs.astral.sh/uv/) 包管理器
- 可访问的 Kubernetes 集群及对应的 kubeconfig

## 快速开始

### 安装

```bash
git clone git@github.com:AmazingYe-oss/k8s-mcp-server.git
cd k8s-mcp-server
uv sync
```

### 配置 kubeconfig

默认从以下路径加载 kubeconfig(在 `src/k8s_mcp_server/k8s_client.py` 中配置):

- `local` → `~/.kube/config`
- `cloud` → `~/.kube/config-k3s-cloud`

如需修改集群映射,编辑 `KUBECONFIGS` 字典即可。

### 运行

```bash
uv run k8s-mcp-server
```

服务器以 stdio 模式启动,等待 MCP 客户端连接。

## MCP 客户端配置

### ZCode / Claude Desktop(Windows 连接 WSL 中的 Server)

```json
{
  "mcp": {
    "servers": {
      "k8s": {
        "type": "stdio",
        "command": "wsl",
        "args": [
          "bash",
          "-lc",
          "cd /home/<your-user>/k8s-mcp-server && uv run k8s-mcp-server"
        ]
      }
    }
  }
}
```

### 原生 Linux/macOS

```json
{
  "mcp": {
    "servers": {
      "k8s": {
        "type": "stdio",
        "command": "uv",
        "args": ["--directory", "/path/to/k8s-mcp-server", "run", "k8s-mcp-server"]
      }
    }
  }
}
```

## Docker

### 构建镜像

```bash
docker build -t k8s-mcp-server:latest .
```

### 运行(挂载 kubeconfig)

```bash
docker run --rm -v ~/.kube:/home/appuser/.kube:ro k8s-mcp-server:latest
```

## 项目结构

```
src/k8s_mcp_server/
├── __init__.py
├── server.py        # MCP Server 入口,注册 8 个工具
├── k8s_client.py    # K8s API 客户端封装与异常处理
├── formatters.py    # K8s 对象到精简文本的格式化
└── diagnose.py      # diagnose_pod 组合工具与规则引擎

tests/
├── conftest.py          # 共享 mock fixtures(5 种 Pod 场景)
├── test_formatters.py   # formatter 单元测试
└── test_diagnose.py     # 规则引擎与报告组装测试
```

## 开发

```bash
# 代码检查
uv run ruff check .
uv run ruff format --check .

# 运行测试
uv run pytest

# 代码格式化
uv run ruff format .
```

## CI/CD

GitHub Actions 流水线(`.github/workflows/docker-ci-cd.yml`):

1. **PR / push 时**:运行 ruff 检查和 pytest
2. **合并到 main 后**:构建 Docker 镜像并推送至阿里云 ACR
   - 标签:`latest`、`<git-sha>`、语义化版本 tag

需要在 GitHub 仓库配置以下 Secrets:

| Secret | 说明 |
|--------|------|
| `ALIYUN_ACR_REGISTRY` | ACR 地址,如 `registry.cn-hangzhou.aliyuncs.com` |
| `ALIYUN_ACR_USERNAME` | ACR 用户名 |
| `ALIYUN_ACR_PASSWORD` | ACR 密码 |

## 技术栈

- Python 3.12
- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
- [Kubernetes Python Client](https://github.com/kubernetes-client/python)
- uv(依赖管理)
- pytest + unittest.mock(单元测试)
- ruff(代码检查与格式化)
- Docker + GitHub Actions + 阿里云 ACR

TDQS

A4.3/5.0

Scored across 8 tools

Disambiguation5/5

Each tool targets a distinct resource or action: health check, namespaces, pods, logs, pod details, nodes, events, and a comprehensive diagnostic. The diagnose_pod tool is clearly positioned as a higher-level troubleshooting action, so there is no ambiguity.

Naming Consistency5/5

Tool names consistently follow the verb_noun pattern (list_*, get_*, describe_*, diagnose_*), with only 'ping' as a standard health-check verb. All names use lowercase with underscores, providing a predictable naming scheme.

Tool Count5/5

Eight tools is well within the ideal range for a focused Kubernetes inspection server. Each tool covers a distinct aspect of cluster and pod monitoring, and there is no redundancy or unnecessary bloat.

Completeness4/5

The tool set provides solid coverage for cluster health, namespace listing, pod logs, pod details, node information, events, and a diagnostic workflow. However, it lacks tools for other common Kubernetes resources like deployments, services, and configmaps, which would be expected from a general-purpose k8s server.

Maintenance

ActivityMaintained
ResponsivenessNo issues