1. fix: charge fees even if the call tool fails due to MCP service not being available/under maintenance.

2. fix: OpenAPI requestBody Not Parsed for MCP Tools
This commit is contained in:
Liujian committed 2025-12-18 15:19:32 +08:00
1 parent ab04738aff
commit 2309de4025
3 files changed
+55 -40

No files matched your search

@@ -206,16 +206,17 @@ class McpServerFactory:
logger.debug(f"Call params: {call_params}")
# Execute tool
result,response_data = await self.tool_service.execute_tool(tool_config, arguments, call_params)
validation_ok, validation_msg = self._validate_output_schema(tool_config, response_data)
if not validation_ok:
call_success = False
error_text = f"Response validation failed: {validation_msg}"
result = [types.TextContent(type="text", text=error_text)]
response_data = {}
else:
call_success = True
logger.info(f"Tool call successful - User ID: {user_id}, Tool: {name}")
result,response_data,call_success = await self.tool_service.execute_tool(tool_config, arguments, call_params)
if call_success:
validation_ok, validation_msg = self._validate_output_schema(tool_config, response_data)
if not validation_ok:
call_success = False
error_text = f"Response validation failed: {validation_msg}"
result = [types.TextContent(type="text", text=error_text)]
response_data = {}
if call_success:
logger.info(f"Tool call successful - User ID: {user_id}, Tool: {name}")
if pre_deduct_result.charge_type == "per_token" and result and call_success:
output_text = ""
+41 -27
View File
@@ -185,14 +185,20 @@ class McpService:
for param in query_params:
if isinstance(param, dict) and "name" in param:
# Handle both direct type and schema.type formats
extend_properties = {}
param_type = "string" # default
if "type" in param:
param_type = param["type"]
elif "schema" in param and isinstance(param["schema"], dict) and "type" in param["schema"]:
param_type = param["schema"]["type"]
if param_type == "array":
extend_properties["items"] = param["schema"]["items"]
elif param_type == "object":
extend_properties["properties"] = param["schema"]["properties"]
schema["properties"][param["name"]] = {
"type": param_type,
**extend_properties,
"description": param.get("description", f"Query parameter: {param['name']}")
}
if param.get("required", False):
@@ -202,34 +208,34 @@ class McpService:
if tool_api.request_body_schema:
# Try to parse as parameters list first, then as schema object
try:
# First try to parse as parameters list (similar to query/path parameters)
body_params = self._safe_parse_params(tool_api.request_body_schema, tool_api.name, 'body')
if body_params:
# If it's a list of parameters, process them like query parameters
for param in body_params:
if isinstance(param, dict) and "name" in param:
param_type = "string" # default
if "type" in param:
param_type = param["type"]
elif "schema" in param and isinstance(param["schema"], dict) and "type" in param["schema"]:
param_type = param["schema"]["type"]
# # First try to parse as parameters list (similar to query/path parameters)
# body_params = self._safe_parse_params(tool_api.request_body_schema, tool_api.name, 'body')
# if body_params:
# # If it's a list of parameters, process them like query parameters
# for param in body_params:
# if isinstance(param, dict) and "name" in param:
# param_type = "string" # default
# if "type" in param:
# param_type = param["type"]
# elif "schema" in param and isinstance(param["schema"], dict) and "type" in param["schema"]:
# param_type = param["schema"]["type"]
schema["properties"][param["name"]] = {
"type": param_type,
"description": param.get("description", f"Body parameter: {param['name']}")
}
if param.get("required", False):
schema["required"].append(param["name"])
else:
# schema["properties"][param["name"]] = {
# "type": param_type,
# "description": param.get("description", f"Body parameter: {param['name']}")
# }
# if param.get("required", False):
# schema["required"].append(param["name"])
# else:
# If not a parameters list, try to parse as JSON schema object
try:
body_schema = json.loads(tool_api.request_body_schema)
if isinstance(body_schema, dict) and "properties" in body_schema:
schema["properties"].update(body_schema["properties"])
if "required" in body_schema:
schema["required"].extend(body_schema["required"])
except json.JSONDecodeError:
pass # Already logged by _safe_parse_params
try:
body_schema = json.loads(tool_api.request_body_schema)
if isinstance(body_schema, dict) and "properties" in body_schema:
schema["properties"].update(body_schema["properties"])
if "required" in body_schema:
schema["required"].extend(body_schema["required"])
except json.JSONDecodeError:
pass # Already logged by _safe_parse_params
except Exception as e:
self.logger.warning(f"Failed to parse request body schema for {tool_api.name}: {e}")
@@ -291,7 +297,15 @@ class McpService:
if tool_api.response_schema:
parsed = json.loads(tool_api.response_schema)
if isinstance(parsed, dict):
return parsed
if parsed["type"] != "object":
return {
"type":"object",
"properties":{
"data":parsed
}
}
else:
return parsed
except Exception as e:
self.logger.warning(f"Failed to parse response_schema for {tool_api.name}: {e}")
@@ -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) -> tuple[List[types.Content],dict]:
async def execute_tool(self, tool_config, arguments: dict, call_params: dict) -> tuple[List[types.Content],dict,bool]:
"""
Execute tool call
@@ -42,12 +42,12 @@ class McpToolService:
else:
response_data = {}
logger.info("Tool execution completed successfully")
return [types.TextContent(type="text", text=response_text)],response_data
return [types.TextContent(type="text", text=response_text)],response_data,True
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)],{},False
async def _send_http_request(self, request_info: Dict[str, Any]) -> str:
"""