@staticmethod def_build_auth(config: Config) -> httpx.Auth: """Single auth injection point. Swap to session/cookie auth here in a future version.""" return httpx.BasicAuth(config.username, config.password)
def_process_response(self, response: httpx.Response, method: str, path: str) -> dict[str, Any]: """Raise on HTTP errors and success=false; return the data field (or full body).""" response.raise_for_status() response_json = response.json()
if response_json.get("success") isFalse: error_msg = response_json.get("message", "Unknown API error") raise ValueError(f"Request API error for {method}{path}: {error_msg}")
return response_json.get("data", response_json)
defget(self, path: str) -> dict[str, Any]: """GET a Console API path and return the unwrapped data.""" response = self._client.get(path) returnself._process_response(response, "GET", path)
defpost(self, path: str, data: dict[str, Any]) -> dict[str, Any]: """POST JSON to a Console API path and return the unwrapped data.""" response = self._client.post(path, json=data) returnself._process_response(response, "POST", path)
defput(self, path: str, data: dict[str, Any]) -> dict[str, Any]: """PUT JSON to a Console API path and return the unwrapped data.""" response = self._client.put(path, json=data) returnself._process_response(response, "PUT", path)
defget_route(self, name: str) -> dict[str, Any] | list[dict[str, Any]]: """Get one route by name.""" returnself.get(f"/v1/routes/{name}")
defadd_route(self, configurations: dict[str, Any]) -> dict[str, Any] | list[dict[str, Any]]: """Create a route. Requires name, path and services in configurations.""" ifnot configurations.get("name"): raise ValueError("Route name is required") ifnot configurations.get("path"): raise ValueError("Route path configuration is required") ifnot configurations.get("services"): raise ValueError("At least one service is required for the route") returnself.post("/v1/routes", configurations)
defupdate_route(self, name: str, configurations: dict[str, Any]) -> dict[str, Any] | list[dict[str, Any]]: """Update a route by merging configurations into the current ones (avoids overwriting).""" ifnot name: raise ValueError("Route name is required") route_config = self.get_route(name) if configurations: route_config.update(configurations) returnself.put(f"/v1/routes/{name}", route_config)
def_setup_logging() -> None: """Log to stderr only — stdout is the stdio transport channel.""" handler = logging.StreamHandler(sys.stderr) handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")) root = logging.getLogger() root.handlers = [handler] root.setLevel(logging.INFO)
def_run(call) -> str: """Execute a client call, converting any failure into an "Error: ..." text result.""" try: return json.dumps(call(), ensure_ascii=False) except (ValueError, httpx.HTTPStatusError, httpx.HTTPError) as e: logger.warning("Tool call failed: %s", e) returnf"Error: {e}" except Exception as e: # noqa: BLE001 - tools must never crash the MCP server logger.exception("Unexpected tool failure") returnf"Error: {e}"
defcreate_mcp_server(client: HigressClient) -> FastMCP: """Create a FastMCP server with all Higress operation tools registered.""" _setup_logging() mcp = FastMCP("higress-mcp-server")
@mcp.tool deflist_routes() -> str: """List all routes configured on the Higress gateway.""" return _run(client.list_routes)
@mcp.tool defget_route(name: str) -> str: """Get detailed configuration of a route by its name.""" return _run(lambda: client.get_route(name))
@mcp.tool defadd_route(configurations: dict[str, Any]) -> str: """Create a route. configurations must contain: name (str), path (str), services (list).""" return _run(lambda: client.add_route(configurations))
@mcp.tool defupdate_route(name: str, configurations: dict[str, Any]) -> str: """Update an existing route; configurations are merged into the current ones.""" return _run(lambda: client.update_route(name, configurations))
看代码其实和我们正常调用一个三方平台的方式(或者 Function Calling)一样,为什么还要多此一举用 MCP 封装呢?