"""Data models, config parsing, secret masking, and schema sanitization for MCP connectors.""" from __future__ import annotations import copy import hashlib import os import re from typing import Any, Literal, Optional from urllib.parse import urlparse from pydantic import BaseModel, Field, field_validator, model_validator TransportType = Literal["auto", "streamable_http", "sse", "stdio"] AuthType = Literal[ "none", "bearer", "api_key", "basic", "headers", "oauth2_client_credentials", "oauth2_pkce", "oauth2_device", "oauth2_refresh_token", ] ConnectorStatus = Literal[ "disconnected", "connecting", "connected", "auth_required", "disabled", "error", ] _ENV_VAR_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-(.*?))?\}") _SLUG_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$") _SAFE_IDENT_RE = re.compile(r"[^a-zA-Z0-9_-]+") # JSON Schema keywords not supported by google-genai FunctionDeclaration `parameters` _UNSUPPORTED_SCHEMA_KEYS = frozenset( { "$schema", "$id", "$defs", "$ref", "$comment", "definitions", "additionalProperties", "patternProperties", "propertyNames", "examples", "default", "title", "exclusiveMinimum", "exclusiveMaximum", "readOnly", "writeOnly", "deprecated", "contentEncoding", "contentMediaType", "minContains", "maxContains", "dependentRequired", "dependentSchemas", "if", "then", "else", "not", "allOf", "oneOf", } ) def expand_env_vars(value: Any) -> Any: """Recursively expand `${VAR}` and `${VAR:-default}` using current environment variables.""" if isinstance(value, str): def _replace(match: re.Match[str]) -> str: var_name = match.group(1) default_val = match.group(2) env_val = os.environ.get(var_name) if env_val is not None: return env_val if default_val is not None: return default_val return match.group(0) return _ENV_VAR_RE.sub(_replace, value) if isinstance(value, dict): return {k: expand_env_vars(v) for k, v in value.items()} if isinstance(value, list): return [expand_env_vars(item) for item in value] return value def is_loopback_url(url: Optional[str]) -> bool: """Return True if URL targets localhost/loopback (so HTTP_PROXY should be bypassed).""" if not url: return False host = (urlparse(url).hostname or "").lower() return host in ("localhost", "127.0.0.1", "::1") or host.endswith(".localhost") def mask_secret(value: Optional[str]) -> str: """Mask a secret value for safe display in Telegram UI and logs.""" if not value: return "не задан" s = value.strip() if s.startswith("${") and s.endswith("}"): return f"`{s}` (env)" if len(s) <= 8: return "••••••••" return f"{s[:4]}••••{s[-4:]}" def normalize_connector_name(name: str) -> str: """Normalize and validate an MCP connector slug.""" cleaned = name.strip().lower().replace(" ", "_") cleaned = _SAFE_IDENT_RE.sub("_", cleaned).strip("_-") if not cleaned: raise ValueError("Имя коннектора не может быть пустым.") if len(cleaned) > 48: cleaned = cleaned[:48].rstrip("_-") if not _SLUG_RE.match(cleaned): raise ValueError( f"Некорректное имя коннектора '{name}'. Используйте латинские буквы, цифры, '-' или '_'." ) return cleaned def sanitize_tool_name( connector_name: str, remote_name: str, *, tool_prefix: Optional[str] = None, existing_names: Optional[set[str]] = None, ) -> str: """Build a valid LLM function name (<= 64 chars, `[a-zA-Z0-9_-]`) for an MCP tool.""" prefix = (tool_prefix or f"mcp_{connector_name}").strip() prefix = _SAFE_IDENT_RE.sub("_", prefix).strip("_") if not prefix or not prefix[0].isalpha(): prefix = f"mcp_{prefix}" if prefix else "mcp" clean_remote = _SAFE_IDENT_RE.sub("_", remote_name.strip()).strip("_") or "tool" candidate = f"{prefix}_{clean_remote}" if len(candidate) > 64: digest = hashlib.sha256(f"{connector_name}:{remote_name}".encode("utf-8")).hexdigest()[:6] max_base = 64 - 1 - len(digest) candidate = f"{candidate[:max_base].rstrip('_')}_{digest}" if existing_names is not None and candidate in existing_names: idx = 2 while True: suffix = f"_{idx}" base = candidate[: 64 - len(suffix)].rstrip("_") alt = f"{base}{suffix}" if alt not in existing_names: candidate = alt break idx += 1 return candidate def _resolve_ref(ref: str, root: dict[str, Any]) -> Optional[dict[str, Any]]: """Resolve a local JSON pointer `$ref` such as `#/$defs/Filter`.""" if not ref.startswith("#/"): return None parts = ref[2:].split("/") current: Any = root for part in parts: part = part.replace("~1", "/").replace("~0", "~") if isinstance(current, dict) and part in current: current = current[part] else: return None return copy.deepcopy(current) if isinstance(current, dict) else None def _sanitize_schema_node( node: Any, root: dict[str, Any], seen_refs: frozenset[str] = frozenset(), ) -> dict[str, Any]: if not isinstance(node, dict): return {"type": "string"} # Resolve $ref if present ref = node.get("$ref") if isinstance(ref, str) and ref not in seen_refs: resolved = _resolve_ref(ref, root) if resolved is not None: merged = {**resolved, **{k: v for k, v in node.items() if k != "$ref"}} return _sanitize_schema_node(merged, root, seen_refs | {ref}) # Simplify anyOf / oneOf with null into nullable type for union_key in ("anyOf", "oneOf"): variants = node.get(union_key) if isinstance(variants, list) and variants: non_null = [v for v in variants if not (isinstance(v, dict) and v.get("type") == "null")] has_null = len(non_null) < len(variants) if len(non_null) == 1 and isinstance(non_null[0], dict): merged = dict(non_null[0]) if "description" in node and "description" not in merged: merged["description"] = node["description"] sanitized = _sanitize_schema_node(merged, root, seen_refs) if has_null: sanitized["nullable"] = True return sanitized if non_null and isinstance(non_null[0], dict): # Keep Gemini-compatible anyOf if simple, or collapse to first non-null type merged = dict(non_null[0]) if "description" in node and "description" not in merged: merged["description"] = node["description"] sanitized = _sanitize_schema_node(merged, root, seen_refs) if has_null: sanitized["nullable"] = True return sanitized cleaned: dict[str, Any] = {} # Handle type arrays such as ["string", "null"] raw_type = node.get("type") if isinstance(raw_type, list): non_null_types = [t for t in raw_type if isinstance(t, str) and t != "null"] has_null = "null" in raw_type cleaned["type"] = non_null_types[0] if non_null_types else "string" if has_null: cleaned["nullable"] = True elif isinstance(raw_type, str) and raw_type != "null": cleaned["type"] = raw_type # Convert const -> enum if "const" in node and "enum" not in node: const_val = node["const"] if isinstance(const_val, (str, int, float, bool)): cleaned["enum"] = [str(const_val)] if cleaned.get("type") == "string" else [const_val] cleaned.setdefault("type", "string") for key, value in node.items(): if key in _UNSUPPORTED_SCHEMA_KEYS or key in ("type", "const", "anyOf"): continue if key == "properties" and isinstance(value, dict): cleaned["properties"] = { str(prop_name): _sanitize_schema_node(prop_schema, root, seen_refs) for prop_name, prop_schema in value.items() } elif key == "items": if isinstance(value, dict): cleaned["items"] = _sanitize_schema_node(value, root, seen_refs) elif isinstance(value, list) and value: cleaned["items"] = _sanitize_schema_node(value[0], root, seen_refs) else: cleaned["items"] = {"type": "string"} elif key == "required" and isinstance(value, list): cleaned["required"] = [str(item) for item in value if isinstance(item, str)] elif key == "enum" and isinstance(value, list): cleaned["enum"] = value elif key in ("description", "format", "nullable", "minimum", "maximum", "minItems", "maxItems", "minLength", "maxLength", "pattern"): cleaned[key] = value if "type" not in cleaned: if "properties" in cleaned: cleaned["type"] = "object" elif "items" in cleaned: cleaned["type"] = "array" else: cleaned["type"] = "string" if cleaned["type"] == "object": cleaned.setdefault("properties", {}) if "required" in cleaned: props = cleaned["properties"] valid_req = [r for r in cleaned["required"] if r in props] if valid_req: cleaned["required"] = valid_req else: del cleaned["required"] elif cleaned["type"] == "array": cleaned.setdefault("items", {"type": "string"}) return cleaned def sanitize_mcp_input_schema(schema: Any) -> dict[str, Any]: """Convert an arbitrary MCP JSON Schema into a clean schema compatible with Gemini, OpenAI, and MCPToolBridge.""" if not isinstance(schema, dict): return {"type": "object", "properties": {}} sanitized = _sanitize_schema_node(schema, schema) if sanitized.get("type") != "object": return {"type": "object", "properties": {}} sanitized.setdefault("properties", {}) return sanitized class MCPAuthConfig(BaseModel): """Authentication configuration supporting static, custom header, and OAuth 2.x MCP flows.""" type: AuthType = "none" # Bearer token token: Optional[str] = None token_prefix: str = "Bearer" # API Key (header or query) api_key: Optional[str] = None api_key_in: Literal["header", "query"] = "header" header_name: str = "X-API-Key" query_param: str = "api_key" api_key_prefix: str = "" # HTTP Basic username: Optional[str] = None password: Optional[str] = None # Custom static headers headers: dict[str, str] = Field(default_factory=dict) # OAuth 2.0 / 2.1 fields client_id: Optional[str] = None client_secret: Optional[str] = None authorization_url: Optional[str] = None token_url: Optional[str] = None device_authorization_url: Optional[str] = None registration_url: Optional[str] = None redirect_uri: Optional[str] = None scope: Optional[str] = None audience: Optional[str] = None resource: Optional[str] = None refresh_token: Optional[str] = None client_auth_method: Literal["post", "basic"] = "post" extra_token_params: dict[str, str] = Field(default_factory=dict) def resolved(self) -> MCPAuthConfig: """Return a copy with `${ENV_VAR}` placeholders expanded from os.environ.""" expanded = expand_env_vars(self.model_dump()) return MCPAuthConfig.model_validate(expanded) def summary(self) -> str: """Human-readable summary with all secrets masked.""" if self.type == "none": return "none (без авторизации)" if self.type == "bearer": return f"bearer ({self.token_prefix} {mask_secret(self.token)})" if self.type == "api_key": loc = f"header `{self.header_name}`" if self.api_key_in == "header" else f"query `{self.query_param}`" return f"api_key ({loc}: {mask_secret(self.api_key)})" if self.type == "basic": return f"basic (user: `{self.username or '?'}`, pass: {mask_secret(self.password)})" if self.type == "headers": keys = ", ".join(f"`{k}`" for k in self.headers.keys()) or "нет" return f"headers ({keys})" if self.type == "oauth2_client_credentials": return f"oauth2_client_credentials (client_id: `{self.client_id or '?'}`)" if self.type == "oauth2_pkce": cid = self.client_id or "auto/DCR" return f"oauth2_pkce (client_id: `{cid}`)" if self.type == "oauth2_device": return f"oauth2_device (client_id: `{self.client_id or '?'}`)" if self.type == "oauth2_refresh_token": return f"oauth2_refresh_token (token: {mask_secret(self.refresh_token)})" return str(self.type) class MCPConnectorConfig(BaseModel): """Configuration for a single external MCP connector.""" name: str transport: TransportType = "auto" enabled: bool = True # Remote transports (streamable_http / sse / auto) url: Optional[str] = None headers: dict[str, str] = Field(default_factory=dict) # Local stdio transport command: Optional[str] = None args: list[str] = Field(default_factory=list) env: dict[str, str] = Field(default_factory=dict) cwd: Optional[str] = None # Authentication auth: MCPAuthConfig = Field(default_factory=MCPAuthConfig) # Tool exposure controls tool_prefix: Optional[str] = None include_tools: list[str] = Field(default_factory=list) exclude_tools: list[str] = Field(default_factory=list) # Connection options timeout_seconds: int = Field(default=60, ge=5, le=600) verify_ssl: bool = True source: Literal["config", "bot"] = "config" @field_validator("name", mode="before") @classmethod def _validate_name(cls, v: Any) -> str: return normalize_connector_name(str(v)) @model_validator(mode="after") def _validate_transport_fields(self) -> MCPConnectorConfig: if self.transport == "auto": if self.command and not self.url: self.transport = "stdio" if self.transport == "stdio": if not self.command: raise ValueError(f"Коннектор '{self.name}' с транспортом 'stdio' требует поле 'command'.") else: if not self.url: raise ValueError( f"Коннектор '{self.name}' с транспортом '{self.transport}' требует поле 'url'." ) return self def resolved(self) -> MCPConnectorConfig: """Return a copy with `${ENV_VAR}` placeholders expanded from os.environ.""" expanded = expand_env_vars(self.model_dump()) return MCPConnectorConfig.model_validate(expanded) class MCPToolInfo(BaseModel): """Metadata about a tool discovered from an MCP server.""" remote_name: str registered_name: str description: str = "" input_schema: dict[str, Any] = Field(default_factory=lambda: {"type": "object", "properties": {}}) class MCPConnectorState(BaseModel): """Runtime status and discovered tools for an MCP connector.""" config: MCPConnectorConfig status: ConnectorStatus = "disconnected" resolved_transport: Optional[str] = None server_info: dict[str, Any] = Field(default_factory=dict) protocol_version: Optional[str] = None tools: list[MCPToolInfo] = Field(default_factory=list) last_error: Optional[str] = None connected_at: Optional[str] = None oauth_challenge: Optional[dict[str, Any]] = None def _normalize_single_connector_entry( name: str, raw: dict[str, Any], *, source: Literal["config", "bot"], default_timeout: int = 60, ) -> MCPConnectorConfig: """Normalize a single entry from `mcpServers` or `connectors` format into `MCPConnectorConfig`.""" data = dict(raw) # Support aliases from Claude Desktop / Cursor / Antigravity configs if "serverUrl" in data and "url" not in data: data["url"] = data.pop("serverUrl") if "server_url" in data and "url" not in data: data["url"] = data.pop("server_url") if "disabled" in data and "enabled" not in data: data["enabled"] = not bool(data.pop("disabled")) if "timeoutSeconds" in data and "timeout_seconds" not in data: data["timeout_seconds"] = int(data.pop("timeoutSeconds")) if "timeout" in data and "timeout_seconds" not in data: data["timeout_seconds"] = int(data.pop("timeout")) if "type" in data and "transport" not in data: raw_t = str(data.pop("type")).strip().lower() mapping = { "http": "streamable_http", "streamable-http": "streamable_http", "streamable_http": "streamable_http", "streamablehttp": "streamable_http", "sse": "sse", "stdio": "stdio", "auto": "auto", } if raw_t in mapping: data["transport"] = mapping[raw_t] if "transport" in data and isinstance(data["transport"], str): t_val = data["transport"].strip().lower().replace("-", "_") if t_val == "http": t_val = "streamable_http" data["transport"] = t_val if "transport" not in data: data["transport"] = "stdio" if data.get("command") and not data.get("url") else "auto" # Normalize auth shorthand if provided as string or dict raw_auth = data.get("auth") if isinstance(raw_auth, str): data["auth"] = {"type": raw_auth} elif isinstance(raw_auth, dict): auth_dict = dict(raw_auth) if "type" in auth_dict and isinstance(auth_dict["type"], str): a_type = auth_dict["type"].strip().lower().replace("-", "_") aliases = { "oauth": "oauth2_pkce", "oauth2": "oauth2_pkce", "pkce": "oauth2_pkce", "client_credentials": "oauth2_client_credentials", "device": "oauth2_device", "device_code": "oauth2_device", "refresh_token": "oauth2_refresh_token", "apikey": "api_key", "api-key": "api_key", "custom_headers": "headers", "header": "headers", } auth_dict["type"] = aliases.get(a_type, a_type) data["auth"] = auth_dict data["name"] = name data.setdefault("timeout_seconds", default_timeout) data["source"] = source return MCPConnectorConfig.model_validate(data) def parse_connectors_payload( payload: Any, *, source: Literal["config", "bot"] = "config", default_timeout: int = 60, ) -> list[MCPConnectorConfig]: """Parse MCP connectors from standard `mcpServers`, HomeAgent `connectors`, list, or bare dict.""" if not payload: return [] items: list[tuple[str, dict[str, Any]]] = [] if isinstance(payload, dict): if "mcpServers" in payload and isinstance(payload["mcpServers"], dict): for name, entry in payload["mcpServers"].items(): if isinstance(entry, dict): items.append((str(name), entry)) if "connectors" in payload: conns = payload["connectors"] if isinstance(conns, dict): for name, entry in conns.items(): if isinstance(entry, dict): items.append((str(name), entry)) elif isinstance(conns, list): for entry in conns: if isinstance(entry, dict) and entry.get("name"): items.append((str(entry["name"]), entry)) if "mcpServers" not in payload and "connectors" not in payload: # Either a single connector dict with "name", or a mapping {name: {...}} if "name" in payload and ( "url" in payload or "serverUrl" in payload or "command" in payload ): items.append((str(payload["name"]), payload)) else: for name, entry in payload.items(): if isinstance(entry, dict): items.append((str(name), entry)) elif isinstance(payload, list): for entry in payload: if isinstance(entry, dict) and entry.get("name"): items.append((str(entry["name"]), entry)) else: raise ValueError("Некорректный формат конфигурации MCP коннекторов (ожидался JSON/YAML объект или список).") result: list[MCPConnectorConfig] = [] for name, entry in items: result.append( _normalize_single_connector_entry( name, entry, source=source, default_timeout=default_timeout, ) ) return result