|
| 1 | +"""ModelScope HTTP client for unified API requests.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import logging as std_logging |
| 5 | +import time |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +import requests |
| 9 | +from fastmcp.utilities import logging |
| 10 | + |
| 11 | +from modelscope_mcp_server.utils.metadata import get_server_version |
| 12 | + |
| 13 | +from .settings import settings |
| 14 | + |
| 15 | +logger = logging.get_logger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +class ModelScopeClient: |
| 19 | + """Unified client for ModelScope API requests.""" |
| 20 | + |
| 21 | + def __init__(self, timeout: int = settings.default_api_timeout_seconds): |
| 22 | + """Initialize the ModelScope client. |
| 23 | +
|
| 24 | + Args: |
| 25 | + timeout: Default timeout for requests in seconds |
| 26 | +
|
| 27 | + """ |
| 28 | + self.timeout = timeout |
| 29 | + self._session = requests.Session() |
| 30 | + |
| 31 | + def _get_default_headers(self) -> dict[str, str]: |
| 32 | + """Get default headers for all requests.""" |
| 33 | + headers = { |
| 34 | + "User-Agent": f"modelscope-mcp-server/{get_server_version()}", |
| 35 | + } |
| 36 | + |
| 37 | + if settings.is_api_token_configured(): |
| 38 | + headers["Authorization"] = f"Bearer {settings.api_token}" |
| 39 | + # TODO: Remove this once all API endpoints support Bearer token |
| 40 | + headers["Cookie"] = f"m_session_id={settings.api_token}" |
| 41 | + |
| 42 | + return headers |
| 43 | + |
| 44 | + def _prepare_request_headers( |
| 45 | + self, kwargs: dict, additional_headers: dict[str, str] | None = None |
| 46 | + ) -> dict[str, str]: |
| 47 | + """Prepare headers for a request and log them if DEBUG is enabled. |
| 48 | +
|
| 49 | + Args: |
| 50 | + kwargs: Request kwargs, may contain 'headers' key that will be popped |
| 51 | + additional_headers: Additional headers to add to defaults |
| 52 | +
|
| 53 | + Returns: |
| 54 | + Final headers dict to use for the request |
| 55 | +
|
| 56 | + """ |
| 57 | + headers = self._get_default_headers() |
| 58 | + if additional_headers: |
| 59 | + headers.update(additional_headers) |
| 60 | + if "headers" in kwargs: |
| 61 | + headers.update(kwargs.pop("headers")) |
| 62 | + |
| 63 | + # Log request headers if DEBUG level is enabled |
| 64 | + if logger.isEnabledFor(std_logging.DEBUG): |
| 65 | + headers_str = "\n".join([f" {key}: {value}" for key, value in headers.items()]) |
| 66 | + logger.debug(f"Request headers:\n{headers_str}") |
| 67 | + |
| 68 | + return headers |
| 69 | + |
| 70 | + def _handle_response(self, response: requests.Response, start_time: float) -> dict[str, Any]: |
| 71 | + """Handle common response processing.""" |
| 72 | + # Log response basic info |
| 73 | + elapsed_time = time.time() - start_time |
| 74 | + content_length = len(response.content) if response.content else 0 |
| 75 | + logger.info( |
| 76 | + f"Response: {response.status_code} {response.reason}, size: {content_length} bytes, " |
| 77 | + f"elapsed: {elapsed_time:.3f}s" |
| 78 | + ) |
| 79 | + |
| 80 | + # Log response headers if DEBUG level is enabled |
| 81 | + if logger.isEnabledFor(std_logging.DEBUG): |
| 82 | + headers_str = "\n".join([f" {key}: {value}" for key, value in response.headers.items()]) |
| 83 | + logger.debug(f"Response headers:\n{headers_str}") |
| 84 | + |
| 85 | + try: |
| 86 | + response_json = response.json() |
| 87 | + except json.JSONDecodeError as e: |
| 88 | + raise Exception(f"Failed to parse JSON response: {e}") from e |
| 89 | + |
| 90 | + # Log JSON body if DEBUG level is enabled |
| 91 | + if logger.isEnabledFor(std_logging.DEBUG): |
| 92 | + formatted_json = json.dumps(response_json, indent=2, ensure_ascii=False) |
| 93 | + logger.debug(f"Response body:\n{formatted_json}") |
| 94 | + |
| 95 | + # Raise an exception if the response is not successful |
| 96 | + response.raise_for_status() |
| 97 | + |
| 98 | + # If 'success = false' (case-insensitive), raise an exception |
| 99 | + if isinstance(response_json, dict): |
| 100 | + for key in response_json: |
| 101 | + if key.lower() == "success" and response_json[key] is False: |
| 102 | + raise Exception(f"Server returned error: {response_json}") |
| 103 | + |
| 104 | + return response_json |
| 105 | + |
| 106 | + def get( |
| 107 | + self, url: str, params: dict[str, Any] | None = None, timeout: int | None = None, **kwargs |
| 108 | + ) -> dict[str, Any]: |
| 109 | + """Perform GET request. |
| 110 | +
|
| 111 | + Args: |
| 112 | + url: The URL to request |
| 113 | + params: Query parameters |
| 114 | + timeout: Request timeout in seconds |
| 115 | + **kwargs: Additional arguments passed to requests.get |
| 116 | +
|
| 117 | + Returns: |
| 118 | + Parsed JSON response |
| 119 | +
|
| 120 | + Raises: |
| 121 | + TimeoutError: If request times out |
| 122 | + Exception: For other request errors |
| 123 | +
|
| 124 | + """ |
| 125 | + logger.info(f"Sending GET request to {url} with params: {params}") |
| 126 | + start_time = time.time() |
| 127 | + try: |
| 128 | + headers = self._prepare_request_headers(kwargs) |
| 129 | + |
| 130 | + response = self._session.get(url, params=params, timeout=timeout or self.timeout, headers=headers, **kwargs) |
| 131 | + return self._handle_response(response, start_time) |
| 132 | + except requests.exceptions.Timeout as e: |
| 133 | + raise TimeoutError("Request timeout - please try again later") from e |
| 134 | + |
| 135 | + def post( |
| 136 | + self, |
| 137 | + url: str, |
| 138 | + json_data: dict[str, Any] | None = None, |
| 139 | + timeout: int | None = None, |
| 140 | + **kwargs, |
| 141 | + ) -> dict[str, Any]: |
| 142 | + """Perform POST request. |
| 143 | +
|
| 144 | + Args: |
| 145 | + url: The URL to request |
| 146 | + json_data: JSON data to send (will be serialized) |
| 147 | + timeout: Request timeout in seconds |
| 148 | + **kwargs: Additional arguments passed to requests.post |
| 149 | +
|
| 150 | + Returns: |
| 151 | + Parsed JSON response |
| 152 | +
|
| 153 | + Raises: |
| 154 | + TimeoutError: If request times out |
| 155 | + Exception: For other request errors |
| 156 | +
|
| 157 | + """ |
| 158 | + return self._request_with_data("POST", url, json_data, timeout, **kwargs) |
| 159 | + |
| 160 | + def put( |
| 161 | + self, url: str, json_data: dict[str, Any] | None = None, timeout: int | None = None, **kwargs |
| 162 | + ) -> dict[str, Any]: |
| 163 | + """Perform PUT request. |
| 164 | +
|
| 165 | + Args: |
| 166 | + url: The URL to request |
| 167 | + json_data: JSON data to send |
| 168 | + timeout: Request timeout in seconds |
| 169 | + **kwargs: Additional arguments passed to requests.put |
| 170 | +
|
| 171 | + Returns: |
| 172 | + Parsed JSON response |
| 173 | +
|
| 174 | + Raises: |
| 175 | + TimeoutError: If request times out |
| 176 | + Exception: For other request errors |
| 177 | +
|
| 178 | + """ |
| 179 | + return self._request_with_data("PUT", url, json_data, timeout, **kwargs) |
| 180 | + |
| 181 | + def _request_with_data( |
| 182 | + self, |
| 183 | + method: str, |
| 184 | + url: str, |
| 185 | + json_data: dict[str, Any] | None = None, |
| 186 | + timeout: int | None = None, |
| 187 | + **kwargs, |
| 188 | + ) -> dict[str, Any]: |
| 189 | + """Perform HTTP request with JSON data.""" |
| 190 | + logger.info(f"Sending {method} request to {url} with data: {json_data}") |
| 191 | + start_time = time.time() |
| 192 | + try: |
| 193 | + headers = self._prepare_request_headers(kwargs, {"Content-Type": "application/json"}) |
| 194 | + |
| 195 | + response = self._session.request( |
| 196 | + method, |
| 197 | + url, |
| 198 | + data=json.dumps(json_data, ensure_ascii=False).encode("utf-8") if json_data else None, |
| 199 | + timeout=timeout or self.timeout, |
| 200 | + headers=headers, |
| 201 | + **kwargs, |
| 202 | + ) |
| 203 | + return self._handle_response(response, start_time) |
| 204 | + except requests.exceptions.Timeout as e: |
| 205 | + raise TimeoutError("Request timeout - please try again later") from e |
| 206 | + |
| 207 | + def close(self): |
| 208 | + """Close the session.""" |
| 209 | + self._session.close() |
| 210 | + |
| 211 | + def __enter__(self): |
| 212 | + """Context manager entry.""" |
| 213 | + return self |
| 214 | + |
| 215 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 216 | + """Context manager exit.""" |
| 217 | + self.close() |
| 218 | + |
| 219 | + |
| 220 | +# Global client instance with default settings |
| 221 | +default_client = ModelScopeClient() |
0 commit comments