"""Minimal stdio MCP server exposing the local read-only quality_data tool.""" from __future__ import annotations import json import logging import os import sys from pathlib import Path from typing import Any from nao_quality_tools import QualityToolError, QualityTools, tool_definition ROOT = Path(__file__).resolve().parents[1] LOG_DIR = ROOT / "output" / "nao-quality" / "tools" SUPPORTED_PROTOCOLS = ("2025-03-26", "2024-11-05") def _error(code: int, message: str, request_id: Any = None) -> dict[str, Any]: return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}} def _tool_result(value: dict[str, Any], *, is_error: bool = False) -> dict[str, Any]: encoded = json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False) return { "content": [{"type": "text", "text": encoded}], "structuredContent": value, "isError": is_error, } class MCPServer: def __init__(self, tools: QualityTools | None = None, logger: logging.Logger | None = None) -> None: self.tools = tools or QualityTools() self.logger = logger or logging.getLogger("nao_quality_mcp") self.initialized = False self.protocol_version: str | None = None def handle(self, request: Any) -> dict[str, Any] | None: if not isinstance(request, dict) or request.get("jsonrpc") != "2.0" or not isinstance(request.get("method"), str): request_id = request.get("id") if isinstance(request, dict) else None return _error(-32600, "无效 JSON-RPC 请求。", request_id) method = request["method"] request_id = request.get("id") is_notification = "id" not in request or method.startswith("notifications/") params = request.get("params") or {} if not isinstance(params, dict): if is_notification: return None return _error(-32602, "params 必须是对象。", request_id) if method == "initialize": version = params.get("protocolVersion") # MCP initialization negotiates the protocol version in the response. # If this client asks for a newer revision, advertise the newest revision # implemented here and let the client decide whether it can continue. selected_version = version if version in SUPPORTED_PROTOCOLS else SUPPORTED_PROTOCOLS[0] self.protocol_version = selected_version self.initialized = True return { "jsonrpc": "2.0", "id": request_id, "result": { "protocolVersion": selected_version, "capabilities": {"tools": {"listChanged": False}}, "serverInfo": {"name": "quality", "version": "1.0.0"}, "instructions": "quality_data 只读查询本机质量中心正式 HTTP API;沿用返回的 releaseId,并引用 evidenceId。", }, } if method == "notifications/initialized": self.initialized = True return None if method == "ping": return None if is_notification else {"jsonrpc": "2.0", "id": request_id, "result": {}} if method == "tools/list": return None if is_notification else { "jsonrpc": "2.0", "id": request_id, "result": {"tools": [tool_definition()]}, } if method == "tools/call": if is_notification: return None name = params.get("name") arguments = params.get("arguments", {}) if name != "quality_data": return _error(-32602, "未知工具;当前只提供 quality_data。", request_id) if not isinstance(arguments, dict): return _error(-32602, "quality_data arguments 必须是对象。", request_id) mode = arguments.get("mode") self.logger.info("tool call mode=%s", mode if isinstance(mode, str) else "invalid") try: result = self.tools.quality_data(arguments) return {"jsonrpc": "2.0", "id": request_id, "result": _tool_result(result)} except QualityToolError as error: self.logger.warning("tool rejected mode=%s message=%s", mode, str(error)[:400]) return {"jsonrpc": "2.0", "id": request_id, "result": _tool_result({"error": {"code": "invalid_or_unavailable", "message": str(error)}}, is_error=True)} except Exception: # Do not log request arguments, credentials, API bodies, or stack locals. self.logger.error("tool failed mode=%s; inspect local service and safe API status", mode) return {"jsonrpc": "2.0", "id": request_id, "result": _tool_result({"error": {"code": "api_failure", "message": "质量中心正式 API 查询未完成;请检查本机服务/登录权限后重试。没有返回空数据成功。"}}, is_error=True)} if is_notification: return None return _error(-32601, f"不支持的 MCP 方法:{method}。", request_id) def _configure_logger() -> logging.Logger: LOG_DIR.mkdir(parents=True, exist_ok=True) path = LOG_DIR / "nao_quality_mcp.log" handler = logging.FileHandler(path, encoding="utf-8") os.chmod(path, 0o600) handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s")) logger = logging.getLogger("nao_quality_mcp") logger.setLevel(logging.INFO) logger.handlers.clear() logger.addHandler(handler) logger.propagate = False return logger def serve(stdin: Any = sys.stdin, stdout: Any = sys.stdout, tools: QualityTools | None = None) -> None: server = MCPServer(tools=tools, logger=_configure_logger()) for raw_line in stdin: line = raw_line.strip() if not line: continue try: request = json.loads(line) except json.JSONDecodeError: response = _error(-32700, "无法解析 JSON。") else: response = server.handle(request) if response is not None: stdout.write(json.dumps(response, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n") stdout.flush() if __name__ == "__main__": serve()