From a85f7b7bbc29c424dcbc7f8f1e189f3602de00d9 Mon Sep 17 00:00:00 2001 From: jinghui Date: Sat, 14 Nov 2026 11:03:20 +0800 Subject: [PATCH] =?UTF-8?q?feat(mcp):=20=E6=AF=8F=20IP=20=E6=AF=8F?= =?UTF-8?q?=E6=97=A5=205=20=E6=AC=A1=E8=B0=83=E7=94=A8=E9=99=90=E6=B5=81?= =?UTF-8?q?=20+=20=E6=95=99=E7=A8=8B=E6=9B=B4=E6=96=B0=E9=99=90=E6=B5=81?= =?UTF-8?q?=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - _AuthMiddleware 新增 POST /mcp 按客户端 IP 日配额(X-Forwarded-For 优先,UTC+8 日期键,内存存储重启清零,env MCP_DAILY_LIMIT 默认 5) - 超限返回 429 + Retry-After: 86400,限流只计 /mcp POST,/health /out/* 不受限 - mcp-guide.md 端点小节新增限流规则 + 常见问题第 9 条 429 排查 - 实测:前 5 次放行、第 6 次 429 --- mcp/server.py | 114 ++++++++++++++++++++++++++++------- public/articles/mcp-guide.md | 6 ++ 2 files changed, 99 insertions(+), 21 deletions(-) diff --git a/mcp/server.py b/mcp/server.py index 11e077b..8287855 100644 --- a/mcp/server.py +++ b/mcp/server.py @@ -843,12 +843,53 @@ class _AuthMiddleware: - /health 监控探针(nginx /mcp-health 转发,无法附带鉴权头) - /out/* 工具产物下载直链(zip/mp3 交人浏览器点开,无法附带鉴权头) 其余路径(含 MCP 协议端点 /mcp 与全部未知路径)必须携带 - Authorization: Bearer 。 + Authorization: Bearer *** + 额外:对 POST /mcp 按客户端 IP 做每日调用上限(默认 5 次/天/IP,env MCP_DAILY_LIMIT 可调), + 超限返回 429 Too Many Requests。 """ OPEN_EXACT = ("/health",) OPEN_PREFIX = ("/out/",) + # ---- 每 IP 每日调用计数(内存,容器重启清零;按 UTC+8 日期键重置) + DAILY_LIMIT = int(os.getenv("MCP_DAILY_LIMIT", "5")) + _rate_lock = None # 延迟初始化(事件循环启动后) + _rate_store: dict = {} + + @classmethod + def _get_lock(cls): + import asyncio + if cls._rate_lock is None: + cls._rate_lock = asyncio.Lock() + return cls._rate_lock + + @classmethod + async def _check_rate(cls, ip: str) -> tuple[bool, int]: + """返回 (allowed, used_count_after)。超限返回 (False, current_count)。""" + import asyncio + lock = cls._get_lock() + from datetime import datetime, timezone, timedelta + today = (datetime.now(timezone(timedelta(hours=8))).date().isoformat()) + async with lock: + entry = cls._rate_store.setdefault(ip, {}) + # 清理旧日期键 + for d in [k for k in entry if k != today]: + del entry[d] + used = entry.get(today, 0) + if used >= cls.DAILY_LIMIT: + return False, used + entry[today] = used + 1 + return True, entry[today] + + @staticmethod + def _client_ip(scope) -> str: + headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers", [])} + xff = headers.get("x-forwarded-for", "") + if xff: + return xff.split(",")[0].strip() + client = scope.get("client") + return client[0] if client else "unknown" + def __init__(self, app): self.app = app @@ -858,6 +899,7 @@ class _AuthMiddleware: return path = scope.get("path", "") + if path in self.OPEN_EXACT or path.startswith(self.OPEN_PREFIX): await self.app(scope, receive, send) return @@ -869,28 +911,58 @@ class _AuthMiddleware: and got.startswith("Bearer ") and hmac.compare_digest(got[7:].strip(), AUTH_TOKEN) # 恒定时间比较,防时序侧信道 ) - if authorized: - await self.app(scope, receive, send) + if not authorized: + detail = ( + "MCP_AUTH_TOKEN not configured on server (fail-closed)" + if not AUTH_TOKEN + else "missing or invalid bearer token" + ) + body = json.dumps({"ok": False, "error": "unauthorized", "detail": detail}, ensure_ascii=False).encode() + await send( + { + "type": "http.response.start", + "status": 401, + "headers": [ + (b"content-type", b"application/json"), + (b"content-length", str(len(body)).encode("ascii")), + (b"www-authenticate", b'Bearer realm="unicut-mcp", charset="UTF-8"'), + ], + } + ) + await send({"type": "http.response.body", "body": body}) return - detail = ( - "MCP_AUTH_TOKEN not configured on server (fail-closed)" - if not AUTH_TOKEN - else "missing or invalid bearer token" - ) - body = json.dumps({"ok": False, "error": "unauthorized", "detail": detail}, ensure_ascii=False).encode() - await send( - { - "type": "http.response.start", - "status": 401, - "headers": [ - (b"content-type", b"application/json"), - (b"content-length", str(len(body)).encode("ascii")), - (b"www-authenticate", b'Bearer realm="unicut-mcp", charset="UTF-8"'), - ], - } - ) - await send({"type": "http.response.body", "body": body}) + # ---- 每 IP 每日调用限流(仅 MCP 协议端点 /mcp 的 POST 计数) + if path in ("/mcp", "/mcp/") and scope.get("method", "GET").upper() == "POST": + ip = self._client_ip(scope) + allowed, used = await self._check_rate(ip) + if not allowed: + body = json.dumps( + { + "ok": False, + "error": "rate_limited", + "detail": f"该 IP 今日 MCP 调用已达上限({self.DAILY_LIMIT} 次/天),明日 00:00 重置", + "limit": self.DAILY_LIMIT, + "used": used, + "ip": ip, + }, + ensure_ascii=False, + ).encode() + await send( + { + "type": "http.response.start", + "status": 429, + "headers": [ + (b"content-type", b"application/json"), + (b"content-length", str(len(body)).encode("ascii")), + (b"retry-after", b"86400"), + ], + } + ) + await send({"type": "http.response.body", "body": body}) + return + + await self.app(scope, receive, send) if __name__ == "__main__": diff --git a/public/articles/mcp-guide.md b/public/articles/mcp-guide.md index c5398a1..b271551 100644 --- a/public/articles/mcp-guide.md +++ b/public/articles/mcp-guide.md @@ -29,6 +29,9 @@ - 令牌错误或没带 → 返回 `401 {"error":"unauthorized"}`,客户端里表现为「连接失败 / 401」 - **健康检查**:`https://cut.88531.cn/mcp-health`(返回容器健康状态 JSON) - ⚠ `/mcp/health` **不是**端点——它会被前端回退成首页 HTML,别拿它测 +- **限流**:每个客户端 IP 每天最多调用 **5 次**(按北京时间 00:00 重置,`env MCP_DAILY_LIMIT` 可调)——这是为了防止被刷爆;超限返回 `429 {"error":"rate_limited"}`,响应头带 `Retry-After: 86400`,等次日即可恢复 + - 限流只计 **POST /mcp**(真正的工具调用),`/mcp-health`、`/mcp-out/*` 下载链接不受限 + - 限流按 IP 识别(优先 `X-Forwarded-For`,反代场景下仍按真实客户端 IP 计);容器重启清零计数 ## 三、接入你的 AI 客户端(四选一) @@ -226,6 +229,9 @@ docker compose up -d --build unicut-mcp **8. AI 说「找不到 unicut 这组工具」?** 客户端没加载成功:确认配置文件路径、URL、令牌后**重启客户端**;命令行客户端可用第六节 curl 先验证服务本身是通的。 +**9. 调用提示 `429 rate_limited`(每天每 IP 5 次上限)?** +服务端对每个客户端 IP 每天最多放行 5 次 MCP 调用(按北京时间 00:00 重置)。超限后等次日再试,或让站点管理员调高 `MCP_DAILY_LIMIT` 环境变量并重建容器。注意 `/mcp-health` 与下载链接不受限。 + ## 九、相关链接 - [AI 一键出片新手教程](/article/about) —— 站内四步出片的完整操作