Mozaar commited on
Commit
3d898cc
·
1 Parent(s): f073083

feat: add Gradio mock demo - full MCP pipeline simulation

Browse files

- 5 MCP tools simulated (list_pods, get_pod_status, read_logs, describe_deployment, restart_service)
- Full pipeline tab: autonomous remediation in one click
- Immutable audit log visible in real-time
- Zero API credits needed - mock data only
- INTENTIONAL_CRASH detection demo

Files changed (3) hide show
  1. app.py +315 -0
  2. mock_engine.py +142 -0
  3. requirements.txt +1 -0
app.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import time
4
+ from mock_engine import run_tool, get_audit_log, MOCK_PODS
5
+
6
+
7
+ def fmt_json(data: dict) -> str:
8
+ return json.dumps(data, indent=2, ensure_ascii=False)
9
+
10
+
11
+ # ── Tool functions ────────────────────────────────────────────────────────────
12
+
13
+ def tool_list_pods(namespace, token):
14
+ if not token:
15
+ return "ERROR: Token required", ""
16
+ result = run_tool("list_pods", {"namespace": namespace})
17
+ summary = (
18
+ "Total: " + str(result["total"]) +
19
+ " | Healthy: " + str(result["healthy"]) +
20
+ " | Crashed: " + str(result["crashed"])
21
+ )
22
+ if result["attention"]:
23
+ summary += "\n\nATTENTION: " + ", ".join(result["attention"])
24
+ return fmt_json(result), summary
25
+
26
+
27
+ def tool_get_pod_status(pod_name, namespace, token):
28
+ if not token:
29
+ return "ERROR: Token required"
30
+ result = run_tool("get_pod_status", {
31
+ "pod_name": pod_name,
32
+ "namespace": namespace,
33
+ })
34
+ return fmt_json(result)
35
+
36
+
37
+ def tool_read_logs(pod_name, namespace, token, tail_lines):
38
+ if not token:
39
+ return "ERROR: Token required"
40
+ result = run_tool("read_logs", {
41
+ "pod_name": pod_name,
42
+ "namespace": namespace,
43
+ "tail_lines": int(tail_lines),
44
+ })
45
+ return result["logs"]
46
+
47
+
48
+ def tool_describe_deployment(deployment_name, namespace, token):
49
+ if not token:
50
+ return "ERROR: Token required"
51
+ result = run_tool("describe_deployment", {
52
+ "deployment_name": deployment_name,
53
+ "namespace": namespace,
54
+ })
55
+ output = fmt_json(result)
56
+ if result.get("diagnosis") == "INTENTIONAL_CRASH":
57
+ output += (
58
+ "\n\n" + "=" * 50 +
59
+ "\nDIAGNOSIS: INTENTIONAL_CRASH" +
60
+ "\nRoot cause: 'exit 1' detected in container command." +
61
+ "\nRestarting alone will NOT fix this." +
62
+ "\n" + "=" * 50
63
+ )
64
+ return output
65
+
66
+
67
+ def tool_restart_service(pod_name, namespace, token, confirm):
68
+ if not token:
69
+ return "ERROR: Token required"
70
+ result = run_tool("restart_service", {
71
+ "pod_name": pod_name,
72
+ "namespace": namespace,
73
+ "confirm": confirm,
74
+ })
75
+ return fmt_json(result)
76
+
77
+
78
+ def run_full_pipeline(namespace, token):
79
+ if not token:
80
+ empty = "ERROR: Token required"
81
+ return empty, empty, empty, empty, empty, empty
82
+
83
+ r1 = run_tool("list_pods", {"namespace": namespace})
84
+ time.sleep(0.2)
85
+
86
+ web_pod = next(
87
+ (p["name"] for p in r1["pods"] if "web-app" in p["name"]),
88
+ "web-app-f6c49bc8-cxjpf"
89
+ )
90
+
91
+ r2 = run_tool("read_logs", {
92
+ "pod_name": web_pod,
93
+ "namespace": namespace,
94
+ "tail_lines": 50,
95
+ })
96
+ time.sleep(0.2)
97
+
98
+ r3 = run_tool("get_pod_status", {
99
+ "pod_name": web_pod,
100
+ "namespace": namespace,
101
+ })
102
+ time.sleep(0.2)
103
+
104
+ r4 = run_tool("describe_deployment", {
105
+ "deployment_name": "web-app",
106
+ "namespace": namespace,
107
+ })
108
+ time.sleep(0.2)
109
+
110
+ r5 = run_tool("restart_service", {
111
+ "pod_name": web_pod,
112
+ "namespace": namespace,
113
+ "confirm": True,
114
+ })
115
+
116
+ logs = get_audit_log()
117
+ audit = "\n".join([
118
+ e["timestamp"] + " | " + e["tool"] + " | success=" + str(e["success"])
119
+ for e in logs[-10:]
120
+ ])
121
+
122
+ return (
123
+ fmt_json(r1),
124
+ r2["logs"],
125
+ fmt_json(r3),
126
+ fmt_json(r4),
127
+ fmt_json(r5),
128
+ audit,
129
+ )
130
+
131
+
132
+ def refresh_audit():
133
+ logs = get_audit_log()
134
+ if not logs:
135
+ return "No tool calls yet. Run a tool first."
136
+ return "\n".join([
137
+ e["timestamp"] + " | " + e["tool"] +
138
+ " | ns=" + e["namespace"] +
139
+ " | success=" + str(e["success"])
140
+ for e in logs
141
+ ])
142
+
143
+
144
+ # ── Gradio UI ─────────────────────────────────────────────────────────────────
145
+
146
+ THEME = gr.themes.Soft(
147
+ primary_hue="orange",
148
+ secondary_hue="blue",
149
+ )
150
+
151
+ with gr.Blocks(theme=THEME, title="MCP Infra Operator") as demo:
152
+
153
+ gr.Markdown("""
154
+ # 🔧 MCP Infra Operator
155
+ ### Autonomous Kubernetes Remediation via Model Context Protocol
156
+
157
+ > **Mock demo** — Full pipeline simulation without a real cluster or API credits.
158
+ > Simulates a `CrashLoopBackOff` incident and demonstrates autonomous root cause analysis.
159
+
160
+ [![GitHub](https://img.shields.io/badge/GitHub-MozaarAI--Agentic-181717?logo=github)](https://github.com/MozaarAI-Agentic/Project3-MCP-Infra-Operator)
161
+ [![MCP](https://img.shields.io/badge/MCP-Protocol-D97757?logo=anthropic)](https://modelcontextprotocol.io)
162
+ [![Kubernetes](https://img.shields.io/badge/Kubernetes-1.35+-326CE5?logo=kubernetes)](https://kubernetes.io)
163
+ [![Tests](https://img.shields.io/badge/Tests-40_passed-22C55E)](https://github.com/MozaarAI-Agentic/Project3-MCP-Infra-Operator)
164
+ """)
165
+
166
+ # ── Auth + Cluster state ──────────────────────────────────────────────────
167
+ with gr.Row():
168
+ with gr.Column(scale=1):
169
+ gr.Markdown("### 🔑 Authentication")
170
+ token_input = gr.Textbox(
171
+ label="MCP Token",
172
+ placeholder="Enter: mcp-dev-2026",
173
+ type="password",
174
+ value="mcp-dev-2026",
175
+ )
176
+ namespace_input = gr.Textbox(
177
+ label="Kubernetes Namespace",
178
+ value="default",
179
+ )
180
+
181
+ with gr.Column(scale=2):
182
+ gr.Markdown("### 🖥️ Mock Cluster State")
183
+ gr.Markdown("""
184
+ | Pod | Phase | Ready | Restarts | Status |
185
+ |-----|-------|-------|----------|--------|
186
+ | web-app-f6c49bc8-cxjpf | Running | ❌ | **99** | 🔴 CRASH |
187
+ | worker-777bbb8cb9-b844r | Running | ✅ | 0 | 🟢 OK |
188
+ | cache-69689c8c-hq55x | Running | ✅ | 0 | 🟢 OK |
189
+
190
+ > `web-app` is in **CrashLoopBackOff** — command: `sh -c "echo '...'; sleep 10; exit 1"`
191
+ """)
192
+
193
+ gr.Markdown("---")
194
+
195
+ # ── Tabs ──────────────────────────────────────────────────────────────────
196
+ with gr.Tabs():
197
+
198
+ # Full Pipeline
199
+ with gr.Tab("🚀 Full Pipeline"):
200
+ gr.Markdown("""
201
+ ### Autonomous Remediation Pipeline
202
+ Runs all 5 MCP tools in sequence:
203
+ `list_pods` → `read_logs` → `get_pod_status` → `describe_deployment` → `restart_service`
204
+ """)
205
+ run_btn = gr.Button(
206
+ "▶ Run Full Remediation Pipeline",
207
+ variant="primary",
208
+ size="lg",
209
+ )
210
+ with gr.Row():
211
+ out_list = gr.Textbox(label="Step 1 — list_pods", lines=10)
212
+ out_logs = gr.Textbox(label="Step 2 — read_logs", lines=10)
213
+ with gr.Row():
214
+ out_status = gr.Textbox(label="Step 3 — get_pod_status", lines=10)
215
+ out_desc = gr.Textbox(label="Step 4 — describe_deployment", lines=10)
216
+ with gr.Row():
217
+ out_restart = gr.Textbox(label="Step 5 — restart_service", lines=10)
218
+ out_audit_p = gr.Textbox(label="Audit Log", lines=10)
219
+
220
+ run_btn.click(
221
+ run_full_pipeline,
222
+ inputs=[namespace_input, token_input],
223
+ outputs=[out_list, out_logs, out_status, out_desc, out_restart, out_audit_p],
224
+ )
225
+
226
+ # list_pods
227
+ with gr.Tab("📋 list_pods"):
228
+ gr.Markdown("Lists all pods in a namespace. Auto-identifies CrashLoopBackOff. **Scope: READ**")
229
+ btn1 = gr.Button("Call list_pods", variant="primary")
230
+ with gr.Row():
231
+ out1 = gr.Textbox(label="Result (JSON)", lines=20)
232
+ sum1 = gr.Textbox(label="Summary", lines=5)
233
+ btn1.click(
234
+ tool_list_pods,
235
+ inputs=[namespace_input, token_input],
236
+ outputs=[out1, sum1],
237
+ )
238
+
239
+ # get_pod_status
240
+ with gr.Tab("🔍 get_pod_status"):
241
+ gr.Markdown("Returns detailed pod status with auto-diagnosis. **Scope: READ**")
242
+ pod_input2 = gr.Textbox(label="Pod Name", value="web-app-f6c49bc8-cxjpf")
243
+ btn2 = gr.Button("Call get_pod_status", variant="primary")
244
+ out2 = gr.Textbox(label="Result (JSON)", lines=20)
245
+ btn2.click(
246
+ tool_get_pod_status,
247
+ inputs=[pod_input2, namespace_input, token_input],
248
+ outputs=[out2],
249
+ )
250
+
251
+ # read_logs
252
+ with gr.Tab("📄 read_logs"):
253
+ gr.Markdown("Reads pod logs. Handles crashed containers via previous container support. **Scope: READ**")
254
+ pod_input3 = gr.Textbox(label="Pod Name", value="web-app-f6c49bc8-cxjpf")
255
+ tail_input = gr.Slider(label="Tail Lines", minimum=10, maximum=200, value=50, step=10)
256
+ btn3 = gr.Button("Call read_logs", variant="primary")
257
+ out3 = gr.Textbox(label="Logs", lines=10)
258
+ btn3.click(
259
+ tool_read_logs,
260
+ inputs=[pod_input3, namespace_input, token_input, tail_input],
261
+ outputs=[out3],
262
+ )
263
+
264
+ # describe_deployment
265
+ with gr.Tab("🏗️ describe_deployment"):
266
+ gr.Markdown("Reads full deployment spec. **Detects `exit 1` as INTENTIONAL_CRASH.** Scope: READ**")
267
+ deploy_input = gr.Textbox(label="Deployment Name", value="web-app")
268
+ btn4 = gr.Button("Call describe_deployment", variant="primary")
269
+ out4 = gr.Textbox(label="Result (JSON) + Diagnosis", lines=25)
270
+ btn4.click(
271
+ tool_describe_deployment,
272
+ inputs=[deploy_input, namespace_input, token_input],
273
+ outputs=[out4],
274
+ )
275
+
276
+ # restart_service
277
+ with gr.Tab("🔄 restart_service"):
278
+ gr.Markdown("""
279
+ **DESTRUCTIVE ACTION** — Deletes pod. Kubernetes recreates via ReplicaSet.
280
+ Requires `confirm=True`. **Scope: WRITE**
281
+ """)
282
+ pod_input5 = gr.Textbox(label="Pod Name", value="web-app-f6c49bc8-cxjpf")
283
+ confirm_check = gr.Checkbox(label="confirm=True (required to execute)", value=False)
284
+ btn5 = gr.Button("Call restart_service", variant="primary")
285
+ out5 = gr.Textbox(label="Result (JSON)", lines=15)
286
+ btn5.click(
287
+ tool_restart_service,
288
+ inputs=[pod_input5, namespace_input, token_input, confirm_check],
289
+ outputs=[out5],
290
+ )
291
+
292
+ # Audit Log
293
+ with gr.Tab("📊 Audit Log"):
294
+ gr.Markdown("""
295
+ ### Immutable Append-Only Audit Log
296
+ Every tool call is permanently recorded with timestamp, tool name, namespace, and result.
297
+ No modification. No deletion. Full traceability.
298
+ """)
299
+ btn_audit = gr.Button("Refresh Audit Log", variant="secondary")
300
+ out_audit_tab = gr.Textbox(label="Audit Log", lines=20)
301
+ btn_audit.click(refresh_audit, outputs=[out_audit_tab])
302
+
303
+ # ── Footer ────────────────────────────────────────────────────────────────
304
+ gr.Markdown("""
305
+ ---
306
+ **Built by [Bobby Mozaar](mailto:smozaar@gmail.com)** — AI Systems Architect · BigIcks Consulting · Cameroon 🇨🇲
307
+
308
+ [📂 GitHub Repository](https://github.com/MozaarAI-Agentic/Project3-MCP-Infra-Operator) |
309
+ [📖 MCP Protocol](https://modelcontextprotocol.io) |
310
+ [🤗 HuggingFace Space](https://huggingface.co/spaces/Mozaar/Project3-MCP-Infra-Operator)
311
+ """)
312
+
313
+
314
+ if __name__ == "__main__":
315
+ demo.launch()
mock_engine.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from datetime import datetime
3
+
4
+ MOCK_PODS = [
5
+ {
6
+ "name": "web-app-f6c49bc8-cxjpf",
7
+ "phase": "Running",
8
+ "ready": False,
9
+ "restarts": 99,
10
+ "namespace": "default"
11
+ },
12
+ {
13
+ "name": "worker-777bbb8cb9-b844r",
14
+ "phase": "Running",
15
+ "ready": True,
16
+ "restarts": 0,
17
+ "namespace": "default"
18
+ },
19
+ {
20
+ "name": "cache-69689c8c-hq55x",
21
+ "phase": "Running",
22
+ "ready": True,
23
+ "restarts": 0,
24
+ "namespace": "default"
25
+ },
26
+ ]
27
+
28
+ MOCK_LOGS = "web-app starting...\n[container exits with code 1 — no error message logged]"
29
+
30
+ MOCK_STATUS = {
31
+ "name": "web-app-f6c49bc8-cxjpf",
32
+ "phase": "Running",
33
+ "containers": [
34
+ {
35
+ "name": "web-app",
36
+ "state": "waiting",
37
+ "reason": "CrashLoopBackOff",
38
+ "restart_count": 99,
39
+ "ready": False,
40
+ }
41
+ ],
42
+ "action_required": True,
43
+ "diagnosis": [
44
+ "CRITICAL: web-app is in CrashLoopBackOff with 99 restarts"
45
+ ],
46
+ }
47
+
48
+ MOCK_DEPLOYMENT = {
49
+ "deployment": "web-app",
50
+ "namespace": "default",
51
+ "replicas": {"desired": 1, "ready": 0, "available": 0},
52
+ "strategy": "RollingUpdate",
53
+ "containers": [
54
+ {
55
+ "name": "web-app",
56
+ "image": "busybox",
57
+ "command": ["sh", "-c", "echo 'web-app starting...'; sleep 10; exit 1"],
58
+ "env_vars": [],
59
+ "liveness_probe": None,
60
+ "readiness_probe": None,
61
+ "resources": {
62
+ "requests": {"cpu": "50m", "memory": "32Mi"},
63
+ "limits": {"cpu": "100m", "memory": "64Mi"},
64
+ },
65
+ }
66
+ ],
67
+ "warnings": [
68
+ "CRITICAL: container 'web-app' has a command with 'exit 1' — intentional crash detected",
69
+ "INFO: container 'web-app' uses sleep + exit — demo crash pattern detected",
70
+ ],
71
+ "diagnosis": "INTENTIONAL_CRASH",
72
+ }
73
+
74
+ MOCK_RESTART = {
75
+ "success": True,
76
+ "pod": "web-app-f6c49bc8-cxjpf",
77
+ "namespace": "default",
78
+ "message": "Pod deleted. Kubernetes will recreate it automatically via ReplicaSet.",
79
+ "restarts_before": 99,
80
+ "action": "DELETE_AND_RECREATE",
81
+ "next_step": "Wait 15-30 seconds then call get_pod_status to verify recovery.",
82
+ }
83
+
84
+ AUDIT_LOG = []
85
+
86
+
87
+ def run_tool(tool_name: str, params: dict) -> dict:
88
+ ts = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
89
+ entry = {
90
+ "timestamp": ts,
91
+ "tool": tool_name,
92
+ "namespace": params.get("namespace", "default"),
93
+ "pod": params.get("pod_name", ""),
94
+ "success": True,
95
+ }
96
+ AUDIT_LOG.append(entry)
97
+
98
+ if tool_name == "list_pods":
99
+ crashed = [p for p in MOCK_PODS if p["restarts"] > 0]
100
+ return {
101
+ "namespace": params.get("namespace", "default"),
102
+ "total": len(MOCK_PODS),
103
+ "healthy": len(MOCK_PODS) - len(crashed),
104
+ "crashed": len(crashed),
105
+ "pods": MOCK_PODS,
106
+ "attention": [
107
+ p["name"] + " (" + str(p["restarts"]) + " restarts)"
108
+ for p in crashed
109
+ ],
110
+ }
111
+
112
+ elif tool_name == "get_pod_status":
113
+ return MOCK_STATUS
114
+
115
+ elif tool_name == "read_logs":
116
+ return {
117
+ "pod": params.get("pod_name", ""),
118
+ "namespace": params.get("namespace", "default"),
119
+ "tail_lines": params.get("tail_lines", 50),
120
+ "logs": MOCK_LOGS,
121
+ "has_errors": False,
122
+ "error_patterns_detected": [],
123
+ }
124
+
125
+ elif tool_name == "describe_deployment":
126
+ return MOCK_DEPLOYMENT
127
+
128
+ elif tool_name == "restart_service":
129
+ if not params.get("confirm", False):
130
+ return {
131
+ "error": "CONFIRMATION_REQUIRED",
132
+ "detail": "restart_service is destructive. Set confirm=True to proceed.",
133
+ "pod": params.get("pod_name", ""),
134
+ "namespace": params.get("namespace", "default"),
135
+ }
136
+ return MOCK_RESTART
137
+
138
+ return {"error": "TOOL_NOT_FOUND", "tool": tool_name}
139
+
140
+
141
+ def get_audit_log() -> list:
142
+ return AUDIT_LOG
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ gradio>=4.0.0