返回提交历史
Modified
g4f/mcp/__init__.py
+2
-2
Modified
g4f/mcp/server.py
+3
-0
Modified
g4f/mcp/tools.py
+162
-3
Modified
g4f/tools/fetch_and_scrape.py
+34
-6
XFEstudio/gpt4free
Add MarkItDownTool and TextToAudioTool; enhance scrape_text and fetch_and_scrape functions with metadata support
5d53e58d
代码差异
4 个文件
+201
-11
@@ -8,6 +8,6 @@ through the Model Context Protocol standard, allowing AI assistants to access:
8
8
"""
9
9
10
10
from .server import MCPServer
11
from .tools import WebSearchTool, WebScrapeTool, ImageGenerationTool
11
from .tools import MarkItDownTool, TextToAudioTool, WebSearchTool, WebScrapeTool, ImageGenerationTool
12
12
13
__all__ = ['MCPServer', 'WebSearchTool', 'WebScrapeTool', 'ImageGenerationTool']
13
__all__ = ['MCPServer', 'MarkItDownTool', 'TextToAudioTool', 'WebSearchTool', 'WebScrapeTool', 'ImageGenerationTool']
@@ -20,6 +20,7 @@ from ..debug import enable_logging
20
20
21
21
enable_logging()
22
22
23
from .tools import MarkItDownTool, TextToAudioTool, WebSearchTool, WebScrapeTool, ImageGenerationTool
23
24
from .tools import WebSearchTool, WebScrapeTool, ImageGenerationTool
24
25
25
26
@@ -54,6 +55,8 @@ class MCPServer:
54
55
'web_search': WebSearchTool(),
55
56
'web_scrape': WebScrapeTool(),
56
57
'image_generation': ImageGenerationTool(),
58
'text_to_audio': TextToAudioTool(),
59
'mark_it_down': MarkItDownTool()
57
60
}
58
61
self.server_info = {
59
62
"name": "gpt4free-mcp-server",
@@ -8,7 +8,6 @@ This module provides MCP tool implementations that wrap gpt4free capabilities:
8
8
9
9
from __future__ import annotations
10
10
11
import asyncio
12
11
from typing import Any, Dict
13
12
from abc import ABC, abstractmethod
14
13
@@ -158,7 +157,7 @@ class WebScrapeTool(MCPTool):
158
157
session=session,
159
158
url=url,
160
159
max_words=max_words,
161
add_source=True
160
add_metadata=True
162
161
)
163
162
164
163
if not content:
@@ -183,7 +182,7 @@ class ImageGenerationTool(MCPTool):
183
182
184
183
@property
185
184
def description(self) -> str:
186
return "Generate images from text prompts using AI image generation providers. Returns base64-encoded image data."
185
return "Generate images from text prompts using AI image generation providers. Returns a URL to the generated image."
187
186
188
187
@property
189
188
def input_schema(self) -> Dict[str, Any]:
@@ -291,3 +290,163 @@ class ImageGenerationTool(MCPTool):
291
290
return {
292
291
"error": f"Image generation failed: {str(e)}"
293
292
}
293
294
class MarkItDownTool(MCPTool):
295
"""MarkItDown tool for converting URLs to markdown format"""
296
297
@property
298
def description(self) -> str:
299
return "Convert a URL to markdown format using MarkItDown. Supports HTTP/HTTPS URLs and returns formatted markdown content."
300
301
@property
302
def input_schema(self) -> Dict[str, Any]:
303
return {
304
"type": "object",
305
"properties": {
306
"url": {
307
"type": "string",
308
"description": "The URL to convert to markdown format (must be HTTP/HTTPS)"
309
},
310
"max_content_length": {
311
"type": "integer",
312
"description": "Maximum content length for processing (default: 10000)",
313
"default": 10000
314
}
315
},
316
"required": ["url"]
317
}
318
319
async def execute(self, arguments: Dict[str, Any]) -> Dict[str, Any]:
320
"""Execute MarkItDown conversion
321
322
Returns:
323
Dict[str, Any]: Markdown content or error message
324
"""
325
try:
326
from ..integration.markitdown import MarkItDown
327
except ImportError as e:
328
return {
329
"error": f"MarkItDown is not installed: {str(e)}"
330
}
331
332
url = arguments.get("url", "")
333
max_content_length = arguments.get("max_content_length", 10000)
334
335
if not url:
336
return {
337
"error": "URL parameter is required"
338
}
339
340
# Validate URL format
341
if not url.startswith(("http://", "https://")):
342
return {
343
"error": "URL must start with http:// or https://"
344
}
345
346
try:
347
# Initialize MarkItDown
348
md = MarkItDown()
349
350
# Convert URL to markdown
351
result = md.convert_url(url)
352
353
if not result:
354
return {
355
"error": "Failed to convert URL to markdown"
356
}
357
358
# Truncate if content exceeds max length
359
if len(result) > max_content_length:
360
result = result[:max_content_length] + "\n\n[Content truncated...]"
361
362
return {
363
"url": url,
364
"markdown_content": result,
365
"content_length": len(result),
366
"truncated": len(result) > max_content_length
367
}
368
369
except Exception as e:
370
return {
371
"error": f"MarkItDown conversion failed: {str(e)}"
372
}
373
374
class TextToAudioTool(MCPTool):
375
"""TextToAudio tool for generating audio from text prompts using Pollinations AI"""
376
377
@property
378
def description(self) -> str:
379
return "Generate an audio URL from a text prompt using Pollinations AI text-to-speech service. Returns a direct URL to the generated audio file."
380
381
@property
382
def input_schema(self) -> Dict[str, Any]:
383
return {
384
"type": "object",
385
"properties": {
386
"prompt": {
387
"type": "string",
388
"description": "The text prompt to the audio model (example: 'Read this: Hello, world!')"
389
},
390
"voice": {
391
"type": "string",
392
"description": "Voice option for text-to-speech (default: 'alloy')",
393
"default": "alloy"
394
},
395
"url_encode": {
396
"type": "boolean",
397
"description": "Whether to URL-encode the prompt text (default: True)",
398
"default": True
399
}
400
},
401
"required": ["prompt"]
402
}
403
404
async def execute(self, arguments: Dict[str, Any]) -> Dict[str, Any]:
405
"""Execute text-to-speech conversion
406
407
Returns:
408
Dict[str, Any]: Audio URL or error message
409
"""
410
try:
411
import urllib.parse
412
except ImportError as e:
413
return {
414
"error": f"urllib is not available: {str(e)}"
415
}
416
417
prompt = arguments.get("prompt", "")
418
voice = arguments.get("voice", "alloy")
419
url_encode = arguments.get("url_encode", True)
420
421
if not prompt:
422
return {
423
"error": "Prompt parameter is required"
424
}
425
426
# Validate prompt length (reasonable limit for text-to-speech)
427
if len(prompt) > 5000:
428
return {
429
"error": "Prompt is too long (max 5000 characters)"
430
}
431
432
try:
433
# Prepare the prompt for URL
434
if url_encode:
435
encoded_prompt = urllib.parse.quote(prompt)
436
else:
437
encoded_prompt = prompt.replace(" ", "%20") # Basic space encoding
438
439
# Construct the Pollinations AI text-to-speech URL
440
base_url = "https://text.pollinations.ai"
441
audio_url = f"{base_url}/{encoded_prompt}?voice={voice}"
442
443
return {
444
"prompt": prompt,
445
"voice": voice,
446
"audio_url": audio_url
447
}
448
449
except Exception as e:
450
return {
451
"error": f"Text-to-speech URL generation failed: {str(e)}"
452
}
@@ -3,14 +3,14 @@ from __future__ import annotations
3
3
import hashlib
4
4
import asyncio
5
5
from pathlib import Path
6
from typing import Iterator, Optional
6
from typing import Dict, Iterator, Optional
7
7
from urllib.parse import urlparse, quote_plus
8
8
from aiohttp import ClientSession, ClientError
9
9
from datetime import date
10
10
import asyncio
11
11
12
12
try:
13
from bs4 import BeautifulSoup
13
from bs4 import BeautifulSoup, Tag
14
14
has_requirements = True
15
15
except ImportError:
16
16
has_requirements = False
@@ -18,11 +18,39 @@ except ImportError:
18
18
from ..cookies import get_cookies_dir
19
19
from ..providers.response import format_link
20
20
21
def scrape_text(html: str, max_words: Optional[int] = None, add_source: bool = True, count_images: int = 2) -> Iterator[str]:
21
def scrape_text(html: str, max_words: Optional[int] = None, add_source: bool = True, count_images: int = 2, add_metadata: bool = False) -> Iterator[str]:
22
22
"""
23
23
Parses the provided HTML and yields text fragments.
24
24
"""
25
25
soup = BeautifulSoup(html, "html.parser")
26
27
# Read the meta tags
28
if add_metadata:
29
metadata: Dict[str, str] = {}
30
31
if soup.title and soup.title.string:
32
yield f"## {soup.title.string}\n"
33
seen_texts.append(soup.title.string)
34
max_words = None if max_words is None else max_words - len(soup.title.string.split())
35
36
for meta in soup(["meta"]):
37
if not isinstance(meta, Tag):
38
continue
39
40
for a in meta.attrs:
41
if a in ["itemprop", "property", "name"]:
42
key = str(meta.get(a, ""))
43
content = str(meta.get("content", ""))
44
if key and content: # Only add non-empty content
45
metadata[key] = content
46
break
47
48
description = metadata.get('description', metadata.get('og:description', '')).strip()
49
if description:
50
yield f"### Description\n{description}\n"
51
seen_texts.append(description)
52
max_words = None if max_words is None else max_words - len(description.split())
53
26
54
for selector in [
27
55
"main", ".main-content-wrapper", ".main-content", ".emt-container-inner",
28
56
".content-wrapper", "#content", "#mainContent",
@@ -74,14 +102,14 @@ def scrape_text(html: str, max_words: Optional[int] = None, add_source: bool = T
74
102
domain = urlparse(link).netloc
75
103
yield f"\nSource: [{domain}]({link})"
76
104
77
async def fetch_and_scrape(session: ClientSession, url: str, max_words: Optional[int] = None, add_source: bool = False, proxy: str = None) -> str:
105
async def fetch_and_scrape(session: ClientSession, url: str, max_words: Optional[int] = None, add_source: bool = False, add_metadata: bool = False, proxy: str = None) -> str:
78
106
"""
79
107
Fetches a URL and returns the scraped text, using caching to avoid redundant downloads.
80
108
"""
81
109
try:
82
110
cache_dir: Path = Path(get_cookies_dir()) / ".scrape_cache" / "fetch_and_scrape"
83
111
cache_dir.mkdir(parents=True, exist_ok=True)
84
md5_hash = hashlib.md5(url.encode(errors="ignore")).hexdigest()
112
md5_hash = hashlib.md5(url.encode(errors="ignore")+str([max_words, add_source, add_metadata]).encode(errors="ignore")).hexdigest()
85
113
cache_file = cache_dir / f"{quote_plus(url.split('?')[0].split('//')[1].replace('/', ' ')[:48])}.{date.today()}.{md5_hash[:16]}.cache"
86
114
if cache_file.exists():
87
115
return cache_file.read_text()
@@ -89,7 +117,7 @@ async def fetch_and_scrape(session: ClientSession, url: str, max_words: Optional
89
117
async with session.get(url, proxy=proxy) as response:
90
118
if response.status == 200:
91
119
html = await response.text(errors="replace")
92
scraped_text = "".join(scrape_text(html, max_words, add_source))
120
scraped_text = "".join(scrape_text(html, max_words, add_source, add_metadata=add_metadata))
93
121
with open(cache_file, "wb") as f:
94
122
f.write(scraped_text.encode(errors="replace"))
95
123
return scraped_text