返回提交历史
Modified
g4f/mcp/server.py
+3
-3
Modified
g4f/mcp/tools.py
+68
-34
XFEstudio/gpt4free
Address code review feedback: improve type hints, validation, and documentation
Co-authored-by: hlohaus <983577+hlohaus@users.noreply.github.com>
0a72ce96
代码差异
2 个文件
+71
-37
@@ -12,7 +12,7 @@ from __future__ import annotations
12
12
import sys
13
13
import json
14
14
import asyncio
15
from typing import Any, Dict, List, Optional
15
from typing import Any, Dict, List, Optional, Union
16
16
from dataclasses import dataclass, asdict
17
17
18
18
from .tools import WebSearchTool, WebScrapeTool, ImageGenerationTool
@@ -22,7 +22,7 @@ from .tools import WebSearchTool, WebScrapeTool, ImageGenerationTool
22
22
class MCPRequest:
23
23
"""MCP request following JSON-RPC 2.0 format"""
24
24
jsonrpc: str = "2.0"
25
id: Optional[int | str] = None
25
id: Optional[Union[int, str]] = None
26
26
method: Optional[str] = None
27
27
params: Optional[Dict[str, Any]] = None
28
28
@@ -31,7 +31,7 @@ class MCPRequest:
31
31
class MCPResponse:
32
32
"""MCP response following JSON-RPC 2.0 format"""
33
33
jsonrpc: str = "2.0"
34
id: Optional[int | str] = None
34
id: Optional[Union[int, str]] = None
35
35
result: Optional[Any] = None
36
36
error: Optional[Dict[str, Any]] = None
37
37
@@ -29,8 +29,15 @@ class MCPTool(ABC):
29
29
pass
30
30
31
31
@abstractmethod
32
async def execute(self, arguments: Dict[str, Any]) -> Any:
33
"""Execute the tool with given arguments"""
32
async def execute(self, arguments: Dict[str, Any]) -> Dict[str, Any]:
33
"""Execute the tool with given arguments
34
35
Args:
36
arguments: Tool input arguments matching the input_schema
37
38
Returns:
39
Dict containing either results or an error key with error message
40
"""
34
41
pass
35
42
36
43
@@ -60,7 +67,11 @@ class WebSearchTool(MCPTool):
60
67
}
61
68
62
69
async def execute(self, arguments: Dict[str, Any]) -> Dict[str, Any]:
63
"""Execute web search"""
70
"""Execute web search
71
72
Returns:
73
Dict[str, Any]: Search results or error message
74
"""
64
75
from ..tools.web_search import do_search
65
76
66
77
query = arguments.get("query", "")
@@ -72,7 +83,8 @@ class WebSearchTool(MCPTool):
72
83
}
73
84
74
85
try:
75
# Perform search
86
# Perform search - query parameter is used for search execution
87
# and prompt parameter holds the content to be searched
76
88
result, sources = await do_search(
77
89
prompt=query,
78
90
query=query,
@@ -127,7 +139,11 @@ class WebScrapeTool(MCPTool):
127
139
}
128
140
129
141
async def execute(self, arguments: Dict[str, Any]) -> Dict[str, Any]:
130
"""Execute web scraping"""
142
"""Execute web scraping
143
144
Returns:
145
Dict[str, Any]: Scraped content or error message
146
"""
131
147
from ..tools.fetch_and_scrape import fetch_and_scrape
132
148
from aiohttp import ClientSession
133
149
@@ -202,7 +218,11 @@ class ImageGenerationTool(MCPTool):
202
218
}
203
219
204
220
async def execute(self, arguments: Dict[str, Any]) -> Dict[str, Any]:
205
"""Execute image generation"""
221
"""Execute image generation
222
223
Returns:
224
Dict[str, Any]: Generated image data or error message
225
"""
206
226
from ..client import AsyncClient
207
227
from ..image import to_data_uri
208
228
import base64
@@ -228,35 +248,49 @@ class ImageGenerationTool(MCPTool):
228
248
height=height
229
249
)
230
250
231
# Get the image data
232
if response and hasattr(response, 'data') and response.data:
233
image_data = response.data[0]
234
235
# Convert to base64 if needed
236
if hasattr(image_data, 'url'):
237
image_url = image_data.url
238
239
# Check if it's already a data URI
240
if image_url.startswith('data:'):
241
return {
242
"prompt": prompt,
243
"model": model,
244
"width": width,
245
"height": height,
246
"image": image_url
247
}
248
else:
249
return {
250
"prompt": prompt,
251
"model": model,
252
"width": width,
253
"height": height,
254
"image_url": image_url
255
}
251
# Get the image data with proper validation
252
if not response:
253
return {
254
"error": "Image generation failed: No response from provider"
255
}
256
256
257
return {
258
"error": "Image generation failed: No image data in response"
259
}
257
if not hasattr(response, 'data') or not response.data:
258
return {
259
"error": "Image generation failed: No image data in response"
260
}
261
262
if len(response.data) == 0:
263
return {
264
"error": "Image generation failed: Empty image data array"
265
}
266
267
image_data = response.data[0]
268
269
# Check if image_data has url attribute
270
if not hasattr(image_data, 'url'):
271
return {
272
"error": "Image generation failed: No URL in image data"
273
}
274
275
image_url = image_data.url
276
277
# Return result based on URL type
278
if image_url.startswith('data:'):
279
return {
280
"prompt": prompt,
281
"model": model,
282
"width": width,
283
"height": height,
284
"image": image_url
285
}
286
else:
287
return {
288
"prompt": prompt,
289
"model": model,
290
"width": width,
291
"height": height,
292
"image_url": image_url
293
}
260
294
261
295
except Exception as e:
262
296
return {