Spaces:
Running
Running
feat(mcp): MCP target — Gradio-MCP configs (Cursor/Claude/generic) or generated FastMCP/MCPServer stdio server (gradio_client tools / generic HTTP)
f85a714 Download backend/tests/test_mcp.py from 2Btainment/spaceforge: direct link, hf CLI and curl.
- Browser
- Download file 5.43 kB
-
https://huggingface.co/spaces/2Btainment/spaceforge/resolve/main/backend/tests/test_mcp.py
- Command line
-
hf download hf://spaces/2Btainment/spaceforge/backend/tests/test_mcp.py
-
curl -L -o test_mcp.py https://huggingface.co/spaces/2Btainment/spaceforge/resolve/main/backend/tests/test_mcp.py
5.43 kB
| """MCP target: remote Gradio-MCP configs, gradio_client stdio server, generic HTTP server.""" | |
| import json | |
| import zipfile | |
| from pathlib import Path | |
| import pytest | |
| from backend.app.converters import mcp_server as m | |
| from backend.app.converters.base import BuildContext | |
| GRADIO = { | |
| "repo_id": "gradio/hello_world", "owner": "gradio", "name": "hello_world", "title": "Hello", | |
| "sdk": "gradio", "embed_url": "https://gradio-hello-world.hf.space", | |
| } | |
| DOCKER = { | |
| "repo_id": "2Btainment/repospace", "owner": "2Btainment", "name": "repospace", "title": "RepoSpace", | |
| "sdk": "docker", "embed_url": "https://2btainment-repospace.hf.space", | |
| } | |
| INFO = { | |
| "named_endpoints": { | |
| "/predict": { | |
| "parameters": [ | |
| {"label": "name", "parameter_name": "name", "parameter_has_default": False, | |
| "type": {"type": "string"}, "python_type": {"type": "str"}, "component": "Textbox"}, | |
| {"label": "count", "parameter_name": "class", "parameter_has_default": True, | |
| "parameter_default": 3, "type": {"type": "integer"}, "python_type": {"type": "int"}}, | |
| {"label": "img", "parameter_name": "img", "parameter_has_default": True, | |
| "parameter_default": None, "type": {"$defs": {"FileData": {}}}, | |
| "python_type": {"type": "filepath"}, "component": "Image"}, | |
| ], | |
| "returns": [{"label": "output"}], | |
| "description": "evil\"\"\"); import os; os.system('x') #", | |
| }, | |
| "/hidden": {"parameters": [], "returns": [], "api_visibility": "private"}, | |
| "/1-weird name!": {"parameters": [], "returns": []}, | |
| } | |
| } | |
| def _zip(path: Path) -> dict[str, bytes]: | |
| with zipfile.ZipFile(path) as zf: | |
| return {n.split("/", 1)[1]: zf.read(n) for n in zf.namelist()} | |
| def test_endpoint_normalization_and_codegen_safe(): | |
| eps = m.gradio_endpoints(INFO) | |
| assert [e["api_name"] for e in eps] == ["/predict", "/1-weird name!"] | |
| assert eps[0]["params"][1]["py"] == "class_" # keyword-safe identifier, original name kept | |
| assert eps[0]["params"][2]["kind"] == "file" | |
| assert eps[1]["tool"].isidentifier() | |
| src = m.generate_server(GRADIO, "gradio", eps) | |
| compile(src, "s.py", "exec") | |
| assert "def predict(name: str, class_: int = 3, img: str | None = None) -> str:" in src | |
| assert "'class': class_" in src and "_file(img)" in src | |
| assert "os.system('x')" not in src.replace(repr("evil\"\"\"); import os; os.system('x') #"), "") | |
| async def test_mcp_gradio_python_package(tmp_path, monkeypatch): | |
| async def fake_probe(info): | |
| return {"mcp_schema": None, "gradio_info": INFO} | |
| monkeypatch.setattr(m, "probe_space", fake_probe) | |
| r = await m.McpConverter().convert(BuildContext("t", tmp_path, GRADIO)) | |
| assert r.ok and r.artifact.filename == "hello_world-mcp.zip" | |
| files = _zip(r.artifact.path) | |
| mod = "spaceforge_mcp_gradio_hello_world.py" | |
| assert mod in files and "pyproject.toml" in files and "install.sh" in files | |
| assert b"gradio_client" in files["requirements.txt"] and b"mcp>=" in files["requirements.txt"] | |
| cur = json.loads(files["configs/cursor-mcp.json"]) | |
| assert cur["mcpServers"]["gradio-hello-world"]["command"].endswith("/.venv/bin/spaceforge-mcp-gradio-hello-world") | |
| assert "HF_TOKEN" in cur["mcpServers"]["gradio-hello-world"]["env"] | |
| assert json.loads(files["spaceforge.json"])["mcp_mode"] == "gradio" | |
| compile(files[mod].decode(), mod, "exec") | |
| async def test_mcp_gradio_dynamic_when_unreachable(tmp_path, monkeypatch): | |
| async def fake_probe(info): | |
| return {"mcp_schema": None, "gradio_info": None} | |
| monkeypatch.setattr(m, "probe_space", fake_probe) | |
| r = await m.McpConverter().convert(BuildContext("t", tmp_path, GRADIO)) | |
| files = _zip(r.artifact.path) | |
| src = files["spaceforge_mcp_gradio_hello_world.py"].decode() | |
| assert "def list_endpoints" in src and "def call_endpoint" in src | |
| async def test_mcp_remote_configs(tmp_path, monkeypatch): | |
| async def fake_probe(info): | |
| return {"mcp_schema": [{"name": "hello_predict", "inputSchema": {}}], "gradio_info": INFO} | |
| monkeypatch.setattr(m, "probe_space", fake_probe) | |
| r = await m.McpConverter().convert(BuildContext("t", tmp_path, GRADIO)) | |
| files = _zip(r.artifact.path) | |
| sse = "https://gradio-hello-world.hf.space/gradio_api/mcp/sse" | |
| assert json.loads(files["configs/cursor-mcp.json"])["mcpServers"]["gradio-hello-world"]["url"] == sse | |
| cl = json.loads(files["configs/claude_desktop_config.json"])["mcpServers"]["gradio-hello-world"] | |
| assert cl["command"] == "npx" and cl["args"] == ["mcp-remote", sse] | |
| assert "schema.json" in files and b"hello_predict" in files["README.md"] | |
| assert not any(k.endswith(".py") for k in files) | |
| async def test_mcp_docker_http_server(tmp_path): | |
| r = await m.McpConverter().convert(BuildContext("t", tmp_path, DOCKER)) # no network for docker sdk | |
| files = _zip(r.artifact.path) | |
| src = files["spaceforge_mcp_2btainment_repospace.py"].decode() | |
| assert "def call_space" in src and "def space_status" in src | |
| assert "SPACE_URL = 'https://2btainment-repospace.hf.space'" in src | |
| assert b"httpx" in files["requirements.txt"] and b"gradio_client" not in files["requirements.txt"] | |
| assert json.loads(files["spaceforge.json"])["mcp_mode"] == "http" | |