From a6064035bdfeb29acfb92e5544e673fdaf5fb94a Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Fri, 7 Nov 2025 17:23:24 +0800 Subject: [PATCH] Completed: OutputSchema functionality added to the MCP tools list. --- scripts/resource/.env.example | 2 +- scripts/resource/start.sh | 4 ++-- .../api_service/services/mcp_server_factory.py | 17 +++++++++-------- services/api_service/services/mcp_service.py | 14 +++++++------- .../api_service/services/mcp_tool_service.py | 13 +++++++++---- 5 files changed, 28 insertions(+), 22 deletions(-) diff --git a/scripts/resource/.env.example b/scripts/resource/.env.example index 89949e1..871f7e4 100644 --- a/scripts/resource/.env.example +++ b/scripts/resource/.env.example @@ -6,7 +6,7 @@ MYSQL_PASSWORD=mysql_ZTdhRB MYSQL_DB=xpack # 服务端口配置 -API_PORT=8000 +API_PORT=8002 ADMIN_PORT=8001 # 调试配置 diff --git a/scripts/resource/start.sh b/scripts/resource/start.sh index 1ec8445..96fc5d6 100755 --- a/scripts/resource/start.sh +++ b/scripts/resource/start.sh @@ -34,11 +34,11 @@ fi # 初始化数据库 python ./init_db.py -nohup uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload > ${LOG_DIR}/admin_service.log 2>&1 & +nohup uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload --timeout-graceful-shutdown 2 --timeout-keep-alive 1 > ${LOG_DIR}/admin_service.log 2>&1 & sleep 5s -nohup uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload > ${LOG_DIR}/api_service.log 2>&1 & +nohup uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload --timeout-graceful-shutdown 2 --timeout-keep-alive 1 > ${LOG_DIR}/api_service.log 2>&1 & HOSTNAME="" cd frontend/ && nohup node server.js> ${LOG_DIR}//frontend.log 2>&1 & diff --git a/services/api_service/services/mcp_server_factory.py b/services/api_service/services/mcp_server_factory.py index 0eff507..877ef12 100644 --- a/services/api_service/services/mcp_server_factory.py +++ b/services/api_service/services/mcp_server_factory.py @@ -57,13 +57,13 @@ class McpServerFactory: # Register tool call handler @app.call_tool() - async def call_tool(name: str, arguments: dict) -> List[types.Content]: + async def call_tool(name: str, arguments: dict) -> tuple[List[types.Content], dict]: """Execute specified tool""" # user_id must exist, otherwise we shouldn't reach here if not user_id: error_msg = "Missing user authentication" logger.error(error_msg) - return [types.TextContent(type="text", text=error_msg)] + return [types.TextContent(type="text", text=error_msg)], {} return await self._handle_call_tool_with_billing(service_id, name, arguments, user_id, apikey_id) @@ -102,7 +102,7 @@ class McpServerFactory: finally: db.close() - async def _handle_call_tool_with_billing(self, service_id: str, name: str, arguments: dict, user_id: str, apikey_id: Optional[str] = None) -> List[types.Content]: + async def _handle_call_tool_with_billing(self, service_id: str, name: str, arguments: dict, user_id: str, apikey_id: Optional[str] = None) -> tuple[List[types.Content], dict]: """ Handle tool call with billing logic @@ -145,7 +145,7 @@ class McpServerFactory: # If tool API id not found, skip sending billing message to avoid FK errors if not api_id_for_log: - return [types.TextContent(type="text", text=error_msg)] + return [types.TextContent(type="text", text=error_msg)], {} call_log = ApiCallLogInfo( user_id=user_id, @@ -163,7 +163,7 @@ class McpServerFactory: ) await self.billing_service.send_billing_message(call_log, False, datetime.now(timezone.utc)) - return [types.TextContent(type="text", text=error_msg)] + return [types.TextContent(type="text", text=error_msg)],{} logger.info(f"Pre-deduction successful - User ID: {user_id}, Deduction amount: {pre_deduct_result.service_price}") amount = pre_deduct_result.service_price @@ -171,6 +171,7 @@ class McpServerFactory: db = next(get_db()) call_success = False result: List[types.ContentBlock] = [] + response_data: dict = {} # calculate input token amount input_token_amount = Decimal("0") output_token_amount = Decimal("0") @@ -195,7 +196,7 @@ class McpServerFactory: logger.error(error_msg) # Close DB and return error without sending billing message to avoid FK violation db.close() - return [types.TextContent(type="text", text=error_msg)] + return [types.TextContent(type="text", text=error_msg)],{} try: logger.info(f"Found tool configuration: {tool_config.name}") @@ -205,7 +206,7 @@ class McpServerFactory: logger.debug(f"Call params: {call_params}") # Execute tool - result = await self.tool_service.execute_tool(tool_config, arguments, call_params) + result,response_data = await self.tool_service.execute_tool(tool_config, arguments, call_params) call_success = True logger.info(f"Tool call successful - User ID: {user_id}, Tool: {name}") @@ -254,7 +255,7 @@ class McpServerFactory: logger.info(f"Billing message sent - User ID: {user_id}, Tool: {name}, Success: {call_success}") # Ensure return type is correct - return result + return result,response_data def _create_mcp_service(self, db) -> McpService: """ diff --git a/services/api_service/services/mcp_service.py b/services/api_service/services/mcp_service.py index 7968a0d..e56310d 100644 --- a/services/api_service/services/mcp_service.py +++ b/services/api_service/services/mcp_service.py @@ -131,12 +131,15 @@ class McpService: "required": [] } - return types.Tool( + t = types.Tool( name=tool_api.name, description=tool_api.description, inputSchema=input_schema, - outputSchema=self._build_output_schema(tool_api), ) + output_schema = self._build_output_schema(tool_api) + if output_schema: + t.outputSchema = output_schema + return t except Exception as e: self.logger.error(f"Tool conversion failed for {tool_api.name}: {e}") return None @@ -274,7 +277,7 @@ class McpService: "headers": headers } - def _build_output_schema(self,tool_api:McpToolApi) -> dict: + def _build_output_schema(self,tool_api:McpToolApi) -> Optional[dict]: """ Build output schema based on API configuration @@ -305,10 +308,7 @@ class McpService: self.logger.warning(f"Failed to infer schema from response_examples for {tool_api.name}: {e}") # 3) Fallback to a generic text MCP content schema - return { - "type": "string", - "description": "Raw response text when no schema or examples are available" - } + return None # Helper: Infer a simple JSON Schema from a Python value def _infer_json_schema_from_example(self, value) -> dict: diff --git a/services/api_service/services/mcp_tool_service.py b/services/api_service/services/mcp_tool_service.py index 3296947..1bda5a6 100644 --- a/services/api_service/services/mcp_tool_service.py +++ b/services/api_service/services/mcp_tool_service.py @@ -17,7 +17,7 @@ class McpToolService: def __init__(self): self.http_builder = HttpRequestBuilder() - async def execute_tool(self, tool_config, arguments: dict, call_params: dict) -> List[types.Content]: + async def execute_tool(self, tool_config, arguments: dict, call_params: dict) -> tuple[List[types.Content],dict]: """ Execute tool call @@ -37,14 +37,17 @@ class McpToolService: # Send HTTP request response_text = await self._send_http_request(request_info) - + if response_text: + response_data = json.loads(response_text) + else: + response_data = {} logger.info("Tool execution completed successfully") - return [types.TextContent(type="text", text=response_text)] + return [types.TextContent(type="text", text=response_text)],response_data except Exception as e: error_msg = f"Tool execution failed: {str(e)}" logger.error(f"Tool execution failed: {error_msg}", exc_info=True) - return [types.TextContent(type="text", text=error_msg)] + return [types.TextContent(type="text", text=error_msg)],{} async def _send_http_request(self, request_info: Dict[str, Any]) -> str: """ @@ -81,6 +84,8 @@ class McpToolService: raise ValueError(f"Unsupported HTTP method: {method}") logger.info(f"HTTP response status code: {response.status_code}") + if response.text != "": + logger.debug(f"Response content: {response.text}") response.raise_for_status() response_text = response.text