Skip to main content
Glama
Krishna1704M

mcp-k8s-context-server

by Krishna1704M

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.


기능

도구

설명

list_pods(namespace)

네임스페이스의 포드를 단계 및 재시작 정보와 함께 나열합니다.

get_pod_status(pod_name, namespace)

포드 상태, 조건, 컨테이너 상태에 대한 상세 정보를 제공합니다.

get_pod_logs(pod_name, namespace, tail_lines)

최근 포드 로그를 tail로 표시합니다.

get_deployment_manifest(deployment_name, namespace)

전체 디플로이먼트 스펙을 JSON으로 제공합니다.

analyze_pod_health(namespace, hours)

분석: 로그를 스캔하고 오류 패턴을 탐지하며 비정상 포드를 순위로 매깁니다.

get_resource_trends(deployment_name, namespace)

분석: Metrics API의 CPU/메모리를 수집하고 SQLite에 기록하여 과거 추세를 유지합니다.


Related MCP server: Kube MCP

프로젝트 구조

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     # >= 24

1단계 — minikube 시작

minikube start --cpus=2 --memory=4096

2단계 — metrics-server 활성화 (get_resource_trends에 필요)

minikube addons enable metrics-server

3단계 — 이미지를 빌드하고 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-server

4단계 — 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.yaml

5단계 — 포드가 실행 중인지 확인

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 서버가 리소스를 생성, 수정, 삭제해야 할 정당한 이유는 없습니다.

부여되는 권한

리소스

동사

이유

pods

get, list, watch

list_pods, get_pod_status, analyze_pod_health

pods/log

get, list, watch

get_pod_logs, analyze_pod_health

deployments

get, list, watch

get_deployment_manifest, get_resource_trends

metrics.k8s.io/pods

get, list

get_resource_trends (Metrics API)

명시적으로 부여되지 않는 권한

동사

제외 이유

create

어떤 도구도 리소스를 생성하지 않음

update / patch

어떤 도구도 리소스를 수정하지 않음

delete / deletecollection

오용 시 치명적이며, 어떤 읽기 도구도 필요로 하지 않음

escalate / bind

권한 상승을 방지

즉, 손상된 MCP 서버는 포드를 삭제하거나, 디플로이먼트를 0으로 축소하거나, 시크릿을 수정하거나, 실행 중인 워크로드에 영향을 줄 수 없습니다. 손상된 MCP 서버의 폭발 반경은 정보를 읽는 것으로 제한되며, 정보를 방해하는 것은 아닙니다.


분석 계층

analyze_pod_health

  1. 네임스페이스의 모든 포드를 나열합니다.

  2. 포드당 최대 500줄의 로그를 가져옵니다.

  3. 알려진 실패 지표 목록과 패턴 매칭합니다:

    • OOMKilled, CrashLoopBackOff

    • Python/Java 예외 (Traceback, RuntimeError 등)

    • Panic, SIGSEGV/SIGKILL, 연결 오류, 권한 거부

    • Liveness/Readiness 프로브 실패

  4. 포드별 건강 점수를 계산합니다 (낮을수록 나쁨).

  5. 오류 빈도 수와 함께 최악 우선 순위로 포드를 반환합니다.

  6. SQLite에 결과를 저장하여 과거 분석을 지원합니다.

  1. Deployment 스펙에서 포드 셀렉터를 확인합니다.

  2. 포드 스펙에서 리소스 한도(limits) 를 읽습니다.

  3. Kubernetes Metrics API (metrics.k8s.io/v1beta1)를 쿼리하여 실시간 CPU/메모리를 가져옵니다.

  4. CPU와 메모리 각각에 대해 평균, 최대, 한도 대비 %를 계산합니다.

  5. 각 스냅샷을 mcp_analytics.db저장하여 호출 간 트렌드가 누적되도록 합니다.

metrics-server 애드온이 필요합니다: minikube addons enable metrics-server


CI / 지속적 통합

GitHub Actions 워크플로(.github/workflows/ci.yml)는 모든 푸시와 PR에서 실행됩니다.

  1. Docker Build — 이미지를 푸시하지 않고 빌드합니다 (Dockerfile + 종속성 검증).

  2. kubeconform — 모든 k8s/*.yaml 매니페스트를 Kubernetes 1.29 스키마에 대해 엄격 모드로 검증합니다.

  3. ruffk8s_mcp_server.py의 Python 오류 및 스타일을 린트합니다.


환경 변수

변수

기본값

설명

MCP_DB_PATH

mcp_analytics.db

SQLite 분석 데이터베이스 경로


라이선스

MIT

F
license - not found
-
quality - not tested
C
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

View all related MCP servers

Related MCP Connectors

  • Read-only bank access for your AI agent. Connects Claude, ChatGPT, Cursor, Gemini, Codex.

  • Read-only access to Auralogs production logs: search logs, inspect errors, review AI analyses.

  • Operate Linux, macOS and Windows from your LLM. Every action runs through an auditable allowlist.

View all MCP Connectors

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/Krishna1704M/mcp-k8s-context-server'

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