#!/usr/bin/env python """ NetAlertX MCP (Model Context Protocol) Server Endpoint This module implements a standards-compliant MCP server that exposes NetAlertX API endpoints as tools for AI assistants. It uses the registry-based OpenAPI spec generator to ensure strict type safety and validation. Key Features: - JSON-RPC 2.0 over MCP Streamable HTTP (/mcp) - Dynamic tool mapping from OpenAPI registry - Pydantic-based input validation - Standard MCP capabilities (tools, resources, prompts) - Session management with automatic cleanup Architecture: ┌──────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ AI Client │────▶│ MCP Server │────▶│ Internal API │ │ (Claude) │◀────│ (this module) │◀────│ (Flask routes) │ └──────────────┘ └─────────────────┘ └─────────────────┘ Streamable HTTP Loopback HTTP """ from __future__ import annotations import threading import json import uuid import queue import time import os import re from copy import deepcopy import secrets from typing import Optional, Dict, Any, List, Tuple from urllib.parse import quote from flask import request, jsonify, Response, stream_with_context import requests from pydantic import ValidationError from collections import deque from helper import get_setting_value from logger import mylog # Import the spec generator (our source of truth) from .openapi.spec_generator import generate_openapi_spec from .openapi.registry import get_registry, is_tool_disabled # ============================================================================= # CONSTANTS & CONFIGURATION # ============================================================================= SUPPORTED_PROTOCOL_VERSIONS = ("2024-11-05", "2025-03-26", "2025-06-18") MCP_DEFAULT_STREAMABLE_HTTP_VERSION = "2025-03-26" MCP_SERVER_NAME = "NetAlertX" MCP_SERVER_VERSION = "2.0.0" # Session & Request Limits SESSION_TIMEOUT = 300 # 5 minutes SSE_KEEPALIVE_INTERVAL = 20 # seconds MAX_ACTIVE_SESSIONS = 32 MAX_MCP_BODY_BYTES = 1_048_576 # 1 MB MAX_BATCH_SIZE = 10 SESSION_ID_PATTERN = re.compile(r"^[0-9a-f]{32}$") # ============================================================================= # SESSION MANAGEMENT # ============================================================================= # Thread-safe session storage _mcp_sessions: Dict[str, Dict[str, Any]] = {} _sessions_lock = threading.Lock() _SESSION_CLOSED = object() # Bounded concurrent SSE stream tracking (independent of session count) MAX_ACTIVE_SSE_STREAMS = 64 _active_sse_streams = 0 _sse_streams_lock = threading.Lock() def _acquire_sse_stream_slot() -> bool: """Reserve a concurrent SSE stream slot, returning False if at capacity.""" global _active_sse_streams with _sse_streams_lock: if _active_sse_streams >= MAX_ACTIVE_SSE_STREAMS: return False _active_sse_streams += 1 return True def _release_sse_stream_slot() -> None: """Release a previously acquired concurrent SSE stream slot.""" global _active_sse_streams with _sse_streams_lock: if _active_sse_streams > 0: _active_sse_streams -= 1 # Background cleanup thread _cleanup_thread: Optional[threading.Thread] = None _cleanup_stop_event = threading.Event() _cleanup_thread_lock = threading.Lock() def _signal_session_closed(message_queue: queue.Queue) -> None: """Signal any active GET /mcp stream generator to exit promptly.""" try: message_queue.put_nowait(_SESSION_CLOSED) except queue.Full: try: message_queue.get_nowait() message_queue.put_nowait(_SESSION_CLOSED) except (queue.Empty, queue.Full): pass def _evict_expired_sessions_locked() -> None: """Evict expired sessions while holding _sessions_lock.""" current_time = time.time() expired_sessions = [ sid for sid, sdata in _mcp_sessions.items() if current_time - sdata.get("last_activity", 0) > SESSION_TIMEOUT ] for sid in expired_sessions: mylog("verbose", [f"[MCP] Cleaning up expired session: {sid}"]) sdata = _mcp_sessions.pop(sid, None) if sdata and "queue" in sdata: _signal_session_closed(sdata["queue"]) def _cleanup_sessions(): """Background thread to clean up expired sessions.""" while not _cleanup_stop_event.is_set(): try: with _sessions_lock: _evict_expired_sessions_locked() except Exception as e: mylog("none", [f"[MCP] Session cleanup error: {e}"]) # Sleep in small increments to allow graceful shutdown for _ in range(60): # Check every minute if _cleanup_stop_event.is_set(): break time.sleep(1) def _ensure_cleanup_thread(): """Ensure the cleanup thread is running.""" global _cleanup_thread if _cleanup_thread is None or not _cleanup_thread.is_alive(): with _cleanup_thread_lock: if _cleanup_thread is None or not _cleanup_thread.is_alive(): _cleanup_stop_event.clear() _cleanup_thread = threading.Thread(target=_cleanup_sessions, daemon=True) _cleanup_thread.start() def is_valid_session_id(session_id: Optional[str]) -> bool: """Validate that a session ID matches the expected 32-char lowercase hex format.""" if not session_id or not isinstance(session_id, str): return False return bool(SESSION_ID_PATTERN.match(session_id)) def create_session() -> Optional[str]: """Create a new MCP session and return the session ID, or None if at capacity.""" _ensure_cleanup_thread() # Use configurable maxsize for message queue to prevent memory exhaustion # In production this could be loaded from settings try: raw_val = get_setting_value('MCP_QUEUE_MAXSIZE') queue_maxsize = int(str(raw_val).strip()) # Treat non-positive values as default (1000) to avoid unbounded queue if queue_maxsize <= 0: queue_maxsize = 1000 except (ValueError, TypeError): mylog("none", ["[MCP] Invalid MCP_QUEUE_MAXSIZE, defaulting to 1000"]) queue_maxsize = 1000 session_id = uuid.uuid4().hex message_queue: queue.Queue = queue.Queue(maxsize=queue_maxsize) with _sessions_lock: _evict_expired_sessions_locked() if len(_mcp_sessions) >= MAX_ACTIVE_SESSIONS: mylog("minimal", [f"[MCP] Session limit reached ({MAX_ACTIVE_SESSIONS}). Rejecting new session."]) return None _mcp_sessions[session_id] = { "queue": message_queue, "created_at": time.time(), "last_activity": time.time(), "initialized": False } mylog("verbose", [f"[MCP] Created session: {session_id}"]) return session_id def get_session(session_id: str) -> Optional[Dict[str, Any]]: """Get a defensive copy of session data by ID, updating last activity.""" if not is_valid_session_id(session_id): return None with _sessions_lock: _evict_expired_sessions_locked() session = _mcp_sessions.get(session_id) if not session: return None session["last_activity"] = time.time() snapshot = deepcopy({k: v for k, v in session.items() if k != "queue"}) snapshot["queue"] = session["queue"] return snapshot def mark_session_initialized(session_id: str, protocol_version: Optional[str] = None) -> None: """Mark a session as initialized and record its negotiated protocol version.""" with _sessions_lock: session = _mcp_sessions.get(session_id) if session: session["initialized"] = True if protocol_version: session["protocol_version"] = protocol_version session["last_activity"] = time.time() def _get_session_protocol_version(session_id: str) -> Optional[str]: """Return the negotiated protocol version for an active session without mutating activity.""" with _sessions_lock: _evict_expired_sessions_locked() session = _mcp_sessions.get(session_id) if session: return session.get("protocol_version") return None def _is_session_active(session_id: str) -> bool: """Return True if the session still exists and has not expired (without mutating last_activity).""" with _sessions_lock: _evict_expired_sessions_locked() return session_id in _mcp_sessions def delete_session(session_id: str) -> bool: """Delete a live session by ID and signal any attached SSE stream to terminate.""" with _sessions_lock: _evict_expired_sessions_locked() sdata = _mcp_sessions.pop(session_id, None) if sdata is not None: if "queue" in sdata: _signal_session_closed(sdata["queue"]) mylog("verbose", [f"[MCP] Deleted session: {session_id}"]) return True return False _DEFAULT_ALLOWED_MCP_ORIGINS = ( "http://localhost:20211", "http://localhost:20212", "http://127.0.0.1:20211", "http://127.0.0.1:20212", ) def _get_allowed_mcp_origins() -> set: """Return explicit allowed Origin values for /mcp (never wildcard '*' or request Host).""" raw_origins = os.environ.get("CORS_ORIGINS", "") configured = { origin.strip().rstrip("/") for origin in raw_origins.split(",") if origin.strip() and origin.strip() != "*" and (origin.strip().startswith("http://") or origin.strip().startswith("https://")) } if configured: return configured return set(_DEFAULT_ALLOWED_MCP_ORIGINS) def _is_allowed_mcp_origin(origin: Optional[str]) -> bool: """Validate the HTTP Origin header per MCP Streamable HTTP transport requirements.""" if origin is None: return True normalized = origin.strip().rstrip("/") if not normalized: return False return normalized in _get_allowed_mcp_origins() # ============================================================================= # AUTHORIZATION # ============================================================================= def _safe_token_compare(candidate: str, expected: str) -> bool: """Constant-time token comparison that safely handles non-ASCII strings without raising.""" if not candidate: return False return secrets.compare_digest(candidate.encode("utf-8"), expected.encode("utf-8")) def check_auth(allow_test_mode: bool = True, min_token_len: int = 2) -> bool: """ Check if the request has valid authorization. Args: allow_test_mode: If True, permit the MCP_TEST_MODE bypass when API_TOKEN is unset. Shared non-MCP routes should pass allow_test_mode=False so they always fail closed. min_token_len: Minimum required API_TOKEN length (default 2 for MCP; 1 for legacy shared routes). Returns: bool: True if the Authorization header or query token matches the expected API token. """ raw_token = get_setting_value('API_TOKEN') raw_token_str = str(raw_token).strip() if raw_token is not None else "" # Fail closed if token is not set (empty, "None", or shorter than min_token_len) # Test mode bypass: MCP_TEST_MODE must be explicitly set and should NEVER # be enabled in production environments. This flag allows MCP tests to run # without a configured API_TOKEN. test_mode = allow_test_mode and os.getenv("MCP_TEST_MODE", "").lower() in ("1", "true", "yes") if not raw_token_str or raw_token_str == "None" or len(raw_token_str) < min_token_len: if test_mode: return True mylog("minimal", ["[MCP] CRITICAL: API_TOKEN is not configured or too short. Access denied."]) return False # Check Authorization header first (primary method) # SECURITY: Always prefer Authorization header over query string tokens auth_header = request.headers.get("Authorization", "").strip() parts = auth_header.split() header_token = parts[1] if len(parts) == 2 and parts[0].lower() == "bearer" else "" if _safe_token_compare(header_token, raw_token_str): return True # Fallback to query string token (for streaming clients that cannot set custom headers) # SECURITY WARNING: query_token in URL can be exposed in logs, history, or Referer headers. # NOTE: Never log or include query_token value in debug output. query_token = request.args.get("token", "").strip() return _safe_token_compare(query_token, raw_token_str) # ============================================================================= # OPENAPI SPEC GENERATION # ============================================================================= # Cached OpenAPI spec _openapi_spec_cache: Optional[Dict[str, Any]] = None _spec_cache_lock = threading.Lock() def get_openapi_spec(force_refresh: bool = False, servers: Optional[List[Dict[str, str]]] = None, flask_app: Optional[Any] = None) -> Dict[str, Any]: """ Get the OpenAPI specification, using cache when available. Args: force_refresh: If True, regenerate spec even if cached servers: Optional custom servers list flask_app: Optional Flask app for dynamic introspection Returns: OpenAPI specification dictionary """ global _openapi_spec_cache with _spec_cache_lock: # If custom servers are provided, we always regenerate or at least update the cached one if servers: spec = generate_openapi_spec(servers=servers, flask_app=flask_app) # We don't necessarily want to cache a prefixed version as the "main" one # if multiple prefixes are used, so we just return it. return spec if _openapi_spec_cache is None or force_refresh: try: _openapi_spec_cache = generate_openapi_spec(flask_app=flask_app) mylog("verbose", ["[MCP] Generated OpenAPI spec from registry"]) except Exception as e: mylog("none", [f"[MCP] Failed to generate OpenAPI spec: {e}"]) # Return minimal valid spec on error return { "openapi": "3.1.0", "info": {"title": "NetAlertX", "version": "2.0.0"}, "paths": {} } return _openapi_spec_cache def openapi_spec(): """ Flask route handler for OpenAPI spec endpoint. Returns: flask.Response: JSON response containing the OpenAPI spec. """ from flask import current_app mylog("verbose", ["[MCP] OpenAPI spec requested"]) # Detect base path from proxy headers # Nginx in this project often sets X-Forwarded-Prefix to /app prefix = request.headers.get('X-Forwarded-Prefix', '') # If the request came through /openapi.json without a prefix, use / as root. # If there is a valid relative prefix, include it in the servers list. servers = None if prefix and prefix.startswith("/") and not prefix.startswith("//"): servers = [{"url": prefix, "description": "Proxied server"}] spec = get_openapi_spec(servers=servers, flask_app=current_app) return jsonify(spec) # ============================================================================= # MCP TOOL MAPPING # ============================================================================= def map_openapi_to_mcp_tools(spec: Dict[str, Any]) -> List[Dict[str, Any]]: """ Convert OpenAPI specification into MCP tool definitions. This function transforms OpenAPI operations into MCP-compatible tool schemas, ensuring proper inputSchema derivation from request bodies and parameters. It deduplicates tools by their original operationId, preferring POST candidates over non-POST regardless of path and keeping the first candidate on a tie. Args: spec: OpenAPI specification dictionary Returns: List of MCP tool definitions with name, description, and inputSchema """ tools_map = {} if not spec or "paths" not in spec: return [] for path, methods in spec["paths"].items(): for method, details in methods.items(): if "operationId" not in details: continue operation_id = details["operationId"] # Deduplicate using the original operationId (before suffixing) # or the unique operationId as fallback. original_op_id = details.get("x-original-operationId", operation_id) # Build inputSchema from requestBody and parameters input_schema = { "type": "object", "properties": {}, "required": [] } # Extract properties from requestBody (POST/PUT/PATCH) if "requestBody" in details: content = details["requestBody"].get("content", {}) if "application/json" in content: body_schema = content["application/json"].get("schema", {}) # Copy properties and required fields if "properties" in body_schema: input_schema["properties"].update(body_schema["properties"]) if "required" in body_schema: input_schema["required"].extend(body_schema["required"]) # Handle $defs references (Pydantic nested models) if "$defs" in body_schema: input_schema["$defs"] = body_schema["$defs"] # Extract properties from parameters (path/query) for param in details.get("parameters", []): if "name" not in param: continue # Skip malformed parameters param_name = param["name"] param_schema = param.get("schema", {"type": "string"}) input_schema["properties"][param_name] = { "type": param_schema.get("type", "string"), "description": param.get("description", "") } # Add enum if present if "enum" in param_schema: input_schema["properties"][param_name]["enum"] = param_schema["enum"] # Add default if present if "default" in param_schema: input_schema["properties"][param_name]["default"] = param_schema["default"] if param.get("required", False) and param_name not in input_schema["required"]: input_schema["required"].append(param_name) if input_schema["required"]: input_schema["required"] = list(dict.fromkeys(input_schema["required"])) else: input_schema.pop("required", None) tool = { "name": original_op_id, "description": details.get("description", details.get("summary", "")), "inputSchema": input_schema, "_is_post": method.upper() == "POST" } # Preference logic for deduplication: # Prefer POST methods over GET for the same logic (usually more robust body validation). existing = tools_map.get(original_op_id) if not existing or (tool["_is_post"] and not existing["_is_post"]): tools_map[original_op_id] = tool final_tools = [] for tool in tools_map.values(): del tool["_is_post"] final_tools.append(tool) return final_tools def find_route_for_tool(tool_name: str) -> Optional[Dict[str, Any]]: """ Find the registered route for a given tool name (operationId). Handles exact matches and deduplicated original IDs. Args: tool_name: The operationId or original_operation_id to look up Returns: Route dictionary with path, method, and models, or None if not found """ registry = get_registry() original_candidates = [] exact_match = None for entry in registry: orig_id = entry.get("original_operation_id", entry["operation_id"]) if orig_id == tool_name: original_candidates.append(entry) elif entry["operation_id"] == tool_name and exact_match is None: exact_match = entry if original_candidates: # Apply the same POST-first preference as map_openapi_to_mcp_tools so a # published tool name always resolves to the route whose schema tools/list advertised. post_candidates = [c for c in original_candidates if c["method"].upper() == "POST"] if post_candidates: return post_candidates[0] return original_candidates[0] return exact_match # ============================================================================= # MCP REQUEST PROCESSING # ============================================================================= def _negotiate_protocol_version( client_version: Any, default_version: str = MCP_DEFAULT_STREAMABLE_HTTP_VERSION ) -> str: """Negotiate the MCP protocol version with the client.""" if isinstance(client_version, str) and client_version in SUPPORTED_PROTOCOL_VERSIONS: return client_version return default_version def _is_valid_jsonrpc_id(msg_id: Any) -> bool: """Return True if msg_id is a valid MCP request ID (string or integer, never null/bool/float/object/array).""" if isinstance(msg_id, bool): return False return isinstance(msg_id, (str, int)) def _is_valid_jsonrpc_envelope(item: Any) -> bool: """Return True if item has a valid JSON-RPC 2.0 request/notification envelope.""" if not isinstance(item, dict): return False method = item.get("method") if item.get("jsonrpc") != "2.0" or not isinstance(method, str) or not method: return False if "id" in item and not _is_valid_jsonrpc_id(item["id"]): return False return True def process_mcp_request( data: Dict[str, Any], session_id: Optional[str] = None, default_protocol_version: str = MCP_DEFAULT_STREAMABLE_HTTP_VERSION ) -> Optional[Dict[str, Any]]: """ Process an incoming MCP JSON-RPC request. Handles MCP protocol methods: - initialize: Protocol handshake - notifications/initialized: Initialization confirmation - tools/list: List available tools - tools/call: Execute a tool - resources/list: List available resources - prompts/list: List available prompts - ping: Keep-alive check Args: data: JSON-RPC request data session_id: Optional session identifier default_protocol_version: Fallback protocol version when client version is omitted or unknown Returns: JSON-RPC response dictionary, or None for notifications """ if not isinstance(data, dict): return _error_response(None, -32600, "Invalid Request: expected JSON object") if "id" in data and not _is_valid_jsonrpc_id(data["id"]): return _error_response(None, -32600, "Invalid Request: id must be a string, number, or null") method = data.get("method") is_notification = "id" not in data msg_id = data.get("id") if data.get("jsonrpc") != "2.0" or not isinstance(method, str) or not method: return _error_response(msg_id, -32600, "Invalid Request") params = data["params"] if "params" in data else {} if not isinstance(params, dict): if is_notification: return None return _error_response(msg_id, -32602, "Invalid params: expected object") mylog("debug", [f"[MCP] Processing request: method={method}, id={msg_id}"]) response = _dispatch_mcp_method( method, msg_id, params, session_id, default_protocol_version, is_notification=is_notification ) if is_notification: return None return response def _dispatch_mcp_method( method: str, msg_id: Any, params: Dict[str, Any], session_id: Optional[str], default_protocol_version: str, is_notification: bool = False, ) -> Optional[Dict[str, Any]]: """Dispatch a validated JSON-RPC method and return the response dictionary.""" # ------------------------------------------------------------------------- # initialize - Protocol handshake # ------------------------------------------------------------------------- if method == "initialize": negotiated_version = _negotiate_protocol_version( params.get("protocolVersion"), default_version=default_protocol_version ) # Mark session as initialized and record its negotiated protocol version if session_id: mark_session_initialized(session_id, protocol_version=negotiated_version) return { "jsonrpc": "2.0", "id": msg_id, "result": { "protocolVersion": negotiated_version, "capabilities": { "tools": {"listChanged": False}, "resources": {"subscribe": False, "listChanged": False}, "prompts": {"listChanged": False} }, "serverInfo": { "name": MCP_SERVER_NAME, "version": MCP_SERVER_VERSION } } } # ------------------------------------------------------------------------- # notifications/* - Only ID-less notifications are silently accepted # ------------------------------------------------------------------------- if is_notification and (method == "notifications/initialized" or method.startswith("notifications/")): return None # ------------------------------------------------------------------------- # tools/list - List available tools # ------------------------------------------------------------------------- if method == "tools/list": from flask import current_app spec = get_openapi_spec(flask_app=current_app) tools = map_openapi_to_mcp_tools(spec) return { "jsonrpc": "2.0", "id": msg_id, "result": { "tools": tools } } # ------------------------------------------------------------------------- # tools/call - Execute a tool # ------------------------------------------------------------------------- if method == "tools/call": tool_name = params.get("name") tool_args = params["arguments"] if "arguments" in params else {} if not tool_name: return _error_response(msg_id, -32602, "Missing tool name") if not isinstance(tool_args, dict): return _error_response(msg_id, -32602, "Invalid tool arguments: expected object") # Find the route for this tool route = find_route_for_tool(tool_name) if not route: return _error_response(msg_id, -32601, f"Tool '{tool_name}' not found") # Execute the tool via loopback HTTP call result = _execute_tool(route, tool_args) return { "jsonrpc": "2.0", "id": msg_id, "result": result } # ------------------------------------------------------------------------- # resources/list - List available resources # ------------------------------------------------------------------------- if method == "resources/list": resources = _list_resources() return { "jsonrpc": "2.0", "id": msg_id, "result": { "resources": resources } } # ------------------------------------------------------------------------- # resources/read - Read a resource # ------------------------------------------------------------------------- if method == "resources/read": uri = params.get("uri") if not uri: return _error_response(msg_id, -32602, "Missing resource URI") content = _read_resource(uri) return { "jsonrpc": "2.0", "id": msg_id, "result": { "contents": content } } # ------------------------------------------------------------------------- # prompts/list - List available prompts # ------------------------------------------------------------------------- if method == "prompts/list": prompts = _list_prompts() return { "jsonrpc": "2.0", "id": msg_id, "result": { "prompts": prompts } } # ------------------------------------------------------------------------- # prompts/get - Get a specific prompt # ------------------------------------------------------------------------- if method == "prompts/get": prompt_name = params.get("name") prompt_args = params.get("arguments", {}) if not prompt_name: return _error_response(msg_id, -32602, "Missing prompt name") prompt_result = _get_prompt(prompt_name, prompt_args) return { "jsonrpc": "2.0", "id": msg_id, "result": prompt_result } # ------------------------------------------------------------------------- # ping - Keep-alive # ------------------------------------------------------------------------- if method == "ping": return { "jsonrpc": "2.0", "id": msg_id, "result": {} } # ------------------------------------------------------------------------- # Unknown method # ------------------------------------------------------------------------- return _error_response(msg_id, -32601, f"Method '{method}' not found") return None def _error_response(msg_id: Any, code: int, message: str) -> Dict[str, Any]: """Create a JSON-RPC error response.""" return { "jsonrpc": "2.0", "id": msg_id, "error": { "code": code, "message": message } } def _execute_tool(route: Dict[str, Any], args: Dict[str, Any]) -> Dict[str, Any]: """ Execute a tool by making a loopback HTTP call to the internal API. Args: route: Route definition from registry args: Tool arguments Returns: MCP tool result with content and isError flag """ path = route["path"] method = route["method"] # Substitute path parameters for key, value in args.items(): placeholder = f"{{{key}}}" if placeholder in path: encoded_value = quote(str(value), safe="") path = path.replace(placeholder, encoded_value) # Check if tool is disabled if is_tool_disabled(route['operation_id']): return { "content": [{"type": "text", "text": f"Error: Tool '{route['operation_id']}' is disabled"}], "isError": True } # Build request port = get_setting_value('GRAPHQL_PORT') if not port: return { "content": [{"type": "text", "text": "Error: GRAPHQL_PORT not configured"}], "isError": True } api_base_url = f"http://localhost:{port}" url = f"{api_base_url}{path}" headers = {"Content-Type": "application/json"} if "Authorization" in request.headers: headers["Authorization"] = request.headers["Authorization"] else: # Propagate query token or fallback to configured API token for internal loopback token = request.args.get("token") or get_setting_value('API_TOKEN') if token: headers["Authorization"] = f"Bearer {token}" non_path_args = {k: v for k, v in args.items() if f"{{{k}}}" not in route['path']} try: # Validate input if request model exists request_model = route.get("request_model") if request_model and method in ("POST", "PUT", "PATCH"): try: # Validate args against Pydantic model request_model(**non_path_args) except ValidationError as e: return { "content": [{ "type": "text", "text": json.dumps({ "success": False, "error": "Validation error", "details": e.errors() }, indent=2) }], "isError": True } # Make the HTTP request if method == "POST": api_response = requests.post(url, json=non_path_args, headers=headers, timeout=60) elif method == "PUT": api_response = requests.put(url, json=non_path_args, headers=headers, timeout=60) elif method == "PATCH": api_response = requests.patch(url, json=non_path_args, headers=headers, timeout=60) elif method == "DELETE": api_response = requests.delete(url, headers=headers, params=non_path_args, json=non_path_args, timeout=60) else: # GET api_response = requests.get(url, params=non_path_args, headers=headers, timeout=60) # Parse response content = [] try: json_content = api_response.json() content.append({ "type": "text", "text": json.dumps(json_content, indent=2) }) except (json.JSONDecodeError, ValueError): # Fallback for endpoints that return plain text instead of JSON (e.g., /metrics) content.append({ "type": "text", "text": api_response.text }) is_error = api_response.status_code >= 400 return { "content": content, "isError": is_error } except requests.Timeout: return { "content": [{"type": "text", "text": "Request timed out"}], "isError": True } except Exception as e: mylog("none", [f"[MCP] Error executing tool {route['operation_id']}: {e}"]) return { "content": [{"type": "text", "text": "Error: Tool execution failed"}], "isError": True } # ============================================================================= # MCP RESOURCES # ============================================================================= def get_log_dir() -> str: """Get the log directory from environment or settings.""" log_dir = os.getenv("NETALERTX_LOG") if not log_dir: # Fallback to setting value if environment variable is not set log_dir = get_setting_value("NETALERTX_LOG") if not log_dir: # If still not set, we return an empty string to indicate missing config # rather than hardcoding /tmp/log return "" return log_dir def _list_resources() -> List[Dict[str, Any]]: """List available MCP resources (read-only data like logs and API spec).""" resources = [] # API Specification resources.append({ "uri": "netalertx://api/openapi.json", "name": "OpenAPI Specification", "description": "The full OpenAPI 3.1 specification for the NetAlertX API and MCP tools", "mimeType": "application/json" }) log_dir = get_log_dir() if not log_dir: return resources # Log files log_files = [ ("app.log", "Backend log"), ("stderr.log", "Backend stderr log"), ("app_front.log", "Frontend commands log"), ("app.php_errors.log", "PHP errors log") ] for filename, description in log_files: log_path = os.path.join(log_dir, filename) if os.path.exists(log_path): resources.append({ "uri": f"netalertx://logs/{filename}", "name": filename, "description": description, "mimeType": "text/plain" }) # Plugin logs plugin_log_dir = os.path.join(log_dir, "plugins") if os.path.exists(plugin_log_dir): try: for filename in os.listdir(plugin_log_dir): if filename.endswith(".log"): resources.append({ "uri": f"netalertx://logs/plugins/{filename}", "name": f"plugins/{filename}", "description": f"Plugin log: {filename}", "mimeType": "text/plain" }) except OSError as e: # Handle permission errors or other filesystem issues gracefully mylog("none", [f"[MCP] Error listing plugin_log_dir ({plugin_log_dir}): {e}"]) return resources def _read_resource(uri: str) -> List[Dict[str, Any]]: """Read a resource by URI.""" # Handle API Specification if uri == "netalertx://api/openapi.json": from flask import current_app spec = get_openapi_spec(flask_app=current_app) return [{ "uri": uri, "mimeType": "application/json", "text": json.dumps(spec, indent=2) }] log_dir = get_log_dir() if not log_dir: return [{"uri": uri, "text": "Error: NETALERTX_LOG directory not configured"}] if uri.startswith("netalertx://logs/"): relative_path = uri.replace("netalertx://logs/", "") file_path = os.path.join(log_dir, relative_path) # Security: ensure path is within log directory real_log_dir = os.path.realpath(log_dir) real_path = os.path.realpath(file_path) if not (real_path.startswith(real_log_dir + os.sep) or real_path == real_log_dir): return [{"uri": uri, "text": "Access denied: path outside log directory"}] if os.path.exists(real_path): try: # Stream the file and retain only the last 500 lines with open(real_path, "r", encoding="utf-8", errors="replace") as f: last_lines = deque(f, maxlen=500) return [{ "uri": uri, "mimeType": "text/plain", "text": "".join(last_lines) }] except Exception as e: mylog("none", [f"[MCP] Error reading resource {uri}: {e}"]) return [{"uri": uri, "text": "Error reading file"}] return [{"uri": uri, "text": "File not found"}] return [{"uri": uri, "text": "Unknown resource type"}] # ============================================================================= # MCP PROMPTS # ============================================================================= def _list_prompts() -> List[Dict[str, Any]]: """List available MCP prompts (curated interactions).""" return [ { "name": "analyze_network_health", "description": "Analyze overall network health including device status, recent alerts, and connectivity issues", "arguments": [] }, { "name": "investigate_device", "description": "Investigate a specific device's status, history, and potential issues", "arguments": [ { "name": "device_identifier", "description": "MAC address, IP, or device name to investigate", "required": True } ] }, { "name": "troubleshoot_connectivity", "description": "Help troubleshoot connectivity issues for a device", "arguments": [ { "name": "target_ip", "description": "IP address experiencing connectivity issues", "required": True } ] } ] def _get_prompt(name: str, args: Dict[str, Any]) -> Dict[str, Any]: """Get a specific prompt with its content.""" if name == "analyze_network_health": return { "description": "Network health analysis", "messages": [ { "role": "user", "content": { "type": "text", "text": ( "Please analyze the network health by:\n" "1. Getting device totals to see overall status\n" "2. Checking recent events for any alerts\n" "3. Looking at network topology for connectivity\n" "Summarize findings and highlight any concerns." ) } } ] } elif name == "investigate_device": device_id = args.get("device_identifier", "") return { "description": f"Investigation of device: {device_id}", "messages": [ { "role": "user", "content": { "type": "text", "text": ( f"Please investigate the device '{device_id}' by:\n" f"1. Search for the device to get its details\n" f"2. Check any recent events for this device\n" f"3. Check open ports if available\n" "Provide a summary of the device's status and any notable findings." ) } } ] } elif name == "troubleshoot_connectivity": target_ip = args.get("target_ip", "") return { "description": f"Connectivity troubleshooting for: {target_ip}", "messages": [ { "role": "user", "content": { "type": "text", "text": ( f"Please help troubleshoot connectivity to '{target_ip}' by:\n" f"1. Run a traceroute to identify network hops\n" f"2. Search for the device by IP to get its info\n" f"3. Check recent events for connection issues\n" "Provide analysis of the network path and potential issues." ) } } ] } return { "description": "Unknown prompt", "messages": [] } # ============================================================================= # FLASK ROUTE HANDLERS # ============================================================================= def _reject_non_json_constant(value: str) -> None: """Reject non-standard JSON numeric literals such as NaN, Infinity, and -Infinity.""" raise ValueError(f"Invalid JSON numeric constant: {value}") def _accepts_event_stream(accept_header: str) -> bool: """ Parse an HTTP Accept header and return True iff text/event-stream has positive quality. Respects RFC 9110 specificity ordering: text/event-stream > text/* > */*. An absent or empty Accept header is treated as accepting any media type. """ if not accept_header or not accept_header.strip(): return True best_rank = (0, -1) best_q = -1.0 for raw_range in accept_header.split(","): part = raw_range.strip() if not part: continue segments = [seg.strip() for seg in part.split(";")] media_type = segments[0].lower() if media_type == "text/event-stream": spec = 3 elif media_type == "text/*": spec = 2 elif media_type == "*/*": spec = 1 else: continue q_val = 1.0 charset_mismatch = False media_param_count = 0 for param in segments[1:]: if "=" in param: k, v = param.split("=", 1) key = k.strip().lower() val = v.strip().strip('"').lower() if key == "q": try: q_val = float(val) except ValueError: q_val = 0.0 break media_param_count += 1 if key == "charset" and val not in ("utf-8", "utf8"): charset_mismatch = True if charset_mismatch: continue rank = (spec, media_param_count) if rank > best_rank or (rank == best_rank and q_val > best_q): best_rank = rank best_q = q_val return best_rank[0] > 0 and best_q > 0.0 def _read_bounded_body() -> Tuple[Optional[bytes], bool]: """ Read the incoming HTTP request body without exceeding MAX_MCP_BODY_BYTES. Returns: Tuple of (raw_bytes, too_large). When too_large is True, raw_bytes is None and the stream was never buffered beyond MAX_MCP_BODY_BYTES + 1 bytes. """ content_length = request.content_length if content_length is not None and content_length > MAX_MCP_BODY_BYTES: return None, True raw_bytes = request.stream.read(MAX_MCP_BODY_BYTES + 1) if len(raw_bytes) > MAX_MCP_BODY_BYTES: return None, True return raw_bytes, False def _handle_initialize_request( item: Dict[str, Any], session_id: Optional[str], effective_proto_version: str, base_headers: Dict[str, str], as_batch: bool = False, ): """Create a new MCP session and process a JSON-RPC initialize request.""" msg_id = item.get("id") if session_id is not None: return jsonify(_error_response(msg_id, -32600, "Cannot supply Mcp-Session-Id on initialize")), 400, base_headers new_session_id = create_session() if not new_session_id: return jsonify(_error_response(msg_id, -32000, "Server busy: maximum active MCP sessions reached")), 503, base_headers try: response_data = process_mcp_request(item, new_session_id, default_protocol_version=effective_proto_version) except Exception as e: delete_session(new_session_id) mylog("none", [f"[MCP] Initialize error: {e}"]) return jsonify(_error_response(msg_id, -32603, "Internal server error")), 500, base_headers if response_data is None: delete_session(new_session_id) return Response("", status=202, headers=base_headers) if "error" in response_data: delete_session(new_session_id) body = [response_data] if as_batch else response_data return jsonify(body), 200, base_headers negotiated = response_data.get("result", {}).get("protocolVersion", effective_proto_version) resp_headers = { "Mcp-Session-Id": new_session_id, "MCP-Protocol-Version": negotiated, } body = [response_data] if as_batch else response_data return jsonify(body), 200, resp_headers def mcp_streamable_http(): """ Handle MCP Streamable HTTP endpoint (MCP 2025-03-26 / 2025-06-18). Supports: - POST /mcp: JSON-RPC 2.0 requests, notifications, and batch arrays - GET /mcp: Standalone SSE stream for server-initiated messages - DELETE /mcp: Explicit session termination via Mcp-Session-Id header - OPTIONS /mcp: CORS preflight """ if not _is_allowed_mcp_origin(request.headers.get("Origin")): return jsonify(_error_response(None, -32600, "Forbidden: Origin not allowed")), 403 if request.method == "OPTIONS": return jsonify({"success": True}), 200 if not check_auth(): return jsonify({"success": False, "error": "Unauthorized"}), 401 # Validate MCP-Protocol-Version header when provided by client header_proto_version = request.headers.get("MCP-Protocol-Version") if header_proto_version is not None: header_proto_version = header_proto_version.strip() if header_proto_version not in SUPPORTED_PROTOCOL_VERSIONS: return jsonify( _error_response( None, -32600, f"Unsupported MCP-Protocol-Version '{header_proto_version}'. " f"Supported: {', '.join(SUPPORTED_PROTOCOL_VERSIONS)}" ) ), 400 # Validate Mcp-Session-Id header format if supplied session_id = request.headers.get("Mcp-Session-Id") if session_id is not None: session_id = session_id.strip() if not is_valid_session_id(session_id): fallback_version = header_proto_version or MCP_DEFAULT_STREAMABLE_HTTP_VERSION return jsonify(_error_response(None, -32600, "Invalid Mcp-Session-Id header")), 400, { "MCP-Protocol-Version": fallback_version } session_proto_version = _get_session_protocol_version(session_id) if session_id else None if session_proto_version and header_proto_version and header_proto_version != session_proto_version: return jsonify( _error_response( None, -32600, f"MCP-Protocol-Version '{header_proto_version}' does not match session's negotiated version '{session_proto_version}'", ) ), 400, {"MCP-Protocol-Version": session_proto_version} effective_proto_version = header_proto_version or session_proto_version or MCP_DEFAULT_STREAMABLE_HTTP_VERSION base_headers = {"MCP-Protocol-Version": effective_proto_version} # ------------------------------------------------------------------------- # DELETE /mcp - Explicit session termination # ------------------------------------------------------------------------- if request.method == "DELETE": if not session_id: return jsonify(_error_response(None, -32600, "Missing Mcp-Session-Id header")), 400, base_headers if not delete_session(session_id): return jsonify(_error_response(None, -32001, "Session not found or expired")), 404, base_headers return jsonify({"success": True, "status": "terminated"}), 200, base_headers # ------------------------------------------------------------------------- # GET /mcp - Standalone SSE stream for server-to-client messages # ------------------------------------------------------------------------- if request.method == "GET": accept_header = request.headers.get("Accept", "") if not _accepts_event_stream(accept_header): return jsonify(_error_response(None, -32600, "Accept header must include text/event-stream")), 406, base_headers # Check supplied session liveness before returning stream capacity errors so # terminated/expired sessions always receive 404 even when stream slots are full. if session_id and not _is_session_active(session_id): return jsonify(_error_response(None, -32001, "Session not found or expired")), 404, base_headers if not _acquire_sse_stream_slot(): return jsonify(_error_response(None, -32000, "Server busy: maximum active SSE streams reached")), 503, base_headers slot_released = False def _release_once() -> None: nonlocal slot_released if not slot_released: slot_released = True _release_sse_stream_slot() ephemeral_session = False active_session_id: Optional[str] = None try: if session_id: session = get_session(session_id) if not session: _release_once() return jsonify(_error_response(None, -32001, "Session not found or expired")), 404, base_headers active_session_id = session_id else: active_session_id = create_session() if not active_session_id: _release_once() return jsonify(_error_response(None, -32000, "Server busy: maximum active MCP sessions reached")), 503, base_headers session = get_session(active_session_id) if not session: delete_session(active_session_id) _release_once() return jsonify(_error_response(None, -32603, "Failed to initialize MCP session")), 500, base_headers ephemeral_session = True message_queue = session["queue"] def stream(): """Generator for standalone Streamable HTTP SSE stream (no legacy endpoint event).""" try: if message_queue.empty(): yield ": keep-alive\n\n" while _is_session_active(active_session_id): try: message = message_queue.get(timeout=SSE_KEEPALIVE_INTERVAL) if message is _SESSION_CLOSED: break yield f"event: message\ndata: {json.dumps(message)}\n\n" except queue.Empty: if not _is_session_active(active_session_id): break yield ": keep-alive\n\n" finally: if ephemeral_session: delete_session(active_session_id) _release_once() stream_headers = { "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no", "MCP-Protocol-Version": effective_proto_version, "Mcp-Session-Id": active_session_id, } resp = Response( stream_with_context(stream()), mimetype="text/event-stream", headers=stream_headers, ) resp.call_on_close(_release_once) return resp except Exception: if ephemeral_session and active_session_id: delete_session(active_session_id) _release_once() raise # ------------------------------------------------------------------------- # Only POST reaches the JSON-RPC body parser (e.g. HEAD returns 405) # ------------------------------------------------------------------------- if request.method != "POST": return Response("", status=405, headers={**base_headers, "Allow": "GET, POST, DELETE, OPTIONS"}) # ------------------------------------------------------------------------- # POST /mcp - JSON-RPC requests, notifications, and batches # ------------------------------------------------------------------------- raw_body, too_large = _read_bounded_body() if too_large or raw_body is None: return jsonify(_error_response(None, -32600, "Payload Too Large")), 413, base_headers try: data = json.loads(raw_body.decode("utf-8"), parse_constant=_reject_non_json_constant) except Exception: return jsonify(_error_response(None, -32700, "Parse error: invalid JSON")), 400, base_headers if data is None or not isinstance(data, (dict, list)): return jsonify(_error_response(None, -32600, "Invalid Request")), 400, base_headers # Handle JSON-RPC Batch (supported in 2025-03-26 and 2024-11-05; removed in 2025-06-18) if isinstance(data, list): if effective_proto_version == "2025-06-18": return jsonify( _error_response( None, -32600, "JSON-RPC batching is not supported in MCP protocol version 2025-06-18", ) ), 400, base_headers if len(data) == 0 or len(data) > MAX_BATCH_SIZE: return jsonify(_error_response(None, -32600, f"Invalid batch size (must be 1..{MAX_BATCH_SIZE})")), 400, base_headers for item in data: if ( _is_valid_jsonrpc_envelope(item) and "id" in item and item.get("method") == "initialize" and len(data) > 1 ): return jsonify(_error_response(item.get("id"), -32600, "initialize cannot be combined in a batch")), 400, base_headers # Check if single-element batch is a valid initialize request (must have an id) if ( len(data) == 1 and _is_valid_jsonrpc_envelope(data[0]) and "id" in data[0] and data[0].get("method") == "initialize" ): return _handle_initialize_request( data[0], session_id, effective_proto_version, base_headers, as_batch=True ) if session_id: session = get_session(session_id) if not session: all_notifications = all( _is_valid_jsonrpc_envelope(item) and "id" not in item for item in data ) if all_notifications: return Response("", status=404, headers=base_headers) return jsonify(_error_response(None, -32001, "Session not found or expired")), 404, base_headers responses = [] for item in data: if not _is_valid_jsonrpc_envelope(item): raw_id = item.get("id") if isinstance(item, dict) else None item_id = raw_id if _is_valid_jsonrpc_id(raw_id) else None responses.append(_error_response(item_id, -32600, "Invalid Request")) continue # ID-less initialize notification is invalid; ignore without allocating a session or aborting siblings if item.get("method") == "initialize" and "id" not in item: continue try: res = process_mcp_request(item, session_id, default_protocol_version=effective_proto_version) if res is not None: responses.append(res) except Exception as e: mylog("none", [f"[MCP] Batch item processing error: {e}"]) if "id" in item: responses.append(_error_response(item.get("id"), -32603, "Internal server error")) resp_headers = dict(base_headers) if session_id: resp_headers["Mcp-Session-Id"] = session_id if not responses: return Response("", status=202, headers=resp_headers) return jsonify(responses), 200, resp_headers # Single JSON-RPC object if not _is_valid_jsonrpc_envelope(data): raw_id = data.get("id") safe_id = raw_id if _is_valid_jsonrpc_id(raw_id) else None return jsonify(_error_response(safe_id, -32600, "Invalid Request")), 400, base_headers method = data["method"] msg_id = data.get("id") is_notification = "id" not in data if method == "initialize": if is_notification: return Response("", status=400, headers=base_headers) return _handle_initialize_request( data, session_id, effective_proto_version, base_headers, as_batch=False ) # Non-initialize request or notification if session_id is not None: session = get_session(session_id) if not session: if is_notification: return Response("", status=404, headers=base_headers) return jsonify(_error_response(msg_id, -32001, "Session not found or expired")), 404, base_headers try: response_data = process_mcp_request(data, session_id, default_protocol_version=effective_proto_version) except Exception as e: mylog("none", [f"[MCP] POST /mcp processing error: {e}"]) if is_notification: return Response("", status=500, headers=base_headers) return jsonify(_error_response(msg_id, -32603, "Internal server error")), 500, base_headers resp_headers = dict(base_headers) if session_id: resp_headers["Mcp-Session-Id"] = session_id if response_data is None: return Response("", status=202, headers=resp_headers) return jsonify(response_data), 200, resp_headers