|
| 1 | +"""version.py - /version endpoint with rich diagnostic & HTML option **requiring authentication**. |
| 2 | +
|
| 3 | +Copyright 2025 |
| 4 | +SPDX-License-Identifier: Apache-2.0 |
| 5 | +Authors: Mihai Criveti |
| 6 | +
|
| 7 | +This module exposes a FastAPI router that returns a structured snapshot of the |
| 8 | +running MCP Gateway instance, its dependencies (database, Redis, OS), and key |
| 9 | +configuration flags. If the request's *Accept* header includes *text/html* or |
| 10 | +`?format=html` is passed, the endpoint will render a simple HTML dashboard; in |
| 11 | +all other cases it returns JSON. |
| 12 | +
|
| 13 | +Access to this endpoint is protected by the same authentication dependency |
| 14 | +(`require_auth`) used elsewhere in the gateway, so callers must supply a valid |
| 15 | +Bearer token (or Basic credentials if enabled). |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import json |
| 21 | +import os |
| 22 | +import platform |
| 23 | +import socket |
| 24 | +import time |
| 25 | +from datetime import datetime |
| 26 | +from typing import Any, Dict |
| 27 | + |
| 28 | +import redis.asyncio as aioredis |
| 29 | +from fastapi import APIRouter, Depends, Request |
| 30 | +from fastapi.responses import HTMLResponse, JSONResponse |
| 31 | +from sqlalchemy import text |
| 32 | + |
| 33 | +try: |
| 34 | + import psutil # optional - process & system metrics |
| 35 | +except ImportError: # pragma: no cover - psutil is optional |
| 36 | + psutil = None # type: ignore |
| 37 | + |
| 38 | +from mcpgateway.config import settings |
| 39 | +from mcpgateway.db import engine |
| 40 | +from mcpgateway.utils.verify_credentials import require_auth |
| 41 | + |
| 42 | +# ────────────────────────────────────────────────────────────────────────────── |
| 43 | +# Globals |
| 44 | +# ────────────────────────────────────────────────────────────────────────────── |
| 45 | + |
| 46 | +START_TIME = time.time() |
| 47 | +HOSTNAME = socket.gethostname() |
| 48 | +router = APIRouter(tags=["meta"]) |
| 49 | + |
| 50 | +# ────────────────────────────────────────────────────────────────────────────── |
| 51 | +# Helper utilities |
| 52 | +# ────────────────────────────────────────────────────────────────────────────── |
| 53 | + |
| 54 | + |
| 55 | +def _is_secret(key: str) -> bool: |
| 56 | + """Heuristic for redacting env‑vars that look secret.""" |
| 57 | + keywords = ("SECRET", "PASSWORD", "TOKEN", "KEY") |
| 58 | + return any(k in key.upper() for k in keywords) |
| 59 | + |
| 60 | + |
| 61 | +def _public_env() -> Dict[str, str]: |
| 62 | + """Return env‑vars with obvious secrets stripped out.""" |
| 63 | + return {k: v for k, v in os.environ.items() if not _is_secret(k)} |
| 64 | + |
| 65 | + |
| 66 | +def _database_version() -> tuple[str | None, bool]: |
| 67 | + """Attempt to fetch RDBMS version string; return (version, reachable).""" |
| 68 | + dialect = engine.dialect.name |
| 69 | + query_map = { |
| 70 | + "sqlite": "SELECT sqlite_version();", |
| 71 | + "postgresql": "SELECT current_setting('server_version');", |
| 72 | + "mysql": "SELECT version();", |
| 73 | + } |
| 74 | + query = query_map.get(dialect, "SELECT version();") |
| 75 | + try: |
| 76 | + with engine.connect() as conn: |
| 77 | + return conn.execute(text(query)).scalar() or "unknown", True |
| 78 | + except Exception as exc: # noqa: BLE001 - we surface raw error |
| 79 | + return str(exc), False |
| 80 | + |
| 81 | + |
| 82 | +def _system_metrics() -> Dict[str, Any]: |
| 83 | + """Return optional memory/CPU metrics if psutil available.""" |
| 84 | + if not psutil: |
| 85 | + return {} |
| 86 | + vm = psutil.virtual_memory() |
| 87 | + load1, load5, load15 = os.getloadavg() |
| 88 | + return { |
| 89 | + "cpu_count": psutil.cpu_count(logical=True), |
| 90 | + "load_avg": [load1, load5, load15], |
| 91 | + "mem_total_mb": round(vm.total / 1048576), |
| 92 | + "mem_used_mb": round(vm.used / 1048576), |
| 93 | + } |
| 94 | + |
| 95 | + |
| 96 | +def _build_payload(redis_version: str | None = None, redis_ok: bool = False) -> Dict[str, Any]: |
| 97 | + """Assemble structured diagnostic payload.""" |
| 98 | + db_version, db_ok = _database_version() |
| 99 | + |
| 100 | + payload: Dict[str, Any] = { |
| 101 | + "timestamp": datetime.utcnow().isoformat() + "Z", |
| 102 | + "host": HOSTNAME, |
| 103 | + "uptime_seconds": int(time.time() - START_TIME), |
| 104 | + "app": { |
| 105 | + "name": settings.app_name, |
| 106 | + "mcp_protocol_version": settings.protocol_version, |
| 107 | + }, |
| 108 | + "platform": { |
| 109 | + "python": platform.python_version(), |
| 110 | + "os": f"{platform.system()} {platform.release()} ({platform.machine()})", |
| 111 | + "fastapi": __import__("fastapi").__version__, |
| 112 | + "sqlalchemy": __import__("sqlalchemy").__version__, |
| 113 | + }, |
| 114 | + "database": { |
| 115 | + "dialect": engine.dialect.name, |
| 116 | + "url": settings.database_url, |
| 117 | + "reachable": db_ok, |
| 118 | + "server_version": db_version, |
| 119 | + }, |
| 120 | + "redis": { |
| 121 | + "url": settings.redis_url, |
| 122 | + "reachable": redis_ok, |
| 123 | + "server_version": redis_version, |
| 124 | + }, |
| 125 | + "settings": { |
| 126 | + "cache_type": settings.cache_type, |
| 127 | + "mcpgateway_ui_enabled": getattr(settings, "mcpgateway_ui_enabled", None), |
| 128 | + "mcpgateway_admin_api_enabled": getattr(settings, "mcpgateway_admin_api_enabled", None), |
| 129 | + }, |
| 130 | + "env": _public_env(), |
| 131 | + "system": _system_metrics(), |
| 132 | + } |
| 133 | + return payload |
| 134 | + |
| 135 | + |
| 136 | +def _render_html(data: Dict[str, Any]) -> str: |
| 137 | + """Very small hand‑rolled HTML template. No Jinja needed.""" |
| 138 | + |
| 139 | + def _table(obj: Dict[str, Any]) -> str: |
| 140 | + rows = "\n".join(f"<tr><th>{k}</th><td>{json.dumps(v, default=str) if not isinstance(v, str) else v}</td></tr>" for k, v in obj.items()) |
| 141 | + return f"<table>{rows}</table>" |
| 142 | + |
| 143 | + sections = [] |
| 144 | + for key in ( |
| 145 | + "app", |
| 146 | + "platform", |
| 147 | + "database", |
| 148 | + "redis", |
| 149 | + "settings", |
| 150 | + "system", |
| 151 | + ): |
| 152 | + sections.append(f"<h2>{key.title()}</h2>{_table(data[key])}") |
| 153 | + env_rows = "".join(f"<tr><th>{k}</th><td>{v}</td></tr>" for k, v in data["env"].items()) |
| 154 | + env_table = f"<h2>Environment</h2><table>{env_rows}</table>" |
| 155 | + info_hdr = f"<h1>MCP Gateway diagnostics</h1><p>Generated: {data['timestamp']} — Host: {data['host']} — Uptime: {data['uptime_seconds']} s</p>" |
| 156 | + style = """ |
| 157 | + <style> |
| 158 | + body{font-family:system-ui,sans-serif;margin:2rem;} |
| 159 | + table{border-collapse:collapse;width:100%;margin-bottom:1.5rem;} |
| 160 | + th,td{border:1px solid #ccc;padding:0.5rem;text-align:left;font-size:0.9rem;} |
| 161 | + th{background:#f7f7f7;width:22%;} |
| 162 | + h1{margin-top:0;} |
| 163 | + </style>""" |
| 164 | + return f"<!doctype html><html><head><meta charset='utf-8'>{style}</head><body>{info_hdr}{''.join(sections)}{env_table}</body></html>" |
| 165 | + |
| 166 | + |
| 167 | +# ────────────────────────────────────────────────────────────────────────────── |
| 168 | +# Endpoint |
| 169 | +# ────────────────────────────────────────────────────────────────────────────── |
| 170 | + |
| 171 | + |
| 172 | +@router.get( |
| 173 | + "/version", |
| 174 | + summary="Gateway diagnostic & dependency versions (auth required)", |
| 175 | + response_class=JSONResponse, |
| 176 | +) |
| 177 | +async def get_version( |
| 178 | + request: Request, |
| 179 | + format: str | None = None, |
| 180 | + user: str = Depends(require_auth), # 🛡️ enforce authentication |
| 181 | +): |
| 182 | + """Return JSON or HTML diagnostic snapshot (authentication required). |
| 183 | +
|
| 184 | + **JSON** is default; request HTML via: |
| 185 | + - `Accept: text/html` header |
| 186 | + - query param `?format=html` |
| 187 | + """ |
| 188 | + redis_version: str | None = None |
| 189 | + redis_ok = False |
| 190 | + |
| 191 | + if settings.cache_type.lower() == "redis" and settings.redis_url: |
| 192 | + try: |
| 193 | + redis = aioredis.Redis.from_url(settings.redis_url) |
| 194 | + await redis.ping() |
| 195 | + info = await redis.info() |
| 196 | + redis_version = info.get("redis_version") |
| 197 | + redis_ok = True |
| 198 | + except Exception as exc: # noqa: BLE001 - surface error |
| 199 | + redis_version = str(exc) |
| 200 | + |
| 201 | + data = _build_payload(redis_version, redis_ok) |
| 202 | + |
| 203 | + wants_html = format == "html" or "text/html" in request.headers.get("accept", "") |
| 204 | + if wants_html: |
| 205 | + return HTMLResponse(content=_render_html(data)) |
| 206 | + return JSONResponse(content=data) |
0 commit comments