K8s MCP Server について
K8s MCP Server は、AI エージェントが 1 つ以上の Kubernetes クラスターでリソース操作、検出、ポートフォワードを行うためのサーバーです。kubectl 形式の出力に対応し、読み取り専用、状態変更、高リスクのツールを区別します。
主な機能
- 01リソースの一覧表示・確認・管理
- 02クラスターとリソース種別の検出
- 03kubectl 形式の出力
- 04ポートフォワードの設定と管理
- 05安全レベル別のツール分類
活用シーン
- 01クラスターのリソースと稼働状況の確認
- 02詳細情報やログを使った Pod の調査
- 03設定済みターゲットへのポートフォワード
- 04リソース更新前の変更内容の確認
MCP 対応
Kubernetes のリソース、検出、監視、ポートフォワードのツールを MCP クライアントに公開します。読み取り専用の照会に加え、状態変更や高リスクの操作にも対応します。
設定
ローカルサーバーの設定はどのクライアントでも共通です。コピーしてクライアントの MCP 設定ファイルに貼り付けてください。
このサーバーのパッケージやリモートエンドポイントはまだ取得できていません。プロジェクトの README の手順に従ってください。
ツール
ローカルサーバーのツールはマシン上で起動して初めて取得できます。メンテナーはまだツール一覧を提供していません。
詳細
K8s MCP サーバー
ヘッドレスサービスに対応した AI フレンドリーなポートフォワード管理により、Kubernetes へのアクセスを強化します。
✅ 実装完了 - すべてのコア機能が実装されています。
機能
- kubectl に着想を得た出力形式:効率的なトークン使用のための複数の出力形式(table、wide、json、yaml、custom-columns、jsonpath)
- リソース種別の検出:自然言語でのクエリにより、キーワードからカスタムリソース定義と組み込みリソースを検索
- URL ベースの設定:GitHub Gist またはローカルファイルを使用してポートフォワード設定を共有
- ヘッドレスサービスのサポート:ラベルセレクターによる Pod の直接指定
- AI 向けに最適化:インテリジェントなあいまい検索に適した、すっきりとしたサービス/ターゲット構造
- 複数形式のサポート:YAML、JSON、TOML の設定ファイル
- kubectl のような動作:
kubectl port-forwardと同様に、最初の Ready 状態の Pod を選択 - セッション管理:ポートフォワードの追跡をメモリ内で行い、一覧表示と終了が可能
- パラメーター不要の検出:AI エージェントがクラスター、エイリアス、サービスを簡単に検出可能
クイックスタート
1. 依存関係をインストールする
pip install -e .
2. 環境変数を設定する
# Required: Kubernetes cluster configurations
export KUBECONFIG_URLS="dev=file:///path/to/dev.yaml prod=file:///path/to/prod.yaml"
# Optional: Cluster aliases
export KUBECONFIG_ALIASES="development=dev production=prod"
# Required: Port-forward configuration URL
export PORT_FORWARD_CONFIG_URL="file://$(pwd)/example-port-forward-config.yaml"
# Or use a GitHub Gist:
# export PORT_FORWARD_CONFIG_URL="https://gist.githubusercontent.com/user/abc123/raw/port-forward.yaml"
3. サーバーを実行する
python main.py
使用例
AI エージェントとのやり取り
User: "Setup port-forward to the FRET Druid in development"
AI Agent:
1. Calls discover_port_forward_services() to understand available services
2. Maps "FRET Druid in development" → service="druid", target="fret-dev"
3. Calls setup_port_forward_to_target("druid", "fret-dev")
4. Returns: "✅ Connected to fret-dev Druid: http://localhost:8082 → pod/druid-router-0"
ツールの直接呼び出し
connect_to_service_targets("druid", ["fret-dev"])- 特定のターゲットに接続connect_to_service_targets("druid", [])- すべての Druid 環境に接続list_resources("prod", "pods", labels={"app": "nginx"})- ラベルを指定して Pod を一覧表示get_resource("dev", "deployment", "my-app", "default")- 特定のリソースを取得discover_resource_kinds("dev", ["druid", "ingestion"])- キーワードからリソース種別を検索list_resources("dev", "pods", output_format="custom-columns", custom_columns="NAME:.metadata.name,IP:.status.podIP")- カスタム出力list_port_forwards()- アクティブなポートフォワードセッションを表示teardown_port_forward("forward-id")- ポートフォワードセッションを終了- kubectl の命名バリエーションに対応:
"pods"、"pod"、"po"はすべて使用可能
出力形式の例
トークン効率の高いリソース一覧表示
# Default table format (kubectl-like)
list_resources(cluster="dev", kind="pods", namespace="fret-dev")
# Returns clean table: NAME | READY | STATUS | RESTARTS | AGE
特定のデータを取得するカスタム列
# Extract specific fields with JSONPath
list_resources(
cluster="dev",
kind="services",
output_format="custom-columns",
custom_columns="NAME:.metadata.name,TYPE:.spec.type,PORTS:.spec.ports[*].port"
)
リソース種別の検出
# Find resource kinds by keywords
discover_resource_kinds(
cluster="dev",
keywords=["druid", "ingestion"],
match_mode="OR"
)
# Returns: DruidIngestion resource kind info with all naming variants
リソースの命名規則
K8s MCP サーバーは kubectl の命名規則に従います。
リソース種別のサポート
- 複数形:
pods、services、deployments - 単数形:
pod、service、deployment - 略称:
po、svc、deploy、sts(StatefulSet の場合) - 大文字と小文字を区別しない:
Pod、POD、podはすべて使用可能
検出と検索
discover_*ツールは、利用可能なリソース種別/タイプを検索しますsearch_*およびlist_*ツールは、特定のインスタンスを検索します
ワークフローの例
# 1. Discover what kinds are available
discover_resource_kinds(cluster="dev", keywords=["druid"])
# Returns: DruidIngestion kind with variants ["druidingestions", "druidingestion"]
# 2. List instances using any variant
list_resources(cluster="dev", kind="druidingestions")
# or
list_resources(cluster="dev", kind="DruidIngestion")
設定
ポートフォワード設定の形式
druid:
fret-dev:
k8s_cluster: "dev-us-east"
namespace: "druid"
labels:
app.kubernetes.io/component: "router"
local_port: 8082
remote_port: 8888
grafana:
dev:
k8s_cluster: "dev-us-east"
namespace: "monitoring"
labels:
app.kubernetes.io/name: "grafana"
local_port: 3000
remote_port: 3000
よくあるワークフロー
以下のワークフロー例では、AI エージェントが複数のツールを組み合わせて、複雑な Kubernetes タスクを実行する方法を説明します。
1. クラスター概要ワークフロー
User: "Show me the status of all my clusters"
AI Agent Flow:
1. discover_clusters() → Get available clusters ["dev", "staging", "prod"]
2. For each cluster:
- cluster_health() → Check API server connectivity
- list_resources("cluster", "nodes") → Get node count and status
- list_resources("cluster", "namespaces") → Get namespace overview
3. Summarize: "3 clusters online, 12 total nodes, 8 namespaces"
2. アプリケーションのデバッグワークフロー
User: "My app isn't working in staging"
AI Agent Flow:
1. list_resources("staging", "pods", labels={"app": "user-app"}) → Find app pods
2. For each pod:
- describe_resource("staging", "pod", pod_name) → Get detailed status
- get_logs("staging", pod_name, lines=50) → Check recent logs
- list_resources("staging", "events", field_selector=f"involvedObject.name={pod_name}") → Get events
3. Analyze patterns: "Found 2 pods crash-looping due to missing config map 'app-config'"
3. 安全なデプロイ更新ワークフロー
User: "Update nginx deployment to version 1.21"
AI Agent Flow:
1. get_resource("prod", "deployment", "nginx") → Get current deployment
2. Modify image version in manifest
3. Present proposed changes: "Will update image from nginx:1.20 to nginx:1.21"
4. User confirms: "Apply it"
5. update_resource("prod", "deployment", "nginx", new_manifest) → Apply update
6. Monitor rollout status with deployment_status()
4. リソースのクリーンアップワークフロー
User: "Clean up all test resources from last week"
AI Agent Flow:
1. list_resources("dev", "all", labels={"purpose": "test", "created": "2024-01-15"}) → Find test resources
2. Group by type: "Found 5 pods, 3 services, 2 configmaps"
3. For each resource:
- Show resource details and age
4. Present deletion plan with resource details
5. User confirms: "Yes, delete them"
6. Execute deletions with proper cascade handling
5. 強化されたポートフォワードワークフロー
User: "Setup port-forward to the FRET Druid in development"
AI Agent Flow:
1. discover_port_forward_services() → Get available services/targets
2. AI reasoning: "FRET Druid in development" → service="druid", target="fret-dev"
3. connect_to_service_targets("druid", ["fret-dev"]) → Setup to specific target
4. Return: "✅ Connected to fret-dev Druid: http://localhost:8082 → pod/druid-router-0"
6. パフォーマンスのトラブルシューティングワークフロー
User: "Why is my app slow in production?"
AI Agent Flow:
1. list_resources("prod", "pods", labels={"app": "slow-app"}) → Find app pods
2. For each pod:
- describe_resource() → Check resource limits/requests
- get_logs(since="1h") → Check for performance-related logs
- execute_in_pod(["top", "-b", "-n", "1"]) → Get resource usage
3. list_resources("prod", "nodes") → Check node capacity
4. query_by_labels("prod", "hpa", "app=slow-app") → Check auto-scaling
5. Analyze: "App is CPU-throttled, increase CPU requests from 100m to 250m"
7. セキュリティ監査ワークフロー
User: "Audit RBAC permissions for the finance team"
AI Agent Flow:
1. list_resources("prod", "rolebindings") → Get all role bindings
2. list_resources("prod", "clusterrolebindings") → Get cluster-wide bindings
3. Filter by subjects containing "finance"
4. For each binding:
- get_resource("prod", "role", role_name) → Get role permissions
5. Summarize: "Finance team has read access to secrets in finance namespace"
8. 災害復旧ワークフロー
User: "Restore the database from backup"
AI Agent Flow:
1. list_resources("prod", "pods", labels={"app": "database"}) → Find DB pods
2. scale_resource("prod", "deployment", "database", replicas=0) → Scale down
3. Wait for pods to terminate
4. apply_manifest("prod", restore_job_manifest) → Apply restore job
5. Monitor job status until completion
6. scale_resource("prod", "deployment", "database", replicas=1) → Scale back up
7. Verify database connectivity
AI エージェントのベストプラクティス
- 変更を必ず事前確認する:変更前に diff/dry-run を使用します
- コンテキストを提示する:問題を報告する際は、関連情報を含めます
- 操作をまとめて実行する:関連する操作をまとめて効率化します
- ページネーションに対応する:結果セットが大きい場合があることに注意します
- クラスターの境界を守る:クラスターをまたぐ操作を想定してはいけません
ツールの安全性分類
すべての MCP ツールは、AI エージェントによる操作に対する安全性レベルで分類されています。
[READ-ONLY] ツール — 自律的な使用が安全です
これらのツールはデータの読み取りのみを行い、クラスターやローカルの状態を変更することはありません。
リソース操作:
get_resource()- 特定のリソースの詳細を取得get_resource_yaml()- リソースを YAML 形式で取得list_resources()- 書式設定オプションを指定してリソースを一覧表示list_resources_yaml()- リソースを YAML 形式で一覧表示query_by_labels()- ラベルに基づく高度なクエリquery_by_labels_yaml()- ラベルクエリを YAML 形式で実行
監視と分析:
troubleshoot_pod()- Pod の包括的なデバッグtroubleshoot_pod_yaml()- Pod のデバッグ結果を YAML 形式で取得cluster_health()- クラスター全体の健全性を評価deployment_status()- デプロイのロールアウトを分析deployment_status_yaml()- デプロイの分析結果を YAML 形式で取得resource_usage()- リソース消費を分析get_logs()- Pod のログを取得list_port_forwards()- アクティブなポートフォワードセッションを一覧表示
検出:
discover_resource_kinds()- キーワードからリソースタイプを検索discover_clusters()- 利用可能なクラスターを一覧表示discover_cluster_aliases()- クラスターのエイリアスを一覧表示discover_port_forward_services()- ポートフォワード設定を一覧表示
[MODIFIES STATE] ツール — ユーザーの承認が必要です
これらのツールはクラスターの状態またはローカルのネットワーク設定を変更します。
リソース管理:
create_resource()- 新しい Kubernetes リソースを作成update_resource()- 既存のリソースを更新patch_resource()- リソースを部分的に更新scale_resource()- レプリカ数を変更apply_manifest()- YAML マニフェストを適用
ネットワーク操作:
connect_to_service_targets()- 設定済みのサービス環境に接続setup_port_forward()- 汎用ポートフォワードを設定teardown_port_forward()- ポートフォワードセッションを終了
[DANGEROUS] ツール — 明示的なユーザー確認が必要です
これらのツールはデータ損失やセキュリティリスクを引き起こす可能性があります。
delete_resource()- リソースを完全に削除します(元に戻せません)execute_in_pod()- Pod 内で任意のコマンドを実行します(セキュリティリスクの可能性があります)
AI エージェントの安全ガイドライン
- 自律的な操作:AI エージェントは [READ-ONLY] ツールを自由に使用できます
- 状態の変更:[MODIFIES STATE] ツールにはユーザーの承認が必要です
- 高リスク操作:[DANGEROUS] ツールには明示的なユーザー確認が必要です
- エラー処理:すべてのツールは、安全に解析できる一貫したエラー形式を返します
アーキテクチャ
k8s-mcp/
├── main.py # MCP server entry point with tool definitions
├── config/ # Configuration management
│ ├── loader.py # URL-based config loading
│ ├── manager.py # Cluster and port-forward session management
│ └── config.py # Environment validation and configuration
├── tools/ # Modular tool implementations
│ ├── resources.py # Common resource operation patterns
│ ├── formatting.py # All resource formatting (table, YAML, JSON)
│ ├── columns.py # Default column definitions for resources
│ ├── discovery.py # Resource kind discovery and CRD enumeration
│ └── port_forward.py # Port-forward specific operations
└── utils/ # Shared utilities
├── helpers.py # Common helper functions
└── jsonpath.py # JSONPath processing for custom columns
コード構成の原則
- 単一責任:各モジュールの目的は明確かつ限定されています
- DRY の遵守:ファイル間で実装を重複させません
- 関心事の分離:クライアント管理、書式設定、ビジネスロジックを分離します
- モジュール設計:ツールを個別にインポートし、再利用できます
コメント
AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。