返回提交历史
Modified
g4f/mcp/server.py
+67
-0
XFEstudio/gpt4free
fix: Add media file handling to MCPServer with caching and conditional requests
8e52133e
代码差异
1 个文件
+67
-0
@@ -10,14 +10,21 @@ The server exposes tools for:
10
10
11
11
from __future__ import annotations
12
12
13
import os
14
import re
13
15
import sys
14
16
import json
15
17
import asyncio
18
import hashlib
19
from email.utils import formatdate
16
20
from typing import Any, Dict, List, Optional, Union
17
21
from dataclasses import dataclass
22
from urllib.parse import unquote_plus
18
23
19
24
from ..debug import enable_logging
20
25
from ..cookies import read_cookie_files
26
from ..image import EXTENSIONS_MAP
27
from ..image.copy_images import get_media_dir, copy_media, get_source_url
21
28
22
29
from .tools import MarkItDownTool, TextToAudioTool, WebSearchTool, WebScrapeTool, ImageGenerationTool
23
30
from .tools import WebSearchTool, WebScrapeTool, ImageGenerationTool
@@ -275,17 +282,77 @@ class MCPServer:
275
282
"server": self.server_info
276
283
})
277
284
285
async def handle_media(request: web.Request) -> web.Response:
286
"""Serve media files from generated_media directory"""
287
filename = request.match_info.get('filename', '')
288
if not filename:
289
return web.Response(status=404, text="File not found")
290
291
def get_timestamp(s):
292
m = re.match("^[0-9]+", s)
293
return int(m.group(0)) if m else 0
294
295
target = os.path.join(get_media_dir(), os.path.basename(filename))
296
297
# Try URL-decoded filename if not found
298
if not os.path.isfile(target):
299
other_name = os.path.join(get_media_dir(), os.path.basename(unquote_plus(filename)))
300
if os.path.isfile(other_name):
301
target = other_name
302
303
# Get file extension and mime type
304
ext = os.path.splitext(filename)[1][1:].lower()
305
mime_type = EXTENSIONS_MAP.get(ext, "application/octet-stream")
306
307
# Try to fetch from backend if file doesn't exist
308
if not os.path.isfile(target) and mime_type != "application/octet-stream":
309
source_url = get_source_url(str(request.query_string))
310
ssl = None
311
if source_url is not None:
312
try:
313
await copy_media([source_url], target=target, ssl=ssl)
314
sys.stderr.write(f"File copied from {source_url}\n")
315
except Exception as e:
316
sys.stderr.write(f"Download failed: {source_url} - {e}\n")
317
raise web.HTTPFound(location=source_url)
318
319
if not os.path.isfile(target):
320
return web.Response(status=404, text="File not found")
321
322
# Build response headers
323
stat_result = os.stat(target)
324
headers = {
325
"cache-control": "public, max-age=31536000",
326
"last-modified": formatdate(get_timestamp(filename), usegmt=True),
327
"etag": f'"{hashlib.md5(filename.encode()).hexdigest()}"',
328
"content-length": str(stat_result.st_size),
329
"content-type": mime_type,
330
"access-control-allow-origin": "*",
331
}
332
333
# Check for conditional request
334
if_none_match = request.headers.get("if-none-match")
335
if if_none_match:
336
etag = headers["etag"]
337
if etag in [tag.strip(" W/") for tag in if_none_match.split(",")]:
338
return web.Response(status=304, headers=headers)
339
340
# Serve the file
341
return web.FileResponse(target, headers=headers)
342
278
343
# Create aiohttp application
279
344
app = web.Application()
280
345
app.router.add_options('/mcp', lambda request: web.Response(headers={"access-control-allow-origin": "*", "access-control-allow-methods": "POST, OPTIONS", "access-control-allow-headers": "Content-Type"}))
281
346
app.router.add_post('/mcp', handle_mcp_request)
282
347
app.router.add_get('/health', handle_health)
348
app.router.add_get('/media/{filename:.*}', handle_media)
283
349
284
350
# Start server
285
351
sys.stderr.write(f"Starting {self.server_info['name']} v{self.server_info['version']} (HTTP mode)\n")
286
352
sys.stderr.write(f"Listening on http://{host}:{port}\n")
287
353
sys.stderr.write(f"MCP endpoint: http://{host}:{port}/mcp\n")
288
354
sys.stderr.write(f"Health check: http://{host}:{port}/health\n")
355
sys.stderr.write(f"Media files: http://{host}:{port}/media/{{filename}}\n")
289
356
sys.stderr.flush()
290
357
291
358
runner = web.AppRunner(app)