|
| 1 | +"""Stateless MCP Streamable HTTP endpoint for quick share uploads.""" |
| 2 | +import base64 |
| 3 | +import binascii |
| 4 | +import html |
| 5 | +import io |
| 6 | +import json |
| 7 | +from html.parser import HTMLParser |
| 8 | +from urllib.parse import quote, urlsplit |
| 9 | + |
| 10 | +from fastapi import APIRouter, HTTPException, Request, UploadFile |
| 11 | +from starlette.datastructures import Headers |
| 12 | +from starlette.responses import JSONResponse, Response |
| 13 | + |
| 14 | +from apps.base.auth import _require_admin_payload |
| 15 | +from apps.base.file_validation import validate_file_type, validate_upload_file |
| 16 | +from apps.base.services import FileUploadService, validate_file_size |
| 17 | +from apps.base.utils import ip_limit, validate_expire_style |
| 18 | +from core.settings import settings |
| 19 | +from core.utils import sanitize_filename |
| 20 | + |
| 21 | +router = APIRouter(tags=["MCP"]) |
| 22 | + |
| 23 | +MCP_PROTOCOL_VERSION = "2025-03-26" |
| 24 | +TEXT_SHARE_MAX_BYTES = 222 * 1024 |
| 25 | +MAX_MCP_BODY_BYTES = 64 * 1024 * 1024 |
| 26 | + |
| 27 | + |
| 28 | +def _jsonrpc_error(request_id, code: int, message: str) -> dict: |
| 29 | + return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}} |
| 30 | + |
| 31 | + |
| 32 | +def _jsonrpc_result(request_id, result: dict) -> dict: |
| 33 | + return {"jsonrpc": "2.0", "id": request_id, "result": result} |
| 34 | + |
| 35 | + |
| 36 | +def _validate_origin(request: Request) -> None: |
| 37 | + """Reject browser cross-site POSTs before parsing any upload tool.""" |
| 38 | + origin = request.headers.get("origin") |
| 39 | + fetch_site = request.headers.get("sec-fetch-site", "").lower() |
| 40 | + if fetch_site == "cross-site": |
| 41 | + raise HTTPException(status_code=403, detail="跨站请求已拒绝") |
| 42 | + if not origin: |
| 43 | + return # Native MCP clients do not send Origin and use no ambient cookies. |
| 44 | + try: |
| 45 | + parsed = urlsplit(origin) |
| 46 | + host = request.headers.get("host", "").lower() |
| 47 | + if ( |
| 48 | + parsed.scheme not in {"http", "https"} |
| 49 | + or not parsed.netloc |
| 50 | + or parsed.netloc.lower() != host |
| 51 | + or parsed.username is not None |
| 52 | + or parsed.password is not None |
| 53 | + or parsed.path not in {"", "/"} |
| 54 | + or parsed.query |
| 55 | + or parsed.fragment |
| 56 | + ): |
| 57 | + raise ValueError("origin mismatch") |
| 58 | + except (ValueError, TypeError): |
| 59 | + raise HTTPException(status_code=403, detail="跨站请求已拒绝") |
| 60 | + |
| 61 | + |
| 62 | +async def _read_limited_body(request: Request) -> bytes: |
| 63 | + max_size = min( |
| 64 | + MAX_MCP_BODY_BYTES, |
| 65 | + max(1024 * 1024, int(settings.upload_size * 4 / 3) + 256 * 1024), |
| 66 | + ) |
| 67 | + declared_size = request.headers.get("content-length") |
| 68 | + if declared_size: |
| 69 | + try: |
| 70 | + if int(declared_size) > max_size: |
| 71 | + raise HTTPException(status_code=413, detail="MCP 请求体过大") |
| 72 | + except ValueError: |
| 73 | + raise HTTPException(status_code=400, detail="Content-Length 无效") |
| 74 | + body = bytearray() |
| 75 | + async for chunk in request.stream(): |
| 76 | + body.extend(chunk) |
| 77 | + if len(body) > max_size: |
| 78 | + raise HTTPException(status_code=413, detail="MCP 请求体过大") |
| 79 | + return bytes(body) |
| 80 | + |
| 81 | + |
| 82 | +def _tool_definitions() -> list[dict]: |
| 83 | + return [ |
| 84 | + { |
| 85 | + "name": "share_text", |
| 86 | + "description": "将文本快速上传到 FileCodeBox 并创建分享链接。", |
| 87 | + "inputSchema": { |
| 88 | + "type": "object", |
| 89 | + "properties": { |
| 90 | + "text": {"type": "string", "description": "要分享的文本"}, |
| 91 | + "expire_value": {"type": "integer", "minimum": 1, "default": 1}, |
| 92 | + "expire_style": {"type": "string", "enum": ["day", "hour", "minute", "forever", "count"], "default": "day"}, |
| 93 | + }, |
| 94 | + "required": ["text"], |
| 95 | + }, |
| 96 | + }, |
| 97 | + { |
| 98 | + "name": "share_file", |
| 99 | + "description": "将 Base64 编码的文件上传到 FileCodeBox 并创建分享链接。", |
| 100 | + "inputSchema": { |
| 101 | + "type": "object", |
| 102 | + "properties": { |
| 103 | + "filename": {"type": "string", "description": "文件名"}, |
| 104 | + "content_base64": {"type": "string", "description": "文件内容的标准 Base64 编码"}, |
| 105 | + "content_type": {"type": "string", "default": "application/octet-stream"}, |
| 106 | + "expire_value": {"type": "integer", "minimum": 1, "default": 1}, |
| 107 | + "expire_style": {"type": "string", "enum": ["day", "hour", "minute", "forever", "count"], "default": "day"}, |
| 108 | + }, |
| 109 | + "required": ["filename", "content_base64"], |
| 110 | + }, |
| 111 | + }, |
| 112 | + ] |
| 113 | + |
| 114 | + |
| 115 | +def _share_result(request: Request, code: str, name: str) -> dict: |
| 116 | + base_url = str(request.base_url).rstrip("/") |
| 117 | + share_url = f"{base_url}/#/?code={quote(code, safe='')}" |
| 118 | + markdown_name = html.escape(name).replace("[", "\\[").replace("]", "\\]") |
| 119 | + return { |
| 120 | + "code": code, |
| 121 | + "name": name, |
| 122 | + "url": share_url, |
| 123 | + "markdown": f"[{markdown_name}]({share_url})", |
| 124 | + } |
| 125 | + |
| 126 | + |
| 127 | +async def _call_tool(request: Request, tool_name: str, arguments: dict) -> dict: |
| 128 | + authorization = request.headers.get("authorization", "") |
| 129 | + if settings.mcp_require_token or not settings.open_upload: |
| 130 | + _require_admin_payload(authorization) |
| 131 | + ip = ip_limit["upload"](request) |
| 132 | + |
| 133 | + if tool_name == "share_text": |
| 134 | + text = arguments.get("text") |
| 135 | + if not isinstance(text, str): |
| 136 | + raise ValueError("text 必须是字符串") |
| 137 | + if len(text.encode("utf-8")) > TEXT_SHARE_MAX_BYTES: |
| 138 | + raise ValueError("内容过多,请改用文件分享") |
| 139 | + expire_value = int(arguments.get("expire_value", 1)) |
| 140 | + expire_style = str(arguments.get("expire_style", "day")) |
| 141 | + if expire_value < 1: |
| 142 | + raise ValueError("expire_value 必须大于 0") |
| 143 | + validate_expire_style(expire_style) |
| 144 | + code = await FileUploadService.create_text_share(text, expire_value, expire_style) |
| 145 | + ip_limit["upload"].add_ip(ip) |
| 146 | + return _share_result(request, code, "Text") |
| 147 | + |
| 148 | + if tool_name == "share_file": |
| 149 | + filename = arguments.get("filename") |
| 150 | + encoded_content = arguments.get("content_base64") |
| 151 | + content_type = str(arguments.get("content_type", "application/octet-stream")) |
| 152 | + if not isinstance(filename, str) or not filename.strip(): |
| 153 | + raise ValueError("filename 不能为空") |
| 154 | + if not isinstance(encoded_content, str): |
| 155 | + raise ValueError("content_base64 必须是字符串") |
| 156 | + try: |
| 157 | + content = base64.b64decode(encoded_content, validate=True) |
| 158 | + except (ValueError, binascii.Error): |
| 159 | + raise ValueError("content_base64 不是有效的标准 Base64") |
| 160 | + safe_name = await sanitize_filename(filename.rsplit("/", 1)[-1].rsplit("\\", 1)[-1]) |
| 161 | + validate_file_type(safe_name, content_type) |
| 162 | + upload = UploadFile(filename=safe_name, file=io.BytesIO(content), size=len(content), headers=Headers({"content-type": content_type})) |
| 163 | + size = await validate_file_size(upload, settings.upload_size) |
| 164 | + await validate_upload_file(upload) |
| 165 | + expire_value = int(arguments.get("expire_value", 1)) |
| 166 | + expire_style = str(arguments.get("expire_style", "day")) |
| 167 | + if expire_value < 1: |
| 168 | + raise ValueError("expire_value 必须大于 0") |
| 169 | + validate_expire_style(expire_style) |
| 170 | + share = await FileUploadService.create_file_share(upload, size=size, expire_value=expire_value, expire_style=expire_style) |
| 171 | + ip_limit["upload"].add_ip(ip) |
| 172 | + return _share_result(request, share["code"], share["name"]) |
| 173 | + |
| 174 | + raise LookupError(f"未知工具:{tool_name}") |
| 175 | + |
| 176 | + |
| 177 | +@router.post("/mcp", include_in_schema=False) |
| 178 | +async def mcp_endpoint(request: Request): |
| 179 | + _validate_origin(request) |
| 180 | + media_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower() |
| 181 | + if media_type != "application/json": |
| 182 | + raise HTTPException(status_code=415, detail="MCP 请求必须使用 application/json") |
| 183 | + try: |
| 184 | + message = json.loads(await _read_limited_body(request)) |
| 185 | + except (json.JSONDecodeError, UnicodeDecodeError): |
| 186 | + return JSONResponse(_jsonrpc_error(None, -32700, "Parse error"), status_code=400) |
| 187 | + if not isinstance(message, dict) or message.get("jsonrpc") != "2.0" or not isinstance(message.get("method"), str): |
| 188 | + return JSONResponse(_jsonrpc_error(message.get("id") if isinstance(message, dict) else None, -32600, "Invalid Request"), status_code=400) |
| 189 | + |
| 190 | + request_id = message.get("id") |
| 191 | + method = message["method"] |
| 192 | + if request_id is None and method.startswith("notifications/"): |
| 193 | + return Response(status_code=202) |
| 194 | + try: |
| 195 | + if method == "initialize": |
| 196 | + result = { |
| 197 | + "protocolVersion": MCP_PROTOCOL_VERSION, |
| 198 | + "capabilities": {"tools": {"listChanged": False}}, |
| 199 | + "serverInfo": {"name": "filecodebox", "version": "1.0.0"}, |
| 200 | + } |
| 201 | + elif method == "ping": |
| 202 | + result = {} |
| 203 | + elif method == "tools/list": |
| 204 | + result = {"tools": _tool_definitions()} |
| 205 | + elif method == "tools/call": |
| 206 | + params = message.get("params") |
| 207 | + if not isinstance(params, dict) or not isinstance(params.get("name"), str): |
| 208 | + return JSONResponse(_jsonrpc_error(request_id, -32602, "Invalid params")) |
| 209 | + arguments = params.get("arguments", {}) |
| 210 | + if not isinstance(arguments, dict): |
| 211 | + return JSONResponse(_jsonrpc_error(request_id, -32602, "Invalid params")) |
| 212 | + try: |
| 213 | + tool_value = await _call_tool(request, params["name"], arguments) |
| 214 | + result = {"content": [{"type": "text", "text": json.dumps(tool_value, ensure_ascii=False)}], "structuredContent": tool_value} |
| 215 | + except LookupError as exc: |
| 216 | + return JSONResponse(_jsonrpc_error(request_id, -32602, str(exc))) |
| 217 | + except HTTPException as exc: |
| 218 | + if exc.status_code in {401, 403}: |
| 219 | + raise |
| 220 | + result = {"content": [{"type": "text", "text": str(exc.detail)}], "isError": True} |
| 221 | + except (TypeError, ValueError) as exc: |
| 222 | + result = {"content": [{"type": "text", "text": str(exc)}], "isError": True} |
| 223 | + else: |
| 224 | + return JSONResponse(_jsonrpc_error(request_id, -32601, "Method not found")) |
| 225 | + return JSONResponse(_jsonrpc_result(request_id, result), headers={"MCP-Protocol-Version": MCP_PROTOCOL_VERSION}) |
| 226 | + except HTTPException as exc: |
| 227 | + return JSONResponse( |
| 228 | + _jsonrpc_error(request_id, -32001 if exc.status_code == 401 else -32003, str(exc.detail)), |
| 229 | + status_code=exc.status_code, |
| 230 | + ) |
| 231 | + |
| 232 | + |
| 233 | +_SAFE_TAGS = { |
| 234 | + "a", "abbr", "article", "b", "blockquote", "br", "caption", "code", "dd", "del", "details", |
| 235 | + "div", "dl", "dt", "em", "figcaption", "figure", "h1", "h2", "h3", "h4", "h5", "h6", |
| 236 | + "hr", "i", "img", "li", "main", "mark", "ol", "p", "pre", "s", "section", "small", "span", |
| 237 | + "strong", "sub", "summary", "sup", "table", "tbody", "td", "th", "thead", "tr", "u", "ul", |
| 238 | +} |
| 239 | +_VOID_TAGS = {"br", "hr", "img"} |
| 240 | +_DROP_CONTENT_TAGS = {"script", "style", "iframe", "object", "embed", "svg", "math", "form", "template"} |
| 241 | +_SAFE_ATTRS = {"alt", "title", "class", "id", "colspan", "rowspan", "width", "height", "scope", "dir", "lang"} |
| 242 | + |
| 243 | + |
| 244 | +class _HTMLPreviewSanitizer(HTMLParser): |
| 245 | + """Whitelist-only HTML serializer; scripts, active embeds and URL attrs are removed.""" |
| 246 | + |
| 247 | + def __init__(self): |
| 248 | + super().__init__(convert_charrefs=True) |
| 249 | + self.output: list[str] = [] |
| 250 | + self.drop_depth = 0 |
| 251 | + |
| 252 | + def handle_starttag(self, tag, attrs): |
| 253 | + tag = tag.lower() |
| 254 | + if self.drop_depth: |
| 255 | + if tag in _DROP_CONTENT_TAGS: |
| 256 | + self.drop_depth += 1 |
| 257 | + return |
| 258 | + if tag in _DROP_CONTENT_TAGS: |
| 259 | + self.drop_depth = 1 |
| 260 | + return |
| 261 | + if tag not in _SAFE_TAGS: |
| 262 | + return |
| 263 | + safe_attrs = [] |
| 264 | + for name, value in attrs: |
| 265 | + name = name.lower() |
| 266 | + if value is None or name.startswith("on") or name not in _SAFE_ATTRS: |
| 267 | + continue |
| 268 | + safe_attrs.append(f' {name}="{html.escape(value, quote=True)}"') |
| 269 | + self.output.append(f"<{tag}{''.join(safe_attrs)}>") |
| 270 | + |
| 271 | + def handle_startendtag(self, tag, attrs): |
| 272 | + self.handle_starttag(tag, attrs) |
| 273 | + if tag.lower() in _SAFE_TAGS and tag.lower() not in _VOID_TAGS: |
| 274 | + self.handle_endtag(tag) |
| 275 | + |
| 276 | + def handle_endtag(self, tag): |
| 277 | + tag = tag.lower() |
| 278 | + if self.drop_depth: |
| 279 | + if tag in _DROP_CONTENT_TAGS: |
| 280 | + self.drop_depth -= 1 |
| 281 | + return |
| 282 | + if tag in _SAFE_TAGS and tag not in _VOID_TAGS: |
| 283 | + self.output.append(f"</{tag}>") |
| 284 | + |
| 285 | + def handle_data(self, data): |
| 286 | + if not self.drop_depth: |
| 287 | + self.output.append(html.escape(data)) |
| 288 | + |
| 289 | + def handle_entityref(self, name): |
| 290 | + if not self.drop_depth: |
| 291 | + self.output.append(f"&{html.escape(name)};") |
| 292 | + |
| 293 | + def handle_charref(self, name): |
| 294 | + if not self.drop_depth: |
| 295 | + self.output.append(f"&#{html.escape(name)};") |
| 296 | + |
| 297 | + |
| 298 | +def sanitize_html_preview(source: str) -> str: |
| 299 | + parser = _HTMLPreviewSanitizer() |
| 300 | + parser.feed(source) |
| 301 | + parser.close() |
| 302 | + return "<!doctype html><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><body>" + "".join(parser.output) + "</body>" |
0 commit comments