Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
608 lines (516 loc) · 31.6 KB
/
Copy pathserver.py
File metadata and controls
608 lines (516 loc) · 31.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
import os
import json
import asyncio
import re
import time
import logging
import aiohttp
import ssl
from fastapi import FastAPI, Request, HTTPException, Response
from fastapi.responses import JSONResponse
from aioruckus import SystemStat
from aioruckus.ajaxsession import AjaxSession as _AjaxSession
from aioruckus.exceptions import AuthenticationError
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("ruckus-mcp")
RUCKUS_HOST = os.getenv("RUCKUS_HOST", "192.168.1.253")
RUCKUS_USER = os.getenv("RUCKUS_USER", "admin")
RUCKUS_PASS = os.getenv("RUCKUS_PASS", "")
MCP_SECRET = os.getenv("MCP_SECRET", "")
DOMAIN = os.getenv("DOMAIN", "ruckus-mcp.example.com")
if not RUCKUS_HOST: raise RuntimeError("RUCKUS_HOST not configured")
if not RUCKUS_USER: raise RuntimeError("RUCKUS_USER not configured")
if not RUCKUS_PASS: logger.warning("RUCKUS_PASS is empty")
STATIC_TOKEN = os.getenv("MCP_SECRET", "")
MAC_RE = re.compile(r"^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$")
app = FastAPI()
# ── Session ───────────────────────────────────────────────────────────────────
#
# Every tool call used to open a brand-new AjaxSession (a full HTTPS login
# round-trip to the AP controller) and log out again at the end. This section
# instead keeps one long-lived AjaxSession alive across calls, guarded by a
# lock so requests to the controller are always serialized (AjaxSession isn't
# designed for concurrent use — CSRF token and login state live on the session
# object). The session is recreated on an idle timeout or on a real connection
# failure; aioruckus's AjaxSession.request() already transparently re-logs in
# if the controller itself ends the session (redirect-to-login on a 302), so
# this is mainly about avoiding a login on every single call, not correctness.
async def _make_session():
"""Ruckus R500/R600 (Embedthis-Appweb 3.4.2) don't support HEAD via aiohttp.
Patch session.head = session.get. SECLEVEL=0 for weak certificate keys
(typical for self-signed certs on older Unleashed firmware)."""
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
ctx.set_ciphers("DEFAULT:@SECLEVEL=0")
websession = aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=10),
cookie_jar=aiohttp.CookieJar(unsafe=True),
connector=aiohttp.TCPConnector(keepalive_timeout=5, ssl=ctx),
)
websession.head = websession.get
return websession
_session_lock = asyncio.Lock()
_session = None
_websession = None
_session_last_used = 0.0
_SESSION_IDLE_LIMIT = 600 # seconds — headroom below the controller's own session idle timeout
class _PersistentSessionHandle:
"""Async context manager that reuses one long-lived AjaxSession instead of
logging in and out on every tool call. The lock is held for the whole tool
call (not just setup), so requests to the controller are always serialized."""
async def __aenter__(self):
global _session, _websession, _session_last_used
await _session_lock.acquire()
try:
now = time.time()
if _session is not None and (now - _session_last_used) > _SESSION_IDLE_LIMIT:
await self._close_locked()
if _session is None:
_websession = await _make_session()
_session = _AjaxSession(_websession, RUCKUS_HOST, RUCKUS_USER, RUCKUS_PASS,
auto_cleanup_websession=False)
await _session.__aenter__() # login
_session_last_used = now
return _session
except Exception:
# __aenter__ failed → __aexit__ will NOT be called (that's how the
# async with protocol works), so the lock must be released here or
# it stays held forever and every subsequent tool call hangs.
await self._close_locked()
_session_lock.release()
raise
async def __aexit__(self, exc_type, exc, tb):
# Connection-level failure (network/timeout/stale auth) — drop the
# session so the next call reconnects from scratch. Application-level
# errors (ValueError etc. from the tool functions themselves) don't
# touch the session — it's still perfectly usable.
if exc_type is not None and issubclass(exc_type, (ConnectionError, OSError, asyncio.TimeoutError, AuthenticationError)):
await self._close_locked()
_session_lock.release()
return False # don't suppress the exception
@staticmethod
async def _close_locked():
global _session, _websession
if _session is not None:
try:
await _session.close()
except Exception:
pass
if _websession is not None:
try:
await _websession.close()
except Exception:
pass
_session = None
_websession = None
def get_session():
return _PersistentSessionHandle()
# ── Startup self-test ─────────────────────────────────────────────────────────
@app.on_event("startup")
async def startup():
logger.info("Ruckus MCP starting → %s", RUCKUS_HOST)
try:
async with get_session() as session:
info = await session.api.get_system_info()
logger.info("Ruckus login OK: %s", list(info.keys()) if isinstance(info, dict) else "ok")
except Exception as e:
logger.error("Ruckus login FAILED: %s", e)
# ── Helpers ───────────────────────────────────────────────────────────────────
def _obj_to_dict(obj):
if isinstance(obj, dict):
return obj.copy()
if hasattr(obj, "__dict__"):
return dict(vars(obj))
if hasattr(obj, "__slots__"):
return {s: getattr(obj, s) for s in obj.__slots__ if hasattr(obj, s)}
return {}
def _normalize_mac(mac: str) -> str:
mac = mac.strip().lower().replace("-", ":").replace(".", ":")
plain = mac.replace(":", "")
if len(plain) == 12 and ":" not in mac:
mac = ":".join(plain[i:i+2] for i in range(0, 12, 2))
if not MAC_RE.fullmatch(mac):
raise ValueError(f"Invalid MAC: '{mac}'. Expected aa:bb:cc:dd:ee:ff")
return mac
def _require(args, key):
if key not in args or args[key] is None:
raise ValueError(f"'{key}' is required")
return args[key]
def _clean_ap(ap, stat=None):
"""`api.get_aps()` only returns identity fields (its 'name' is literally the
MAC, not a friendly name) — status/uptime/clients/channels/firmware live in
`api.get_ap_stats()` instead, under differently-named keys. Merge both here
rather than relying on get_aps() alone (that was the bug: every dynamic
field came back null).
NOTE: 'status' is inferred from stat['state'] == '1' (observed on healthy
APs) — unverified against a genuinely down AP, treat as best-effort.
'uptime_seconds_raw' is passed through unconverted: the raw value looked
too large for plain seconds against the AP's own reboot counters, so the
unit needs empirical confirmation before trusting it."""
ap = _obj_to_dict(ap)
stat = _obj_to_dict(stat) if stat else {}
radios = stat.get("radio") if isinstance(stat.get("radio"), list) else []
state = stat.get("state")
return {
"name": stat.get("ap-name") or ap.get("name"),
"mac": ap.get("mac") or stat.get("mac"),
"ip": ap.get("ip") or stat.get("ip"),
"model": ap.get("model") or stat.get("model"),
"serial": ap.get("serial") or stat.get("serial-number"),
"status": ({"1": "up"}.get(state, f"unknown (state={state})") if state is not None else None),
"uptime_seconds_raw": stat.get("uptime"),
"clients": stat.get("num-sta") or stat.get("assoc-stas"),
"channel-24": stat.get("channel-11ng"),
"channel-5": stat.get("channel-11na"),
"tx-power-24": radios[0].get("tx-power") if len(radios) > 0 else None,
"tx-power-5": radios[1].get("tx-power") if len(radios) > 1 else None,
"firmware": stat.get("firmware-version") or ap.get("firmware"),
"description": ap.get("description"),
}
def _clean_client(c):
c = _obj_to_dict(c)
keys = ["hostname","mac","ip","ssid","ap","ap-mac","radio-type","rssi","vlan","rx-bytes","tx-bytes","uptime"]
return {k: c[k] for k in keys if k in c}
def _clean_alarm(a):
a = _obj_to_dict(a)
keys = ["id","severity","type","description","timestamp","cleared"]
return {k: a[k] for k in keys if k in a}
def _clean_rogue(r):
r = _obj_to_dict(r)
keys = ["ssid","mac","channel","rssi","type","encryption","last-seen"]
return {k: r[k] for k in keys if k in r}
def _clean_event(e):
e = _obj_to_dict(e)
keys = ["id","type","severity","description","timestamp","ap","client","ssid"]
return {k: e[k] for k in keys if k in e}
def _clean_system_info(info):
"""get_system_info(SystemStat.ALL) returns the controller's ENTIRE raw config,
including admin.password in plaintext, TR-069/CWMP passwords, and AWS SNS/
PubNub secret keys. The tool only promises a network summary — so, like the
other _clean_* helpers, this whitelists only the safe fields."""
info = _obj_to_dict(info)
sysinfo = info.get("sysinfo", {}) or {}
identity = info.get("identity", {}) or {}
cpu = info.get("cpu-util", {}) or {}
ap_policy = info.get("ap-policy", {}) or {}
return {
"identity": identity.get("name"),
"model": sysinfo.get("model"),
"firmware_version": sysinfo.get("version"),
"uptime_seconds": sysinfo.get("uptime"),
"max_aps": sysinfo.get("maxap"),
"cpu_load_percent": cpu.get("now"),
"master_ap_mac": ap_policy.get("prefer-master"),
}
# ── Tools ─────────────────────────────────────────────────────────────────────
TOOLS = [
# ── Monitoring ────────────────────────────────────────────────────────────
{"name": "get_system_info", "description": "General info about the Unleashed network: firmware version, AP count, operating mode, master AP.", "inputSchema": {"type": "object", "properties": {}, "required": []}},
{"name": "get_aps", "description": "List of all access points: model, IP, MAC, status, uptime, 2.4/5 GHz channels, clients, TX power.", "inputSchema": {"type": "object", "properties": {}, "required": []}},
{"name": "get_ap_stats", "description": "Extended per-AP stats: rx/tx traffic bytes, channel load, clients per radio.", "inputSchema": {"type": "object", "properties": {}, "required": []}},
{"name": "get_ap_groups", "description": "List of AP groups and their settings.", "inputSchema": {"type": "object", "properties": {}, "required": []}},
{"name": "get_mesh_info", "description": "Mesh network info: root AP, member APs, uplink, backhaul RSSI.", "inputSchema": {"type": "object", "properties": {}, "required": []}},
{"name": "get_active_clients", "description": "List of connected clients: hostname, MAC, IP, SSID, AP, RSSI, VLAN, traffic, uptime.", "inputSchema": {"type": "object", "properties": {"ssid": {"type": "string", "description": "Filter by SSID (optional)"}, "ap_name": {"type": "string", "description": "Filter by AP name (optional)"}}, "required": []}},
{"name": "get_wlans", "description": "List of all SSIDs/WLANs: name, status, security, VLAN.", "inputSchema": {"type": "object", "properties": {}, "required": []}},
{"name": "get_wlan_groups", "description": "List of WLAN groups.", "inputSchema": {"type": "object", "properties": {}, "required": []}},
{"name": "get_vap_stats", "description": "VAP (Virtual Access Point) stats: traffic and clients per SSID on each AP.", "inputSchema": {"type": "object", "properties": {}, "required": []}},
{"name": "get_alarms", "description": "Recent alarms: type, severity, description, time (max 30).", "inputSchema": {"type": "object", "properties": {"limit": {"type": "integer", "description": "Max entries (default 20, max 30)", "default": 20}}, "required": []}},
{"name": "get_all_events", "description": "All network events: connects, disconnects, errors, roaming.", "inputSchema": {"type": "object", "properties": {"limit": {"type": "integer", "description": "Max entries (default 50, max 200)", "default": 50}}, "required": []}},
{"name": "get_ap_events", "description": "Events for a specific access point.", "inputSchema": {"type": "object", "properties": {"mac": {"type": "string", "description": "AP MAC address"}, "limit": {"type": "integer", "description": "Max entries (default 30)", "default": 30}}, "required": []}},
{"name": "get_wlan_events", "description": "Events for a specific SSID/WLAN.", "inputSchema": {"type": "object", "properties": {"ssid": {"type": "string", "description": "SSID name"}, "limit": {"type": "integer", "description": "Max entries (default 30)", "default": 30}}, "required": []}},
{"name": "get_syslog", "description": "Unleashed system log.", "inputSchema": {"type": "object", "properties": {"limit": {"type": "integer", "description": "Max lines (default 50)", "default": 50}}, "required": []}},
{"name": "get_rogues", "description": "List of rogue access points detected over the air.", "inputSchema": {"type": "object", "properties": {}, "required": []}},
{"name": "get_blocked_clients", "description": "List of blocked clients (MAC blocklist).", "inputSchema": {"type": "object", "properties": {}, "required": []}},
{"name": "get_dpsks", "description": "List of Dynamic PSK (DPSK) keys.", "inputSchema": {"type": "object", "properties": {}, "required": []}},
{"name": "get_acls", "description": "List of ACLs (Access Control Lists) and their members.", "inputSchema": {"type": "object", "properties": {}, "required": []}},
{"name": "debug_api_methods", "description": "Show all available aioruckus API methods.", "inputSchema": {"type": "object", "properties": {}, "required": []}},
# ── AP management ─────────────────────────────────────────────────────────
{"name": "reboot_ap", "description": "Reboot an access point by MAC. Format: 8c:fe:74:39:c2:e0", "inputSchema": {"type": "object", "properties": {"mac": {"type": "string", "description": "AP MAC address"}}, "required": ["mac"]}},
{"name": "show_ap_leds", "description": "Turn on LED indicators on an access point by MAC.", "inputSchema": {"type": "object", "properties": {"mac": {"type": "string", "description": "AP MAC address"}}, "required": ["mac"]}},
{"name": "hide_ap_leds", "description": "Turn off LED indicators on an access point by MAC.", "inputSchema": {"type": "object", "properties": {"mac": {"type": "string", "description": "AP MAC address"}}, "required": ["mac"]}},
# ── WLAN management ───────────────────────────────────────────────────────
{"name": "enable_wlan", "description": "Enable an SSID by name.", "inputSchema": {"type": "object", "properties": {"ssid": {"type": "string"}}, "required": ["ssid"]}},
{"name": "disable_wlan", "description": "Disable an SSID by name (clients will be disconnected).", "inputSchema": {"type": "object", "properties": {"ssid": {"type": "string"}}, "required": ["ssid"]}},
{"name": "set_wlan_password", "description": "Change a WLAN's password by SSID name.", "inputSchema": {"type": "object", "properties": {"ssid": {"type": "string", "description": "SSID name"}, "password": {"type": "string", "description": "New password (min 8 characters)"}}, "required": ["ssid", "password"]}},
# ── Client management ─────────────────────────────────────────────────────
{"name": "block_client", "description": "Block a client by MAC address.", "inputSchema": {"type": "object", "properties": {"mac": {"type": "string"}}, "required": ["mac"]}},
{"name": "unblock_client", "description": "Unblock a client by MAC address.", "inputSchema": {"type": "object", "properties": {"mac": {"type": "string"}}, "required": ["mac"]}},
]
# ── Tool logic ────────────────────────────────────────────────────────────────
async def run_tool(name, args):
async def _run():
async with get_session() as session:
api = session.api
# ── Monitoring ────────────────────────────────────────────────────
if name == "get_system_info":
return _clean_system_info(await api.get_system_info(SystemStat.ALL))
elif name == "get_aps":
aps = await api.get_aps()
stats = await api.get_ap_stats()
stats_by_mac = {}
for s in stats:
s = _obj_to_dict(s)
mac = (s.get("mac") or "").lower()
if mac:
stats_by_mac[mac] = s
return [
_clean_ap(ap, stats_by_mac.get((_obj_to_dict(ap).get("mac") or "").lower()))
for ap in aps
]
elif name == "get_ap_stats":
stats = await api.get_ap_stats()
if isinstance(stats, list):
return [_obj_to_dict(x) for x in stats]
return _obj_to_dict(stats)
elif name == "get_ap_groups":
groups = await api.get_ap_groups()
if isinstance(groups, list):
return [_obj_to_dict(g) for g in groups]
return _obj_to_dict(groups)
elif name == "get_mesh_info":
return _obj_to_dict(await api.get_mesh_info())
elif name == "get_active_clients":
clients = [_clean_client(c) for c in await api.get_active_clients()]
ssid_f = args.get("ssid", "").lower()
ap_f = args.get("ap_name", "").lower()
if ssid_f:
clients = [c for c in clients if ssid_f in (c.get("ssid") or "").lower()]
if ap_f:
clients = [c for c in clients if ap_f in (c.get("ap") or "").lower()]
return {"total": len(clients), "clients": clients}
elif name == "get_wlans":
result = []
for w in await api.get_wlans():
w = _obj_to_dict(w)
enc = w.get("encryption")
security = enc.get("method") if isinstance(enc, dict) else (str(enc) if enc else None)
result.append({
"name": w.get("name"),
"ssid": w.get("ssid", w.get("name")),
"enabled": not w.get("disabled", False),
"security": security,
"hidden": w.get("hidden", False),
"vlan": w.get("vlan"),
"description": w.get("description"),
})
return result
elif name == "get_wlan_groups":
groups = await api.get_wlan_groups()
if isinstance(groups, list):
return [_obj_to_dict(g) for g in groups]
return _obj_to_dict(groups)
elif name == "get_vap_stats":
stats = await api.get_vap_stats()
if isinstance(stats, list):
return [_obj_to_dict(x) for x in stats]
return _obj_to_dict(stats)
elif name == "get_alarms":
try:
limit = int(args.get("limit", 20))
except (ValueError, TypeError):
limit = 20
limit = max(1, min(limit, 30))
alarms = await api.get_all_alarms()
return [_clean_alarm(a) for a in alarms[:limit]]
elif name == "get_all_events":
try:
limit = int(args.get("limit", 50))
except (ValueError, TypeError):
limit = 50
limit = max(1, min(limit, 200))
events = await api.get_all_events()
if isinstance(events, list):
return [_clean_event(e) for e in events[:limit]]
return _obj_to_dict(events)
elif name == "get_ap_events":
try:
limit = int(args.get("limit", 30))
except (ValueError, TypeError):
limit = 30
mac = args.get("mac")
events = await api.get_ap_events()
if isinstance(events, list):
if mac:
mac = mac.lower()
events = [e for e in events if mac in str(_obj_to_dict(e).get("ap", "")).lower()]
return [_clean_event(e) for e in events[:limit]]
return _obj_to_dict(events)
elif name == "get_wlan_events":
try:
limit = int(args.get("limit", 30))
except (ValueError, TypeError):
limit = 30
ssid = args.get("ssid", "").lower()
events = await api.get_wlan_events()
if isinstance(events, list):
if ssid:
events = [e for e in events if ssid in str(_obj_to_dict(e).get("ssid", "")).lower()]
return [_clean_event(e) for e in events[:limit]]
return _obj_to_dict(events)
elif name == "get_syslog":
try:
limit = int(args.get("limit", 50))
except (ValueError, TypeError):
limit = 50
log = await api.get_syslog()
if isinstance(log, list):
return log[:limit]
return _obj_to_dict(log)
elif name == "get_rogues":
return {
"active_rogues": [_clean_rogue(r) for r in await api.get_active_rogues()],
"known_rogues": [_clean_rogue(r) for r in await api.get_known_rogues()],
}
elif name == "get_blocked_clients":
return {"blocked_macs": await api.get_blocked_client_macs()}
elif name == "get_dpsks":
dpsks = await api.get_dpsks()
if isinstance(dpsks, list):
return [_obj_to_dict(d) for d in dpsks]
return _obj_to_dict(dpsks)
elif name == "get_acls":
acls = await api.get_acls()
if isinstance(acls, list):
return [_obj_to_dict(a) for a in acls]
return _obj_to_dict(acls)
elif name == "debug_api_methods":
return {"methods": sorted(x for x in dir(api) if not x.startswith("_"))}
# ── AP management ────────────────────────────────────────────────
elif name == "reboot_ap":
mac = _normalize_mac(_require(args, "mac"))
await api.do_restart_ap(mac)
return {"status": "ok", "action": "reboot_ap", "mac": mac}
elif name == "show_ap_leds":
mac = _normalize_mac(_require(args, "mac"))
await api.do_show_ap_leds(mac)
return {"status": "ok", "action": "show_ap_leds", "mac": mac}
elif name == "hide_ap_leds":
mac = _normalize_mac(_require(args, "mac"))
await api.do_hide_ap_leds(mac)
return {"status": "ok", "action": "hide_ap_leds", "mac": mac}
# ── WLAN management ──────────────────────────────────────────────
elif name == "enable_wlan":
ssid = _require(args, "ssid")
await api.do_enable_wlan(ssid)
return {"status": "ok", "action": "enable_wlan", "ssid": ssid}
elif name == "disable_wlan":
ssid = _require(args, "ssid")
await api.do_disable_wlan(ssid)
return {"status": "ok", "action": "disable_wlan", "ssid": ssid}
elif name == "set_wlan_password":
ssid = _require(args, "ssid")
password = _require(args, "password")
if len(password) < 8:
raise ValueError("Password must be at least 8 characters")
await api.do_set_wlan_password(ssid, password)
return {"status": "ok", "action": "set_wlan_password", "ssid": ssid}
# ── Client management ────────────────────────────────────────────
elif name == "block_client":
mac = _normalize_mac(_require(args, "mac"))
await api.do_block_client(mac)
return {"status": "ok", "action": "block_client", "mac": mac}
elif name == "unblock_client":
mac = _normalize_mac(_require(args, "mac"))
await api.do_unblock_client(mac)
return {"status": "ok", "action": "unblock_client", "mac": mac}
else:
raise ValueError(f"Unknown tool: {name}")
return await asyncio.wait_for(_run(), timeout=15)
# ── Auth ──────────────────────────────────────────────────────────────────────
def check_auth(request: Request):
auth = request.headers.get("Authorization", "")
allowed = {f"Bearer {STATIC_TOKEN}"}
if MCP_SECRET:
allowed.add(f"Bearer {MCP_SECRET}")
if auth not in allowed:
raise HTTPException(status_code=401, detail="Unauthorized")
ALLOWED_REDIRECT_HOSTS = {"claude.ai", "anthropic.com", "console.anthropic.com"}
def validate_redirect_uri(uri: str):
from urllib.parse import urlparse
parsed = urlparse(uri)
host = (parsed.hostname or "").lower()
is_local = host in ("localhost", "127.0.0.1")
is_trusted = host in ALLOWED_REDIRECT_HOSTS or any(host.endswith("." + h) for h in ALLOWED_REDIRECT_HOSTS)
ok = (parsed.scheme == "http" and is_local) or (parsed.scheme == "https" and (is_local or is_trusted))
if not ok:
raise HTTPException(status_code=400, detail=f"redirect_uri not allowed: {uri}")
# ── Endpoints ─────────────────────────────────────────────────────────────────
@app.get("/")
async def root():
return {"status": "ruckus-mcp running", "version": "2.1.0", "host": RUCKUS_HOST}
@app.get("/mcp")
async def mcp_info(request: Request):
check_auth(request)
return {"protocolVersion": "2024-11-05", "capabilities": {"tools": {}}, "serverInfo": {"name": "ruckus-mcp", "version": "2.1.0"}}
@app.post("/mcp")
async def mcp_handler(request: Request):
check_auth(request)
try:
body = await request.json()
except Exception:
return JSONResponse({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}})
method = body.get("method")
req_id = body.get("id")
if method == "initialize":
return JSONResponse({"jsonrpc": "2.0", "id": req_id, "result": {
"protocolVersion": "2024-11-05",
"capabilities": {"tools": {}},
"serverInfo": {"name": "ruckus-mcp", "version": "2.1.0"}
}})
elif method == "notifications/initialized":
return Response(status_code=204)
elif method == "tools/list":
return JSONResponse({"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}})
elif method == "tools/call":
params = body.get("params", {})
tool_name = params.get("name")
tool_args = params.get("arguments")
if tool_args is None:
tool_args = {}
if not isinstance(tool_args, dict):
return JSONResponse({"jsonrpc": "2.0", "id": req_id, "error": {"code": -32602, "message": "arguments must be an object"}})
logger.info("Tool called: %s args=%s", tool_name, tool_args)
try:
result = await run_tool(tool_name, tool_args)
logger.info("Tool OK: %s", tool_name)
return JSONResponse({"jsonrpc": "2.0", "id": req_id, "result": {
"content": [{"type": "text", "text": json.dumps(result, ensure_ascii=False, indent=2, default=str)}],
"isError": False
}})
except asyncio.TimeoutError:
logger.error("Tool timeout: %s", tool_name)
return JSONResponse({"jsonrpc": "2.0", "id": req_id, "error": {"code": -32603, "message": "Ruckus API timeout after 15 seconds"}})
except Exception as e:
logger.exception("Tool failed: %s", tool_name)
return JSONResponse({"jsonrpc": "2.0", "id": req_id, "error": {"code": -32603, "message": str(e)}})
else:
return JSONResponse({"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}})
# ── OAuth stub ────────────────────────────────────────────────────────────────
@app.get("/.well-known/oauth-authorization-server")
async def oauth_metadata():
return {
"issuer": f"https://{DOMAIN}",
"authorization_endpoint": f"https://{DOMAIN}/oauth/authorize",
"token_endpoint": f"https://{DOMAIN}/oauth/token",
"response_types_supported": ["code"],
"grant_types_supported": ["authorization_code"]
}
@app.get("/oauth/authorize")
async def oauth_authorize(request: Request):
from fastapi.responses import RedirectResponse
params = dict(request.query_params)
redirect_uri = params.get("redirect_uri", "")
state = params.get("state", "")
if not redirect_uri:
raise HTTPException(status_code=400, detail="redirect_uri required")
validate_redirect_uri(redirect_uri)
return RedirectResponse(url=f"{redirect_uri}?code=ruckus-mcp-static-code&state={state}")
@app.post("/oauth/token")
async def oauth_token(request: Request):
form = await request.form()
if form.get("client_secret") != STATIC_TOKEN:
raise HTTPException(status_code=401, detail="Invalid client_secret")
return {"access_token": STATIC_TOKEN, "token_type": "bearer", "expires_in": 86400}