mcp-k8s-context-server
MCP K8s Context Server
A FastMCP server that exposes Kubernetes as a set of read-only tools consumable by LLMs, plus an analytics layer for pod-health analysis and resource-trend tracking.
기능
도구 | 설명 |
| 네임스페이스의 포드를 단계 및 재시작 정보와 함께 나열합니다. |
| 포드 상태, 조건, 컨테이너 상태에 대한 상세 정보를 제공합니다. |
| 최근 포드 로그를 tail로 표시합니다. |
| 전체 디플로이먼트 스펙을 JSON으로 제공합니다. |
| 분석: 로그를 스캔하고 오류 패턴을 탐지하며 비정상 포드를 순위로 매깁니다. |
| 분석: Metrics API의 CPU/메모리를 수집하고 SQLite에 기록하여 과거 추세를 유지합니다. |
Related MCP server: Kubernetes Read Only MCP Server
프로젝트 구조
mcp-k8s-context-server/
├── k8s_mcp_server.py # FastMCP server (all tools)
├── requirements.txt # Python dependencies
├── Dockerfile # Container image definition
├── k8s/
│ ├── serviceaccount.yaml # ServiceAccount + Namespace
│ ├── role.yaml # Least-privilege ClusterRole (read-only)
│ ├── rolebinding.yaml # ClusterRoleBinding
│ └── deployment.yaml # Deployment + Service
└── .github/
└── workflows/
└── ci.yml # Build + kubeconform validation로컬 개발
# Create and activate a virtual environment
python -m venv .venv && source .venv/bin/activate
# Install dependencies
pip install -r requirements.txt
# Run with local kubeconfig (falls back automatically from in-cluster config)
python k8s_mcp_server.py클러스터 내 배포 (minikube)
사전 요구 사항
# Install minikube, kubectl, docker
minikube version # >= 1.32
kubectl version # >= 1.28
docker version # >= 241단계 — minikube 시작
minikube start --cpus=2 --memory=40962단계 — metrics-server 활성화 (get_resource_trends에 필요)
minikube addons enable metrics-server3단계 — 이미지를 빌드하고 minikube에 로드
# Build locally
docker build -t mcp-k8s-server:latest .
# Load into minikube's image registry (no registry push needed)
minikube image load mcp-k8s-server:latest
# Verify the image is available
minikube image ls | grep mcp-k8s-server4단계 — Kubernetes 매니페스트 적용
# Apply in dependency order: SA → Role → Binding → Deployment
kubectl apply -f k8s/serviceaccount.yaml
kubectl apply -f k8s/role.yaml
kubectl apply -f k8s/rolebinding.yaml
kubectl apply -f k8s/deployment.yaml5단계 — 포드가 실행 중인지 확인
kubectl get pods -n mcp-system
# Expected:
# NAME READY STATUS RESTARTS AGE
# mcp-k8s-server-xxxxxxxxx-xxxxx 1/1 Running 0 30s
kubectl logs -n mcp-system deploy/mcp-k8s-server
# Expected: "Using in-cluster Kubernetes config (ServiceAccount token)"6단계 — 클러스터 내에서 읽기 전용 도구 테스트
# Port-forward to access the server from your laptop
kubectl port-forward -n mcp-system svc/mcp-k8s-server 8000:8000 &
# Create a test pod to query
kubectl run nginx-test --image=nginx --restart=Never
# Test list_pods
curl -s http://localhost:8000/tools/list_pods \
-H 'Content-Type: application/json' \
-d '{"namespace":"default"}' | jq .
# Test get_pod_logs
curl -s http://localhost:8000/tools/get_pod_logs \
-H 'Content-Type: application/json' \
-d '{"pod_name":"nginx-test","namespace":"default","tail_lines":20}' | jq .
# Test analyze_pod_health
curl -s http://localhost:8000/tools/analyze_pod_health \
-H 'Content-Type: application/json' \
-d '{"namespace":"default","hours":1}' | jq .7단계 — RBAC가 쓰기 작업을 차단함을 입증
ServiceAccount에는 쓰기 동사(verbs)가 없습니다. 이를 확인하려면:
# Exec into the pod and try to delete another pod using the SA token
MCP_POD=$(kubectl get pod -n mcp-system -l app=mcp-k8s-server -o jsonpath='{.items[0].metadata.name}')
kubectl exec -n mcp-system $MCP_POD -- \
kubectl delete pod nginx-test --namespace=default \
--token=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token) \
--server=https://kubernetes.default.svc \
--certificate-authority=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt예상 출력:
Error from server (Forbidden): pods "nginx-test" is forbidden:
User "system:serviceaccount:mcp-system:mcp-server-sa" cannot delete
resource "pods" in API group "" in the namespace "default"API 서버의 403 Forbidden 응답은 RBAC 범위 지정이 작동한다는 직접적인 증거입니다. ServiceAccount는 읽을 수 있지만 어떤 리소스도 수정할 수 없습니다.
RBAC 최소 권한 설계
설계 철학
필요한 것만 부여하고, 그 외 모든 것은 명시적으로 거부한다.
MCP 서버는 관측 도구입니다. 운영자와 AI 시스템이 상황을 이해할 수 있도록 클러스터 상태를 읽습니다. MCP 서버가 리소스를 생성, 수정, 삭제해야 할 정당한 이유는 없습니다.
부여되는 권한
리소스 | 동사 | 이유 |
|
|
|
|
|
|
|
|
|
|
|
|
명시적으로 부여되지 않는 권한
동사 | 제외 이유 |
| 어떤 도구도 리소스를 생성하지 않음 |
| 어떤 도구도 리소스를 수정하지 않음 |
| 오용 시 치명적이며, 어떤 읽기 도구도 필요로 하지 않음 |
| 권한 상승을 방지 |
즉, 손상된 MCP 서버는 포드를 삭제하거나, 디플로이먼트를 0으로 축소하거나, 시크릿을 수정하거나, 실행 중인 워크로드에 영향을 줄 수 없습니다. 손상된 MCP 서버의 폭발 반경은 정보를 읽는 것으로 제한되며, 정보를 방해하는 것은 아닙니다.
분석 계층
analyze_pod_health
네임스페이스의 모든 포드를 나열합니다.
포드당 최대 500줄의 로그를 가져옵니다.
알려진 실패 지표 목록과 패턴 매칭합니다:
OOMKilled,CrashLoopBackOffPython/Java 예외 (Traceback, RuntimeError 등)
Panic, SIGSEGV/SIGKILL, 연결 오류, 권한 거부
Liveness/Readiness 프로브 실패
포드별 건강 점수를 계산합니다 (낮을수록 나쁨).
오류 빈도 수와 함께 최악 우선 순위로 포드를 반환합니다.
SQLite에 결과를 저장하여 과거 분석을 지원합니다.
get_resource_trends
Deployment 스펙에서 포드 셀렉터를 확인합니다.
포드 스펙에서 리소스 한도(limits) 를 읽습니다.
Kubernetes Metrics API (
metrics.k8s.io/v1beta1)를 쿼리하여 실시간 CPU/메모리를 가져옵니다.CPU와 메모리 각각에 대해 평균, 최대, 한도 대비 %를 계산합니다.
각 스냅샷을
mcp_analytics.db에 저장하여 호출 간 트렌드가 누적되도록 합니다.
metrics-server애드온이 필요합니다:minikube addons enable metrics-server
CI / 지속적 통합
GitHub Actions 워크플로(.github/workflows/ci.yml)는 모든 푸시와 PR에서 실행됩니다.
Docker Build — 이미지를 푸시하지 않고 빌드합니다 (Dockerfile + 종속성 검증).
kubeconform — 모든
k8s/*.yaml매니페스트를 Kubernetes 1.29 스키마에 대해 엄격 모드로 검증합니다.ruff —
k8s_mcp_server.py의 Python 오류 및 스타일을 린트합니다.
환경 변수
변수 | 기본값 | 설명 |
|
| SQLite 분석 데이터베이스 경로 |
라이선스
MIT
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
Related MCP Connectors
Read-only production context for AI agents: Docker/K8s health, deploys, logs, traffic, code graph
Provides read access to your GKE and Kubernetes resources.
Read-only Linux server and Docker monitoring for AI assistants: CPU, memory, disk, network.
Read-only server insight: why a Linux server or K8s cluster is slow, failing or changed.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceProvides read-only access to Kubernetes clusters for AI assistants.25MIT
- AlicenseAqualityCmaintenanceEnables safe, read-only interaction with Kubernetes clusters, allowing users to list resources and fetch logs without any create/update/delete operations.1119 PyPI7Apache 2.0
- FlicenseNot gradedqualityDmaintenanceProvides read-only Kubernetes cluster operations via MCP, enabling LLMs to query nodes, pods, logs, events, and watch real-time status for troubleshooting.2-
- AlicenseNot gradedqualityDmaintenanceLets AI agents inspect Kubernetes clusters in plain English, exposing read-only tools for pods, deployments, services, events, and logs, with mock and real backend support.MIT