Completed: OutputSchema functionality added to the MCP tools list.

This commit is contained in:
Liujian committed 2025-11-07 17:23:24 +08:00
1 parent 5450027bbc
commit a6064035bd
5 files changed
+28 -22

No files matched your search

@@ -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:
"""
+7 -7
View File
@@ -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:
@@ -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