mirror of
https://github.com/vastsa/FileCodeBox.git
synced 2026-11-25 16:51:08 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1fee1edff | ||
|
|
65f4929d40 | ||
|
|
40f22de7f8 | ||
|
|
da374b4595 | ||
|
|
d3f9e7902c | ||
|
|
2f5eab18b1 | ||
|
|
6bb1ef06c1 | ||
|
|
63e72c1455 |
No files matched your search
@@ -1,3 +1,3 @@
|
|||||||
{
|
{
|
||||||
".": "2.7.1"
|
".": "2.8.3"
|
||||||
}
|
}
|
||||||
+1
-1
@@ -54,7 +54,7 @@ RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
|
|||||||
echo 'Asia/Shanghai' > /etc/timezone
|
echo 'Asia/Shanghai' > /etc/timezone
|
||||||
|
|
||||||
# 从构建阶段复制编译好的前端主题
|
# 从构建阶段复制编译好的前端主题
|
||||||
COPY --from=frontend-builder /build/fronted-2024/dist ./themes/2024
|
COPY --from=frontend-builder /build/FileCodeBox/themes/2024 ./themes/2024
|
||||||
COPY --from=frontend-builder /build/fronted-2023/dist ./themes/2023
|
COPY --from=frontend-builder /build/fronted-2023/dist ./themes/2023
|
||||||
|
|
||||||
# 安装系统安全更新 + Python 依赖
|
# 安装系统安全更新 + Python 依赖
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ class ConfigService:
|
|||||||
"max_save_seconds",
|
"max_save_seconds",
|
||||||
"onedrive_proxy",
|
"onedrive_proxy",
|
||||||
"open_upload",
|
"open_upload",
|
||||||
|
"mcp_require_token",
|
||||||
"port",
|
"port",
|
||||||
"s3_proxy",
|
"s3_proxy",
|
||||||
"server_port",
|
"server_port",
|
||||||
|
|||||||
@@ -0,0 +1,231 @@
|
|||||||
|
"""Stateless MCP Streamable HTTP endpoint for quick share uploads."""
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
import html
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import quote, urlsplit
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Request, UploadFile
|
||||||
|
from starlette.datastructures import Headers
|
||||||
|
from starlette.responses import JSONResponse, Response
|
||||||
|
|
||||||
|
from apps.base.auth import _require_admin_payload
|
||||||
|
from apps.base.file_validation import validate_file_type, validate_upload_file
|
||||||
|
from apps.base.services import FileUploadService, validate_file_size
|
||||||
|
from apps.base.utils import ip_limit, validate_expire_style
|
||||||
|
from core.settings import settings
|
||||||
|
from core.utils import sanitize_filename
|
||||||
|
|
||||||
|
router = APIRouter(tags=["MCP"])
|
||||||
|
|
||||||
|
MCP_PROTOCOL_VERSION = "2025-03-26"
|
||||||
|
TEXT_SHARE_MAX_BYTES = 222 * 1024
|
||||||
|
MAX_MCP_BODY_BYTES = 64 * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
def _jsonrpc_error(request_id, code: int, message: str) -> dict:
|
||||||
|
return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
|
||||||
|
|
||||||
|
|
||||||
|
def _jsonrpc_result(request_id, result: dict) -> dict:
|
||||||
|
return {"jsonrpc": "2.0", "id": request_id, "result": result}
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_origin(request: Request) -> None:
|
||||||
|
"""Reject browser cross-site POSTs before parsing any upload tool."""
|
||||||
|
origin = request.headers.get("origin")
|
||||||
|
fetch_site = request.headers.get("sec-fetch-site", "").lower()
|
||||||
|
if fetch_site == "cross-site":
|
||||||
|
raise HTTPException(status_code=403, detail="跨站请求已拒绝")
|
||||||
|
if not origin:
|
||||||
|
return # Native MCP clients do not send Origin and use no ambient cookies.
|
||||||
|
try:
|
||||||
|
parsed = urlsplit(origin)
|
||||||
|
host = request.headers.get("host", "").lower()
|
||||||
|
if (
|
||||||
|
parsed.scheme not in {"http", "https"}
|
||||||
|
or not parsed.netloc
|
||||||
|
or parsed.netloc.lower() != host
|
||||||
|
or parsed.username is not None
|
||||||
|
or parsed.password is not None
|
||||||
|
or parsed.path not in {"", "/"}
|
||||||
|
or parsed.query
|
||||||
|
or parsed.fragment
|
||||||
|
):
|
||||||
|
raise ValueError("origin mismatch")
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
raise HTTPException(status_code=403, detail="跨站请求已拒绝")
|
||||||
|
|
||||||
|
|
||||||
|
async def _read_limited_body(request: Request) -> bytes:
|
||||||
|
max_size = min(
|
||||||
|
MAX_MCP_BODY_BYTES,
|
||||||
|
max(1024 * 1024, int(settings.upload_size * 4 / 3) + 256 * 1024),
|
||||||
|
)
|
||||||
|
declared_size = request.headers.get("content-length")
|
||||||
|
if declared_size:
|
||||||
|
try:
|
||||||
|
if int(declared_size) > max_size:
|
||||||
|
raise HTTPException(status_code=413, detail="MCP 请求体过大")
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(status_code=400, detail="Content-Length 无效")
|
||||||
|
body = bytearray()
|
||||||
|
async for chunk in request.stream():
|
||||||
|
body.extend(chunk)
|
||||||
|
if len(body) > max_size:
|
||||||
|
raise HTTPException(status_code=413, detail="MCP 请求体过大")
|
||||||
|
return bytes(body)
|
||||||
|
|
||||||
|
|
||||||
|
def _tool_definitions() -> list[dict]:
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"name": "share_text",
|
||||||
|
"description": "将文本快速上传到 FileCodeBox 并创建分享链接。",
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"text": {"type": "string", "description": "要分享的文本"},
|
||||||
|
"expire_value": {"type": "integer", "minimum": 1, "default": 1},
|
||||||
|
"expire_style": {"type": "string", "enum": ["day", "hour", "minute", "forever", "count"], "default": "day"},
|
||||||
|
},
|
||||||
|
"required": ["text"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "share_file",
|
||||||
|
"description": "将 Base64 编码的文件上传到 FileCodeBox 并创建分享链接。",
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"filename": {"type": "string", "description": "文件名"},
|
||||||
|
"content_base64": {"type": "string", "description": "文件内容的标准 Base64 编码"},
|
||||||
|
"content_type": {"type": "string", "default": "application/octet-stream"},
|
||||||
|
"expire_value": {"type": "integer", "minimum": 1, "default": 1},
|
||||||
|
"expire_style": {"type": "string", "enum": ["day", "hour", "minute", "forever", "count"], "default": "day"},
|
||||||
|
},
|
||||||
|
"required": ["filename", "content_base64"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _share_result(request: Request, code: str, name: str) -> dict:
|
||||||
|
base_url = str(request.base_url).rstrip("/")
|
||||||
|
share_url = f"{base_url}/#/?code={quote(code, safe='')}"
|
||||||
|
markdown_name = html.escape(name).replace("[", "\\[").replace("]", "\\]")
|
||||||
|
return {
|
||||||
|
"code": code,
|
||||||
|
"name": name,
|
||||||
|
"url": share_url,
|
||||||
|
"markdown": f"[{markdown_name}]({share_url})",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def _call_tool(request: Request, tool_name: str, arguments: dict) -> dict:
|
||||||
|
authorization = request.headers.get("authorization", "")
|
||||||
|
if settings.mcp_require_token or not settings.open_upload:
|
||||||
|
_require_admin_payload(authorization)
|
||||||
|
ip = ip_limit["upload"](request)
|
||||||
|
|
||||||
|
if tool_name == "share_text":
|
||||||
|
text = arguments.get("text")
|
||||||
|
if not isinstance(text, str):
|
||||||
|
raise ValueError("text 必须是字符串")
|
||||||
|
if len(text.encode("utf-8")) > TEXT_SHARE_MAX_BYTES:
|
||||||
|
raise ValueError("内容过多,请改用文件分享")
|
||||||
|
expire_value = int(arguments.get("expire_value", 1))
|
||||||
|
expire_style = str(arguments.get("expire_style", "day"))
|
||||||
|
if expire_value < 1:
|
||||||
|
raise ValueError("expire_value 必须大于 0")
|
||||||
|
validate_expire_style(expire_style)
|
||||||
|
code = await FileUploadService.create_text_share(text, expire_value, expire_style)
|
||||||
|
ip_limit["upload"].add_ip(ip)
|
||||||
|
return _share_result(request, code, "Text")
|
||||||
|
|
||||||
|
if tool_name == "share_file":
|
||||||
|
filename = arguments.get("filename")
|
||||||
|
encoded_content = arguments.get("content_base64")
|
||||||
|
content_type = str(arguments.get("content_type", "application/octet-stream"))
|
||||||
|
if not isinstance(filename, str) or not filename.strip():
|
||||||
|
raise ValueError("filename 不能为空")
|
||||||
|
if not isinstance(encoded_content, str):
|
||||||
|
raise ValueError("content_base64 必须是字符串")
|
||||||
|
try:
|
||||||
|
content = base64.b64decode(encoded_content, validate=True)
|
||||||
|
except (ValueError, binascii.Error):
|
||||||
|
raise ValueError("content_base64 不是有效的标准 Base64")
|
||||||
|
safe_name = await sanitize_filename(filename.rsplit("/", 1)[-1].rsplit("\\", 1)[-1])
|
||||||
|
validate_file_type(safe_name, content_type)
|
||||||
|
upload = UploadFile(filename=safe_name, file=io.BytesIO(content), size=len(content), headers=Headers({"content-type": content_type}))
|
||||||
|
size = await validate_file_size(upload, settings.upload_size)
|
||||||
|
await validate_upload_file(upload)
|
||||||
|
expire_value = int(arguments.get("expire_value", 1))
|
||||||
|
expire_style = str(arguments.get("expire_style", "day"))
|
||||||
|
if expire_value < 1:
|
||||||
|
raise ValueError("expire_value 必须大于 0")
|
||||||
|
validate_expire_style(expire_style)
|
||||||
|
share = await FileUploadService.create_file_share(upload, size=size, expire_value=expire_value, expire_style=expire_style)
|
||||||
|
ip_limit["upload"].add_ip(ip)
|
||||||
|
return _share_result(request, share["code"], share["name"])
|
||||||
|
|
||||||
|
raise LookupError(f"未知工具:{tool_name}")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/mcp", include_in_schema=False)
|
||||||
|
async def mcp_endpoint(request: Request):
|
||||||
|
_validate_origin(request)
|
||||||
|
media_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||||
|
if media_type != "application/json":
|
||||||
|
raise HTTPException(status_code=415, detail="MCP 请求必须使用 application/json")
|
||||||
|
try:
|
||||||
|
message = json.loads(await _read_limited_body(request))
|
||||||
|
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||||
|
return JSONResponse(_jsonrpc_error(None, -32700, "Parse error"), status_code=400)
|
||||||
|
if not isinstance(message, dict) or message.get("jsonrpc") != "2.0" or not isinstance(message.get("method"), str):
|
||||||
|
return JSONResponse(_jsonrpc_error(message.get("id") if isinstance(message, dict) else None, -32600, "Invalid Request"), status_code=400)
|
||||||
|
|
||||||
|
request_id = message.get("id")
|
||||||
|
method = message["method"]
|
||||||
|
if request_id is None and method.startswith("notifications/"):
|
||||||
|
return Response(status_code=202)
|
||||||
|
result: dict[str, Any] = {}
|
||||||
|
try:
|
||||||
|
if method == "initialize":
|
||||||
|
result = {
|
||||||
|
"protocolVersion": MCP_PROTOCOL_VERSION,
|
||||||
|
"capabilities": {"tools": {"listChanged": False}},
|
||||||
|
"serverInfo": {"name": "filecodebox", "version": "1.0.0"},
|
||||||
|
}
|
||||||
|
elif method == "ping":
|
||||||
|
result = {}
|
||||||
|
elif method == "tools/list":
|
||||||
|
result = {"tools": _tool_definitions()}
|
||||||
|
elif method == "tools/call":
|
||||||
|
params = message.get("params")
|
||||||
|
if not isinstance(params, dict) or not isinstance(params.get("name"), str):
|
||||||
|
return JSONResponse(_jsonrpc_error(request_id, -32602, "Invalid params"))
|
||||||
|
arguments = params.get("arguments", {})
|
||||||
|
if not isinstance(arguments, dict):
|
||||||
|
return JSONResponse(_jsonrpc_error(request_id, -32602, "Invalid params"))
|
||||||
|
try:
|
||||||
|
tool_value = await _call_tool(request, params["name"], arguments)
|
||||||
|
result = {"content": [{"type": "text", "text": json.dumps(tool_value, ensure_ascii=False)}], "structuredContent": tool_value}
|
||||||
|
except LookupError as exc:
|
||||||
|
return JSONResponse(_jsonrpc_error(request_id, -32602, str(exc)))
|
||||||
|
except HTTPException as exc:
|
||||||
|
if exc.status_code in {401, 403}:
|
||||||
|
raise
|
||||||
|
result = {"content": [{"type": "text", "text": str(exc.detail)}], "isError": True}
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
result = {"content": [{"type": "text", "text": str(exc)}], "isError": True}
|
||||||
|
else:
|
||||||
|
return JSONResponse(_jsonrpc_error(request_id, -32601, "Method not found"))
|
||||||
|
return JSONResponse(_jsonrpc_result(request_id, result), headers={"MCP-Protocol-Version": MCP_PROTOCOL_VERSION})
|
||||||
|
except HTTPException as exc:
|
||||||
|
return JSONResponse(
|
||||||
|
_jsonrpc_error(request_id, -32001 if exc.status_code == 401 else -32003, str(exc.detail)),
|
||||||
|
status_code=exc.status_code,
|
||||||
|
)
|
||||||
@@ -194,6 +194,8 @@ async def post_file_metadata(
|
|||||||
return APIResponse(detail=build_file_metadata(file_code))
|
return APIResponse(detail=build_file_metadata(file_code))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@share_api.get("/select/")
|
@share_api.get("/select/")
|
||||||
async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
|
async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
|
||||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ DEFAULT_CONFIG: dict[str, Any] = {
|
|||||||
"jwt_secret": "",
|
"jwt_secret": "",
|
||||||
"admin_session_expire": ADMIN_SESSION_EXPIRE_DEFAULT,
|
"admin_session_expire": ADMIN_SESSION_EXPIRE_DEFAULT,
|
||||||
"open_upload": 1,
|
"open_upload": 1,
|
||||||
|
"mcp_require_token": 0,
|
||||||
"upload_size": 1024 * 1024 * 10,
|
"upload_size": 1024 * 1024 * 10,
|
||||||
"allowed_file_types": ["*"],
|
"allowed_file_types": ["*"],
|
||||||
"expire_style": ["day", "hour", "minute", "forever", "count"],
|
"expire_style": ["day", "hour", "minute", "forever", "count"],
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
version: "3"
|
version: "3"
|
||||||
services:
|
services:
|
||||||
file-code-box:
|
file-code-box:
|
||||||
image: lanol/filecodebox:2.7.1 # x-release-please-version
|
image: lanol/filecodebox:2.8.3 # x-release-please-version
|
||||||
volumes:
|
volumes:
|
||||||
- fcb-data:/app/data:rw
|
- fcb-data:/app/data:rw
|
||||||
# NAS 已有文件:把共享目录挂到 /app/data/local,即可在后台「本地分享」里生成提取码,无需再上传
|
# NAS 已有文件:把共享目录挂到 /app/data/local,即可在后台「本地分享」里生成提取码,无需再上传
|
||||||
|
|||||||
@@ -1,5 +1,33 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## [2.8.3](https://github.com/vastsa/FileCodeBox/compare/v2.8.2...v2.8.3) (2026-10-10)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* remove HTML preview endpoint ([65f4929](https://github.com/vastsa/FileCodeBox/commit/65f4929d405408e1c9e58127e0097f8b78b1819f))
|
||||||
|
|
||||||
|
## [2.8.2](https://github.com/vastsa/FileCodeBox/compare/v2.8.1...v2.8.2) (2026-10-10)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* type MCP protocol results ([da374b4](https://github.com/vastsa/FileCodeBox/commit/da374b459537ee079e1d03da121a935c8fb18f0e))
|
||||||
|
|
||||||
|
## [2.8.1](https://github.com/vastsa/FileCodeBox/compare/v2.8.0...v2.8.1) (2026-10-10)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* restore lint and Docker theme build ([2f5eab1](https://github.com/vastsa/FileCodeBox/commit/2f5eab18b1ab28fcb4f416248076ce574998d718))
|
||||||
|
|
||||||
|
## [2.8.0](https://github.com/vastsa/FileCodeBox/compare/v2.7.1...v2.8.0) (2026-10-10)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* add MCP quick share and safe HTML preview ([63e72c1](https://github.com/vastsa/FileCodeBox/commit/63e72c145576d169265e4fa8cf373e33531a06a0))
|
||||||
|
|
||||||
## [2.7.1](https://github.com/vastsa/FileCodeBox/compare/v2.7.0...v2.7.1) (2026-09-19)
|
## [2.7.1](https://github.com/vastsa/FileCodeBox/compare/v2.7.0...v2.7.1) (2026-09-19)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
<!-- Current release: 2.7.1 x-release-please-version -->
|
<!-- Current release: 2.8.3 x-release-please-version -->
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -42,7 +42,7 @@ docker run -d --restart unless-stopped \
|
|||||||
--log-opt max-size=10m \
|
--log-opt max-size=10m \
|
||||||
--log-opt max-file=3 \
|
--log-opt max-file=3 \
|
||||||
--name filecodebox \
|
--name filecodebox \
|
||||||
lanol/filecodebox:2.7.1 # x-release-please-version
|
lanol/filecodebox:2.8.3 # x-release-please-version
|
||||||
```
|
```
|
||||||
|
|
||||||
Open `http://localhost:12345` and complete the first-run setup.
|
Open `http://localhost:12345` and complete the first-run setup.
|
||||||
|
|||||||
+1
-1
@@ -42,7 +42,7 @@ docker run -d --restart unless-stopped \
|
|||||||
--log-opt max-size=10m \
|
--log-opt max-size=10m \
|
||||||
--log-opt max-file=3 \
|
--log-opt max-file=3 \
|
||||||
--name filecodebox \
|
--name filecodebox \
|
||||||
lanol/filecodebox:2.7.1 # x-release-please-version
|
lanol/filecodebox:2.8.3 # x-release-please-version
|
||||||
```
|
```
|
||||||
|
|
||||||
打开 `http://localhost:12345`,按引导完成首次初始化。
|
打开 `http://localhost:12345`,按引导完成首次初始化。
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ from apps.base.tasks import (
|
|||||||
delete_expire_files,
|
delete_expire_files,
|
||||||
)
|
)
|
||||||
from apps.base.views import share_api, chunk_api, presign_api
|
from apps.base.views import share_api, chunk_api, presign_api
|
||||||
|
from apps.base.mcp import router as mcp_router
|
||||||
from core.database import db_startup_lock, get_db_config, init_db
|
from core.database import db_startup_lock, get_db_config, init_db
|
||||||
from core.errors import StorageError
|
from core.errors import StorageError
|
||||||
from core.logger import get_log_level_name, is_access_log_enabled, logger
|
from core.logger import get_log_level_name, is_access_log_enabled, logger
|
||||||
@@ -139,6 +140,7 @@ app.include_router(presign_api)
|
|||||||
app.include_router(presign_api, prefix="/api")
|
app.include_router(presign_api, prefix="/api")
|
||||||
app.include_router(admin_api)
|
app.include_router(admin_api)
|
||||||
app.include_router(pages_router)
|
app.include_router(pages_router)
|
||||||
|
app.include_router(mcp_router)
|
||||||
|
|
||||||
# 404 时返回主题首页(index 兼任 exception handler 与 GET / 路由)
|
# 404 时返回主题首页(index 兼任 exception handler 与 GET / 路由)
|
||||||
app.add_exception_handler(404, not_found_handler)
|
app.add_exception_handler(404, not_found_handler)
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ docker run -d --restart unless-stopped \
|
|||||||
--log-opt max-size=10m \
|
--log-opt max-size=10m \
|
||||||
--log-opt max-file=3 \
|
--log-opt max-file=3 \
|
||||||
--name filecodebox \
|
--name filecodebox \
|
||||||
lanol/filecodebox:2.7.1 # x-release-please-version
|
lanol/filecodebox:2.8.3 # x-release-please-version
|
||||||
```
|
```
|
||||||
|
|
||||||
访问 `http://localhost:12345`,完成首次初始化。生产环境建议固定版本号;`latest` 指向最新正式版。
|
访问 `http://localhost:12345`,完成首次初始化。生产环境建议固定版本号;`latest` 指向最新正式版。
|
||||||
|
|||||||
+1
-1
@@ -32,7 +32,7 @@ docker run -d --restart unless-stopped \
|
|||||||
--log-opt max-size=10m \
|
--log-opt max-size=10m \
|
||||||
--log-opt max-file=3 \
|
--log-opt max-file=3 \
|
||||||
--name filecodebox \
|
--name filecodebox \
|
||||||
lanol/filecodebox:2.7.1 # x-release-please-version
|
lanol/filecodebox:2.8.3 # x-release-please-version
|
||||||
```
|
```
|
||||||
|
|
||||||
Open `http://localhost:12345` and complete first-run setup. Pin a version in production; `latest` tracks the newest stable release.
|
Open `http://localhost:12345` and complete first-run setup. Pin a version in production; `latest` tracks the newest stable release.
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from apps.base.models import KeyValue
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_mcp_initialize_and_list_tools(initialized_client):
|
||||||
|
init_response = await initialized_client.post(
|
||||||
|
"/mcp",
|
||||||
|
json={"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}},
|
||||||
|
)
|
||||||
|
assert init_response.status_code == 200
|
||||||
|
assert init_response.json()["result"]["capabilities"]["tools"]
|
||||||
|
|
||||||
|
tools_response = await initialized_client.post(
|
||||||
|
"/mcp", json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"}
|
||||||
|
)
|
||||||
|
assert tools_response.status_code == 200
|
||||||
|
assert {tool["name"] for tool in tools_response.json()["result"]["tools"]} == {
|
||||||
|
"share_text",
|
||||||
|
"share_file",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_mcp_rejects_cross_origin_requests(initialized_client):
|
||||||
|
response = await initialized_client.post(
|
||||||
|
"/mcp",
|
||||||
|
json={"jsonrpc": "2.0", "id": 3, "method": "tools/list"},
|
||||||
|
headers={"origin": "https://attacker.invalid"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_mcp_token_can_be_required(initialized_client):
|
||||||
|
from core.settings import settings
|
||||||
|
|
||||||
|
record = await KeyValue.filter(key="settings").first()
|
||||||
|
config = dict(record.value)
|
||||||
|
config["mcp_require_token"] = 1
|
||||||
|
record.value = config
|
||||||
|
await record.save()
|
||||||
|
settings.user_config = config
|
||||||
|
|
||||||
|
response = await initialized_client.post(
|
||||||
|
"/mcp",
|
||||||
|
json={
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 4,
|
||||||
|
"method": "tools/call",
|
||||||
|
"params": {"name": "share_text", "arguments": {"text": "private"}},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert response.status_code == 401
|
||||||
|
from apps.admin.dependencies import create_token
|
||||||
|
|
||||||
|
token = create_token({"is_admin": True})
|
||||||
|
authorized = await initialized_client.post(
|
||||||
|
"/mcp",
|
||||||
|
headers={"authorization": f"Bearer {token}"},
|
||||||
|
json={
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 6,
|
||||||
|
"method": "tools/call",
|
||||||
|
"params": {"name": "share_text", "arguments": {"text": "private"}},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert authorized.status_code == 200
|
||||||
|
assert "/#/?code=" in authorized.json()["result"]["structuredContent"]["url"]
|
||||||
Reference in new issue
Block a user