|
| 1 | +import asyncio |
| 2 | +import uuid |
| 3 | +from typing import Any, Awaitable, Callable, Dict |
| 4 | + |
| 5 | +from kubernetes_asyncio import client, config, watch |
| 6 | + |
| 7 | + |
| 8 | +class KubernetesEvents: |
| 9 | + """ |
| 10 | + Handles Kubernetes resource watching for the MCP server. |
| 11 | + This class is dynamically loaded by mcpserver if defined in config. |
| 12 | + """ |
| 13 | + |
| 14 | + def __init__(self): |
| 15 | + self._active_watches: Dict[str, asyncio.Task] = {} |
| 16 | + try: |
| 17 | + config.load_incluster_config() |
| 18 | + except config.ConfigException: |
| 19 | + asyncio.run(config.load_kube_config()) |
| 20 | + |
| 21 | + def get_metadata(self) -> Dict[str, Any]: |
| 22 | + """ |
| 23 | + Returns static discovery info for the Agent. |
| 24 | + The Agent uses this to know what parameters to send. |
| 25 | + """ |
| 26 | + return { |
| 27 | + "name": "kubernetes_events", |
| 28 | + "description": "Subscribe to events for Kubernetes resources (Pods, Deployments, etc.)", |
| 29 | + "parameters": { |
| 30 | + "resource_type": "string (e.g., pods, deployments, kustomizations)", |
| 31 | + "namespace": "string", |
| 32 | + "label_selector": "string (optional)", |
| 33 | + "field_selector": "string (optional)", |
| 34 | + }, |
| 35 | + } |
| 36 | + |
| 37 | + async def subscribe( |
| 38 | + self, params: Dict[str, Any], callback: Callable[[str, Dict[str, Any]], Awaitable[None]] |
| 39 | + ) -> str: |
| 40 | + """ |
| 41 | + Starts a Kubernetes watch task in the background. |
| 42 | + """ |
| 43 | + sub_id = f"k8s_{uuid.uuid4().hex[:8]}" |
| 44 | + |
| 45 | + # Spin up the background listener |
| 46 | + task = asyncio.create_task(self._watch_loop(sub_id, params, callback)) |
| 47 | + self._active_watches[sub_id] = task |
| 48 | + |
| 49 | + return sub_id |
| 50 | + |
| 51 | + async def unsubscribe(self, sub_id: str) -> bool: |
| 52 | + """ |
| 53 | + Stops a specific watch task. |
| 54 | + """ |
| 55 | + task = self._active_watches.pop(sub_id, None) |
| 56 | + if task: |
| 57 | + task.cancel() |
| 58 | + try: |
| 59 | + await task |
| 60 | + except asyncio.CancelledError: |
| 61 | + pass |
| 62 | + return True |
| 63 | + return False |
| 64 | + |
| 65 | + async def _watch_loop(self, sub_id: str, params: Dict[str, Any], callback: Callable): |
| 66 | + """ |
| 67 | + The internal async loop that communicates with the K8s API. |
| 68 | + """ |
| 69 | + resource_type = params.get("resource_type", "pods") |
| 70 | + namespace = params.get("namespace", "default") |
| 71 | + |
| 72 | + # Dynamic API selection based on resource type |
| 73 | + v1 = client.CoreV1Api() |
| 74 | + w = watch.Watch() |
| 75 | + |
| 76 | + try: |
| 77 | + # Note: This is an example for Pods. |
| 78 | + # You would extend this to support Deployments/Flux CRDs. |
| 79 | + method = getattr(v1, f"list_namespaced_{resource_type}") |
| 80 | + |
| 81 | + async with w.stream( |
| 82 | + method, |
| 83 | + namespace=namespace, |
| 84 | + label_selector=params.get("label_selector", ""), |
| 85 | + field_selector=params.get("field_selector", ""), |
| 86 | + ) as stream: |
| 87 | + async for event in stream: |
| 88 | + # Clean up the object for the LLM to save tokens |
| 89 | + obj = event["raw_object"] |
| 90 | + event_data = { |
| 91 | + "type": event["type"], |
| 92 | + "name": obj["metadata"]["name"], |
| 93 | + "status": obj.get("status", {}), |
| 94 | + "resource": resource_type, |
| 95 | + } |
| 96 | + |
| 97 | + # Push notification to MCP client via the provided callback |
| 98 | + await callback(sub_id, event_data) |
| 99 | + |
| 100 | + except asyncio.CancelledError: |
| 101 | + # Clean exit on unsubscribe |
| 102 | + pass |
| 103 | + except Exception as e: |
| 104 | + # Notify the agent that the watch failed |
| 105 | + await callback(sub_id, {"error": str(e), "status": "failed"}) |
| 106 | + finally: |
| 107 | + w.stop() |
0 commit comments