2Btainment commited on
Commit
f85a714
·
1 Parent(s): 1e9b113

feat(mcp): MCP target — Gradio-MCP configs (Cursor/Claude/generic) or generated FastMCP/MCPServer stdio server (gradio_client tools / generic HTTP)

Browse files
backend/app/converters/mcp_server.py ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MCP target — expose a Hugging Face Space to MCP clients (Cursor, Claude Desktop, ...).
2
+
3
+ Two honest modes, chosen at build time by probing the live Space:
4
+
5
+ * ``remote`` — the Space is a Gradio app launched with ``mcp_server=True`` and serves
6
+ ``/gradio_api/mcp/schema``. We emit ready-to-paste client configs pointing at the Space's own
7
+ MCP endpoint (``/gradio_api/mcp/sse``). Nothing runs locally.
8
+ * ``python`` — otherwise we generate a small Python MCP **stdio** server package:
9
+ - Gradio Spaces: one tool per public API endpoint, calling the Space via ``gradio_client``
10
+ (endpoint list snapshotted from ``/gradio_api/info``; if the Space is asleep at build time
11
+ the server discovers endpoints at runtime instead).
12
+ - Docker / static / other Spaces: a generic ``call_space`` HTTP tool (restricted to the Space
13
+ host) plus ``space_status``.
14
+ Optional ``HF_TOKEN`` env var for private / rate-limited Spaces.
15
+
16
+ Generated code never embeds untrusted Space metadata except via ``repr``/JSON literals.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import io
21
+ import json
22
+ import keyword
23
+ import re
24
+ import time
25
+ import zipfile
26
+ from typing import Any
27
+
28
+ import httpx
29
+
30
+ from backend.app.converters.base import Artifact, BuildContext, Converter, ConverterResult
31
+ from backend.app.converters.desktop.common import file_slug, owner_of, pkg_name, safe_title
32
+
33
+ PROBE_TIMEOUT = 15.0
34
+ MCP_MIN = "mcp>=1.10"
35
+ GRADIO_CLIENT_MIN = "gradio_client>=1.3"
36
+ HTTPX_MIN = "httpx>=0.27"
37
+
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # Probing
41
+ # ---------------------------------------------------------------------------
42
+
43
+ async def _get_json(client: httpx.AsyncClient, url: str) -> Any | None:
44
+ try:
45
+ r = await client.get(url)
46
+ except httpx.HTTPError:
47
+ return None
48
+ if r.status_code != 200 or "json" not in (r.headers.get("content-type") or ""):
49
+ return None
50
+ try:
51
+ return r.json()
52
+ except ValueError:
53
+ return None
54
+
55
+
56
+ async def probe_space(info: dict[str, Any]) -> dict[str, Any]:
57
+ """Return {"mcp_schema": list|None, "gradio_info": dict|None}."""
58
+ embed = (info.get("embed_url") or "").rstrip("/")
59
+ out: dict[str, Any] = {"mcp_schema": None, "gradio_info": None}
60
+ if not embed.startswith("https://") or not embed.endswith(".hf.space"):
61
+ return out
62
+ async with httpx.AsyncClient(timeout=PROBE_TIMEOUT, follow_redirects=False,
63
+ headers={"User-Agent": "SpaceForge-MCP/1.0"}) as client:
64
+ if (info.get("sdk") or "") == "gradio":
65
+ schema = await _get_json(client, f"{embed}/gradio_api/mcp/schema")
66
+ if isinstance(schema, list) and schema:
67
+ out["mcp_schema"] = schema
68
+ for path in ("/gradio_api/info", "/info"):
69
+ gi = await _get_json(client, embed + path)
70
+ if isinstance(gi, dict) and isinstance(gi.get("named_endpoints"), dict):
71
+ out["gradio_info"] = gi
72
+ break
73
+ return out
74
+
75
+
76
+ # ---------------------------------------------------------------------------
77
+ # Naming helpers
78
+ # ---------------------------------------------------------------------------
79
+
80
+ def server_key(info: dict[str, Any]) -> str:
81
+ raw = f"{owner_of(info)}-{info.get('name') or ''}".lower()
82
+ s = re.sub(r"[^a-z0-9]+", "-", raw).strip("-")
83
+ return s[:60] or "spaceforge-space"
84
+
85
+
86
+ def _ident(raw: str, used: set[str], fallback: str) -> str:
87
+ s = re.sub(r"[^0-9a-zA-Z_]+", "_", raw or "").strip("_").lower() or fallback
88
+ if s[0].isdigit():
89
+ s = "p_" + s
90
+ if keyword.iskeyword(s) or s in {"self", "ctx", "mcp"}:
91
+ s += "_"
92
+ base, i = s, 2
93
+ while s in used:
94
+ s = f"{base}_{i}"
95
+ i += 1
96
+ used.add(s)
97
+ return s
98
+
99
+
100
+ _FILE_COMPONENTS = {"image", "file", "audio", "video", "model3d", "uploadbutton", "imageeditor", "simpleimage"}
101
+
102
+
103
+ def _param_kind(p: dict[str, Any]) -> str:
104
+ pt = str((p.get("python_type") or {}).get("type") or "").strip()
105
+ jt = p.get("type") or {}
106
+ comp = str(p.get("component") or "").lower()
107
+ blob = json.dumps(jt)
108
+ if pt == "filepath" or "FileData" in blob or comp in _FILE_COMPONENTS:
109
+ return "file"
110
+ if pt == "str" or (isinstance(jt, dict) and jt.get("type") == "string"):
111
+ return "str"
112
+ if pt == "bool" or (isinstance(jt, dict) and jt.get("type") == "boolean"):
113
+ return "bool"
114
+ if pt == "int" or (isinstance(jt, dict) and jt.get("type") == "integer"):
115
+ return "int"
116
+ if pt == "float" or (isinstance(jt, dict) and jt.get("type") == "number"):
117
+ return "float"
118
+ return "any"
119
+
120
+
121
+ _PY_TYPE = {"str": "str", "bool": "bool", "int": "int", "float": "float", "file": "str", "any": "Any"}
122
+
123
+
124
+ def gradio_endpoints(gi: dict[str, Any]) -> list[dict[str, Any]]:
125
+ """Normalize /gradio_api/info into a compact, JSON-safe endpoint list."""
126
+ eps: list[dict[str, Any]] = []
127
+ used_tools: set[str] = set()
128
+ for api_name, ep in (gi.get("named_endpoints") or {}).items():
129
+ if not isinstance(ep, dict) or not isinstance(api_name, str):
130
+ continue
131
+ vis = ep.get("api_visibility", ep.get("show_api", "public"))
132
+ if vis in ("private", "undocumented", False):
133
+ continue
134
+ used_params: set[str] = set()
135
+ params = []
136
+ by_kw = True
137
+ for i, p in enumerate(ep.get("parameters") or []):
138
+ if not isinstance(p, dict):
139
+ continue
140
+ pname = p.get("parameter_name")
141
+ if not pname:
142
+ by_kw = False
143
+ default = p.get("parameter_default")
144
+ has_default = bool(p.get("parameter_has_default"))
145
+ if not isinstance(default, (str, int, float, bool, type(None))):
146
+ default = None
147
+ params.append({
148
+ "py": _ident(str(pname or p.get("label") or f"arg{i}"), used_params, f"arg{i}"),
149
+ "name": pname,
150
+ "label": str(p.get("label") or pname or f"arg{i}")[:120],
151
+ "kind": _param_kind(p),
152
+ "has_default": has_default,
153
+ "default": default,
154
+ "example": p.get("example_input") if isinstance(p.get("example_input"), (str, int, float, bool)) else None,
155
+ })
156
+ returns = [str(r.get("label") or r.get("component") or "output")[:80]
157
+ for r in (ep.get("returns") or []) if isinstance(r, dict)]
158
+ eps.append({
159
+ "api_name": api_name,
160
+ "tool": _ident(api_name.lstrip("/"), used_tools, "endpoint"),
161
+ "description": str(ep.get("description") or "")[:800],
162
+ "params": params,
163
+ "by_keyword": by_kw,
164
+ "returns": returns,
165
+ })
166
+ return eps
167
+
168
+
169
+ # ---------------------------------------------------------------------------
170
+ # Code generation
171
+ # ---------------------------------------------------------------------------
172
+
173
+ _HEADER = '''#!/usr/bin/env python3
174
+ """MCP stdio server for the Hugging Face Space {repo_id!s} — generated by SpaceForge.
175
+
176
+ Mode: {mode}. Calls the LIVE Space ({embed}); nothing of the model runs locally.
177
+ Optional env: HF_TOKEN (private / rate-limited Spaces).
178
+ """
179
+ from __future__ import annotations
180
+
181
+ import contextlib
182
+ import json
183
+ import os
184
+ import sys
185
+ from typing import Any
186
+
187
+ try: # mcp >= 2
188
+ from mcp.server.mcpserver import MCPServer as _Server
189
+ except ImportError: # mcp 1.x
190
+ from mcp.server.fastmcp import FastMCP as _Server
191
+
192
+ SPACE_ID = {repo_id!r}
193
+ SPACE_URL = {embed!r}
194
+ HF_TOKEN = (os.environ.get("HF_TOKEN") or "").strip() or None
195
+
196
+ mcp = _Server({server_name!r}, instructions={instructions!r})
197
+
198
+
199
+ def _fmt(result: Any) -> str:
200
+ if isinstance(result, str):
201
+ return result
202
+ return json.dumps(result, ensure_ascii=False, default=str, indent=2)
203
+ '''
204
+
205
+ _GRADIO_CORE = '''
206
+
207
+ _CLIENT = None
208
+
209
+
210
+ def _client():
211
+ """Lazily connect (the Space may need to wake up). stdout is reserved for MCP JSON-RPC."""
212
+ global _CLIENT
213
+ if _CLIENT is None:
214
+ from gradio_client import Client
215
+
216
+ with contextlib.redirect_stdout(sys.stderr):
217
+ try:
218
+ _CLIENT = Client(SPACE_ID, token=HF_TOKEN, verbose=False)
219
+ except TypeError: # very old gradio_client
220
+ _CLIENT = Client(SPACE_ID, hf_token=HF_TOKEN)
221
+ return _CLIENT
222
+
223
+
224
+ def _file(value: Any) -> Any:
225
+ if isinstance(value, str) and value:
226
+ from gradio_client import handle_file
227
+
228
+ return handle_file(value)
229
+ return value
230
+
231
+
232
+ def _predict(api_name: str, args: list, kwargs: dict) -> str:
233
+ with contextlib.redirect_stdout(sys.stderr):
234
+ result = _client().predict(*args, api_name=api_name, **kwargs)
235
+ return _fmt(result)
236
+ '''
237
+
238
+ _GRADIO_DYNAMIC = '''
239
+
240
+ @mcp.tool(name="list_endpoints", description="List the Space's Gradio API endpoints and their parameters.")
241
+ def list_endpoints() -> str:
242
+ with contextlib.redirect_stdout(sys.stderr):
243
+ api = _client().view_api(print_info=False, return_format="dict")
244
+ return _fmt(api)
245
+
246
+
247
+ @mcp.tool(
248
+ name="call_endpoint",
249
+ description="Call a Gradio API endpoint of the Space. api_name like '/predict'; pass inputs as "
250
+ "keyword arguments (kwargs) or positional list (args). File inputs: give a URL or local path "
251
+ "and list its parameter name in file_params.",
252
+ )
253
+ def call_endpoint(api_name: str, kwargs: dict | None = None, args: list | None = None,
254
+ file_params: list[str] | None = None) -> str:
255
+ kw = dict(kwargs or {})
256
+ for k in file_params or []:
257
+ if k in kw:
258
+ kw[k] = _file(kw[k])
259
+ return _predict(api_name, list(args or []), kw)
260
+ '''
261
+
262
+ _HTTP_CORE = '''
263
+
264
+ import httpx
265
+
266
+ _METHODS = {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"}
267
+ _MAX_CHARS = 50_000
268
+
269
+
270
+ def _headers() -> dict:
271
+ h = {"User-Agent": "SpaceForge-MCP/1.0"}
272
+ if HF_TOKEN:
273
+ h["Authorization"] = f"Bearer {HF_TOKEN}"
274
+ return h
275
+
276
+
277
+ @mcp.tool(
278
+ name="call_space",
279
+ description="Send an HTTP request to the Space's own web server (" + SPACE_URL + "). "
280
+ "path must start with '/', e.g. '/', '/api/health', '/openapi.json'. Returns status, "
281
+ "content-type and the (truncated) body. Only this Space host can be reached.",
282
+ )
283
+ def call_space(path: str = "/", method: str = "GET", query: dict | None = None,
284
+ json_body: Any = None, timeout_s: float = 60.0) -> str:
285
+ method = (method or "GET").upper()
286
+ if method not in _METHODS:
287
+ return f"error: method must be one of {sorted(_METHODS)}"
288
+ if not path.startswith("/") or path.startswith("//") or "://" in path:
289
+ return "error: path must be a relative path starting with '/'"
290
+ url = SPACE_URL.rstrip("/") + path
291
+ try:
292
+ with httpx.Client(timeout=max(1.0, min(float(timeout_s), 300.0)), follow_redirects=False) as c:
293
+ r = c.request(method, url, params=query or None,
294
+ json=json_body if json_body is not None else None, headers=_headers())
295
+ except httpx.HTTPError as e:
296
+ return f"error: {type(e).__name__}: {e}"
297
+ body = r.text if method != "HEAD" else ""
298
+ out = {
299
+ "status": r.status_code,
300
+ "content_type": r.headers.get("content-type"),
301
+ "location": r.headers.get("location"),
302
+ "body": body[:_MAX_CHARS],
303
+ "truncated": len(body) > _MAX_CHARS,
304
+ }
305
+ if r.status_code == 503:
306
+ out["hint"] = "The Space may be sleeping, paused or building — check space_status()."
307
+ return _fmt(out)
308
+
309
+
310
+ @mcp.tool(name="space_status", description="Hugging Face runtime status of the Space (RUNNING, SLEEPING, PAUSED, ...).")
311
+ def space_status() -> str:
312
+ try:
313
+ r = httpx.get(f"https://huggingface.co/api/spaces/{SPACE_ID}", headers=_headers(), timeout=20)
314
+ d = r.json() if r.status_code == 200 else {}
315
+ except (httpx.HTTPError, ValueError) as e:
316
+ return f"error: {type(e).__name__}: {e}"
317
+ rt = d.get("runtime") or {}
318
+ return _fmt({"space": SPACE_ID, "http_status": r.status_code, "sdk": d.get("sdk"),
319
+ "stage": rt.get("stage"), "hardware": (rt.get("hardware") or {}).get("current"),
320
+ "url": SPACE_URL})
321
+ '''
322
+
323
+ _FOOTER = '''
324
+
325
+ def main() -> None:
326
+ mcp.run()
327
+
328
+
329
+ if __name__ == "__main__":
330
+ main()
331
+ '''
332
+
333
+
334
+ def _tool_code(ep: dict[str, Any]) -> str:
335
+ req = [p for p in ep["params"] if not p["has_default"]]
336
+ opt = [p for p in ep["params"] if p["has_default"]]
337
+ sig_parts = []
338
+ for p in req:
339
+ sig_parts.append(f"{p['py']}: {_PY_TYPE[p['kind']]}")
340
+ for p in opt:
341
+ t = _PY_TYPE[p["kind"]]
342
+ if p["default"] is None and t != "Any":
343
+ t = f"{t} | None"
344
+ sig_parts.append(f"{p['py']}: {t} = {p['default']!r}")
345
+ if not ep["by_keyword"]:
346
+ # positional call: keep Space order; give everything after the first optional a default
347
+ sig_parts, seen_default = [], False
348
+ for p in ep["params"]:
349
+ t = _PY_TYPE[p["kind"]]
350
+ if p["has_default"] or seen_default:
351
+ seen_default = True
352
+ if p["default"] is None and t != "Any":
353
+ t = f"{t} | None"
354
+ sig_parts.append(f"{p['py']}: {t} = {p['default']!r}")
355
+ else:
356
+ sig_parts.append(f"{p['py']}: {t}")
357
+ lines = []
358
+ desc = ep["description"].strip() or f"Call the Space endpoint {ep['api_name']}."
359
+ pdesc = "; ".join(
360
+ f"{p['py']}: {p['label']}" + (" (file: URL or local path)" if p["kind"] == "file" else "")
361
+ for p in ep["params"]
362
+ )
363
+ if pdesc:
364
+ desc += " Inputs — " + pdesc + "."
365
+ if ep["returns"]:
366
+ desc += " Returns: " + ", ".join(ep["returns"]) + "."
367
+ lines.append("")
368
+ lines.append("")
369
+ lines.append(f"@mcp.tool(name={ep['tool']!r}, description={desc[:1500]!r})")
370
+ lines.append(f"def {ep['tool']}({', '.join(sig_parts)}) -> str:")
371
+ def val(p: dict[str, Any]) -> str:
372
+ return f"_file({p['py']})" if p["kind"] == "file" else p["py"]
373
+ if ep["by_keyword"]:
374
+ kw = ", ".join(f"{p['name']!r}: {val(p)}" for p in ep["params"])
375
+ lines.append(f" return _predict({ep['api_name']!r}, [], {{{kw}}})")
376
+ else:
377
+ args = ", ".join(val(p) for p in ep["params"])
378
+ lines.append(f" return _predict({ep['api_name']!r}, [{args}], {{}})")
379
+ return "\n".join(lines) + "\n"
380
+
381
+
382
+ def generate_server(info: dict[str, Any], mode: str, endpoints: list[dict[str, Any]] | None) -> str:
383
+ repo = str(info.get("repo_id") or "")
384
+ embed = str(info.get("embed_url") or "")
385
+ if mode == "gradio":
386
+ instr = (f"Tools call the Gradio Space {repo} ({embed}) via gradio_client. "
387
+ "First call may take a while if the Space is waking up.")
388
+ elif mode == "gradio_dynamic":
389
+ instr = (f"Use list_endpoints, then call_endpoint, to use the Gradio Space {repo} ({embed}).")
390
+ else:
391
+ instr = (f"Use call_space to send HTTP requests to the Space {repo} ({embed}); "
392
+ "space_status shows whether it is running.")
393
+ src = _HEADER.format(repo_id=repo, embed=embed, mode=mode, server_name=server_key(info),
394
+ instructions=instr)
395
+ if mode in ("gradio", "gradio_dynamic"):
396
+ src += _GRADIO_CORE
397
+ if mode == "gradio":
398
+ for ep in endpoints or []:
399
+ src += _tool_code(ep)
400
+ else:
401
+ src += _GRADIO_DYNAMIC
402
+ else:
403
+ src += _HTTP_CORE
404
+ src += _FOOTER
405
+ compile(src, "server.py", "exec") # fail the build, not the user, on a codegen bug
406
+ return src
407
+
408
+
409
+ def _j(data: Any) -> bytes:
410
+ return (json.dumps(data, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
411
+
412
+
413
+ def build_python_package(info: dict[str, Any], mode: str, endpoints: list[dict[str, Any]] | None,
414
+ dirname: str) -> dict[str, bytes]:
415
+ key = server_key(info)
416
+ dist = pkg_name(info).replace("spaceforge-", "spaceforge-mcp-", 1)
417
+ module = re.sub(r"[^a-z0-9_]", "_", dist.replace("-", "_"))
418
+ script = dist
419
+ repo = info.get("repo_id")
420
+ deps = [MCP_MIN] + ([GRADIO_CLIENT_MIN] if mode.startswith("gradio") else [HTTPX_MIN])
421
+ files: dict[str, bytes] = {}
422
+ files[f"{module}.py"] = generate_server(info, mode, endpoints).encode("utf-8")
423
+ files["requirements.txt"] = ("\n".join(deps) + "\n").encode()
424
+ files["pyproject.toml"] = f'''[build-system]
425
+ requires = ["setuptools>=61"]
426
+ build-backend = "setuptools.build_meta"
427
+
428
+ [project]
429
+ name = "{dist}"
430
+ version = "1.0.0"
431
+ description = {json.dumps(f"MCP stdio server for the Hugging Face Space {repo} (SpaceForge)")}
432
+ requires-python = ">=3.10"
433
+ dependencies = {json.dumps(deps)}
434
+
435
+ [project.scripts]
436
+ {script} = "{module}:main"
437
+
438
+ [tool.setuptools]
439
+ py-modules = ["{module}"]
440
+ '''.encode()
441
+ placeholder = f"/ABSOLUTE/PATH/TO/{dirname}"
442
+ cmd = f"{placeholder}/.venv/bin/{script}"
443
+ env = {"HF_TOKEN": ""}
444
+ files["configs/cursor-mcp.json"] = _j({"mcpServers": {key: {"command": cmd, "args": [], "env": env}}})
445
+ files["configs/claude_desktop_config.json"] = _j({"mcpServers": {key: {"command": cmd, "args": [], "env": env}}})
446
+ files["configs/mcp.json"] = _j({
447
+ "mcpServers": {key: {"type": "stdio", "command": cmd, "args": [], "env": env}},
448
+ "alternative_without_install": {"command": "python3", "args": [f"{placeholder}/{module}.py"],
449
+ "note": "needs the requirements.txt packages in that python"},
450
+ })
451
+ files["install.sh"] = f'''#!/usr/bin/env bash
452
+ # Create a private venv, install the server, and print ready-to-paste MCP configs.
453
+ set -euo pipefail
454
+ cd "$(dirname "$(readlink -f "$0")")"
455
+ DIR="$(pwd)"
456
+ python3 -m venv .venv
457
+ .venv/bin/pip install -q --upgrade pip
458
+ .venv/bin/pip install -q .
459
+ mkdir -p configs/local
460
+ for f in configs/*.json; do
461
+ sed "s#{placeholder}#$DIR#g" "$f" > "configs/local/$(basename "$f")"
462
+ done
463
+ echo "Installed: $DIR/.venv/bin/{script}"
464
+ echo "Cursor: merge configs/local/cursor-mcp.json into ~/.cursor/mcp.json"
465
+ echo "Claude: merge configs/local/claude_desktop_config.json into ~/.config/Claude/claude_desktop_config.json"
466
+ '''.encode()
467
+ if mode == "gradio":
468
+ tools_md = "\n".join(
469
+ f"- `{e['tool']}` → `{e['api_name']}`"
470
+ + (f" ({', '.join(p['py'] for p in e['params'])})" if e["params"] else "")
471
+ for e in endpoints or []
472
+ ) or "- (no public endpoints found)"
473
+ files["endpoints.json"] = _j(endpoints or [])
474
+ elif mode == "gradio_dynamic":
475
+ tools_md = ("- `list_endpoints` — discover the Space API at runtime\n"
476
+ "- `call_endpoint(api_name, kwargs|args, file_params)`\n\n"
477
+ "_The Space was not reachable when this package was built, so endpoints are discovered at runtime._")
478
+ else:
479
+ tools_md = ("- `call_space(path, method, query, json_body)` — HTTP to the Space host only\n"
480
+ "- `space_status()` — RUNNING / SLEEPING / PAUSED …")
481
+ files["README.md"] = f"""# MCP server for `{repo}` (SpaceForge)
482
+
483
+ Local **stdio** MCP server that calls the live Hugging Face Space **{info.get('embed_url')}**.
484
+ Mode: `{mode}`. Nothing of the model runs on your machine; the Space must be running
485
+ (a sleeping Space wakes on the first call, which can take a while).
486
+
487
+ ## Tools
488
+ {tools_md}
489
+
490
+ ## Install (Linux / macOS)
491
+ ```bash
492
+ unzip {dirname}.zip && cd {dirname}
493
+ ./install.sh # creates .venv, pip install ., writes configs/local/*.json with real paths
494
+ ```
495
+ Manual: `python3 -m venv .venv && .venv/bin/pip install .` → command `.venv/bin/{script}`.
496
+
497
+ ## Client config
498
+ - **Cursor**: merge `configs/local/cursor-mcp.json` into `~/.cursor/mcp.json` (or project `.cursor/mcp.json`).
499
+ - **Claude Desktop**: merge `configs/local/claude_desktop_config.json` into
500
+ `~/.config/Claude/claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/`).
501
+ - Generic: `configs/mcp.json`. Without installing: `python3 {module}.py` with `{" ".join(deps)}` available.
502
+
503
+ ## Auth
504
+ Set `HF_TOKEN` in the config's `env` for private Spaces or higher rate limits (leave empty otherwise).
505
+ The token is only sent to Hugging Face.
506
+
507
+ ## Limits
508
+ - Requires network; results come from the Space as-is (file outputs are downloaded to a temp dir and
509
+ returned as local paths).
510
+ - Paused/private Spaces return errors (`space_status` / the error text say why).
511
+
512
+ Generated by SpaceForge — https://huggingface.co/spaces/2Btainment/spaceforge
513
+ """.encode()
514
+ return files
515
+
516
+
517
+ def build_remote_package(info: dict[str, Any], schema: list[Any], dirname: str) -> dict[str, bytes]:
518
+ key = server_key(info)
519
+ embed = (info.get("embed_url") or "").rstrip("/")
520
+ sse = f"{embed}/gradio_api/mcp/sse"
521
+ http = f"{embed}/gradio_api/mcp/"
522
+ files: dict[str, bytes] = {}
523
+ files["configs/cursor-mcp.json"] = _j({"mcpServers": {key: {"url": sse}}})
524
+ files["configs/claude_desktop_config.json"] = _j(
525
+ {"mcpServers": {key: {"command": "npx", "args": ["mcp-remote", sse]}}}
526
+ )
527
+ files["configs/mcp.json"] = _j({
528
+ "mcpServers": {key: {"type": "sse", "url": sse}},
529
+ "streamable_http_url": http,
530
+ "schema_url": f"{embed}/gradio_api/mcp/schema",
531
+ })
532
+ files["schema.json"] = _j(schema)
533
+ names = [str(t.get("name")) for t in schema if isinstance(t, dict) and t.get("name")]
534
+ tools_md = "\n".join(f"- `{n}`" for n in names[:60]) or "- (see schema.json)"
535
+ files["README.md"] = f"""# MCP config for `{info.get('repo_id')}` (SpaceForge)
536
+
537
+ This Gradio Space runs its **own MCP server** (`mcp_server=True`), so no local code is needed.
538
+
539
+ - SSE endpoint: `{sse}`
540
+ - Streamable HTTP endpoint (newer clients): `{http}`
541
+ - Tool schema snapshot: `schema.json` (live: `{embed}/gradio_api/mcp/schema`)
542
+
543
+ ## Tools (at build time)
544
+ {tools_md}
545
+
546
+ ## Cursor
547
+ Merge `configs/cursor-mcp.json` into `~/.cursor/mcp.json`:
548
+ ```json
549
+ {json.dumps({"mcpServers": {key: {"url": sse}}}, indent=2)}
550
+ ```
551
+
552
+ ## Claude Desktop
553
+ Claude Desktop speaks stdio, so it bridges via `mcp-remote` (needs Node.js / `npx`).
554
+ Merge `configs/claude_desktop_config.json` into `~/.config/Claude/claude_desktop_config.json`
555
+ (add `"-y"` before `"mcp-remote"` to skip npx's install prompt).
556
+
557
+ ## Private Spaces / rate limits
558
+ Add a header with your token, e.g. for mcp-remote:
559
+ `"args": ["mcp-remote", "{sse}", "--header", "Authorization: Bearer ${{HF_TOKEN}}"]` with
560
+ `"env": {{"HF_TOKEN": "hf_..."}}`; Cursor: `"headers": {{"Authorization": "Bearer hf_..."}}`.
561
+
562
+ ## Limits
563
+ The Space must be running; GPU/ZeroGPU Spaces may queue or hit quota. Tools are exactly what the
564
+ Space author exposes.
565
+
566
+ Generated by SpaceForge — https://huggingface.co/spaces/2Btainment/spaceforge
567
+ """.encode()
568
+ return files
569
+
570
+
571
+ class McpConverter(Converter):
572
+ id = "mcp"
573
+ label = "MCP Server / Config"
574
+ mode = "hosted_wrapper"
575
+ available = True
576
+ stub = False
577
+
578
+ async def convert(self, ctx: BuildContext) -> ConverterResult:
579
+ info = ctx.space_info
580
+ name = file_slug(info.get("name") or "space")
581
+ dirname = f"{name}-mcp"
582
+ ctx.info(f"MCP for {info.get('repo_id')} (sdk={info.get('sdk')}): probing {info.get('embed_url')} …")
583
+ probe = await probe_space(info)
584
+ if probe["mcp_schema"]:
585
+ files = build_remote_package(info, probe["mcp_schema"], dirname)
586
+ mode = "remote"
587
+ ntools = len(probe["mcp_schema"])
588
+ ctx.info(f"Space serves Gradio MCP ({ntools} tools) → emitting Cursor/Claude/generic configs")
589
+ notes = (f"Space has its own Gradio MCP server ({ntools} tools): configs for Cursor (url "
590
+ f"…/gradio_api/mcp/sse), Claude Desktop (npx mcp-remote) and generic JSON. Space must be running.")
591
+ elif (info.get("sdk") or "") == "gradio":
592
+ eps = gradio_endpoints(probe["gradio_info"]) if probe["gradio_info"] else None
593
+ mode = "gradio" if eps else "gradio_dynamic"
594
+ files = build_python_package(info, mode, eps, dirname)
595
+ if eps:
596
+ ctx.info(f"Gradio API: {len(eps)} public endpoint(s) → one MCP tool each: "
597
+ + ", ".join(e["tool"] for e in eps[:12]))
598
+ notes = (f"Python MCP stdio server (gradio_client), {len(eps)} tool(s) from the Space API. "
599
+ "./install.sh then paste configs/local/*.json. Calls the live Space; optional HF_TOKEN.")
600
+ else:
601
+ ctx.info("Gradio API info not reachable now (Space asleep?) → runtime-discovery server "
602
+ "(list_endpoints / call_endpoint)")
603
+ notes = ("Python MCP stdio server with runtime endpoint discovery (Space was not reachable at "
604
+ "build time). Calls the live Space; optional HF_TOKEN.")
605
+ else:
606
+ mode = "http"
607
+ files = build_python_package(info, mode, None, dirname)
608
+ ctx.info(f"{info.get('sdk')} Space → generic HTTP MCP server (call_space, space_status)")
609
+ notes = ("Python MCP stdio server with a generic call_space HTTP tool (Space host only) + "
610
+ "space_status. Calls the live Space; optional HF_TOKEN.")
611
+ files["spaceforge.json"] = _j({
612
+ "product": "SpaceForge",
613
+ "target": "mcp",
614
+ "mcp_mode": mode,
615
+ "space": info.get("repo_id"),
616
+ "sdk": info.get("sdk"),
617
+ "embed_url": info.get("embed_url"),
618
+ "title": safe_title(info),
619
+ "built_at": int(time.time()),
620
+ "binary_included": False,
621
+ })
622
+ out = ctx.work_dir / f"{dirname}.zip"
623
+ buf = io.BytesIO()
624
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
625
+ for rel, data in files.items():
626
+ zi = zipfile.ZipInfo(f"{dirname}/{rel}", date_time=time.localtime()[:6])
627
+ zi.compress_type = zipfile.ZIP_DEFLATED
628
+ zi.external_attr = ((0o755 if rel.endswith(".sh") else 0o644) << 16)
629
+ zf.writestr(zi, data)
630
+ out.write_bytes(buf.getvalue())
631
+ ctx.info(f"OK: {out.name} ({out.stat().st_size} bytes) mode={mode}")
632
+ return ConverterResult(
633
+ ok=True,
634
+ artifact=Artifact(
635
+ target_id=self.id, path=out, filename=out.name, mode=self.mode,
636
+ media_type="application/zip", notes=notes, binary_included=False,
637
+ ),
638
+ )
backend/app/converters/registry.py CHANGED
@@ -12,6 +12,7 @@ from backend.app.converters.tauri import TauriConverter
12
  from backend.app.converters.mobile.android import AndroidConverter
13
  from backend.app.converters.desktop.linux_appimage import LinuxAppImageConverter
14
  from backend.app.converters.desktop.arch_pkgbuild import ArchPkgbuildConverter
 
15
  from backend.app.converters.stubs import WindowsPortableStub
16
 
17
 
@@ -25,6 +26,7 @@ def get_registry() -> Dict[str, Converter]:
25
  AndroidConverter(),
26
  LinuxAppImageConverter(),
27
  ArchPkgbuildConverter(),
 
28
  WindowsPortableStub(),
29
  ]
30
  return {c.id: c for c in converters}
 
12
  from backend.app.converters.mobile.android import AndroidConverter
13
  from backend.app.converters.desktop.linux_appimage import LinuxAppImageConverter
14
  from backend.app.converters.desktop.arch_pkgbuild import ArchPkgbuildConverter
15
+ from backend.app.converters.mcp_server import McpConverter
16
  from backend.app.converters.stubs import WindowsPortableStub
17
 
18
 
 
26
  AndroidConverter(),
27
  LinuxAppImageConverter(),
28
  ArchPkgbuildConverter(),
29
+ McpConverter(),
30
  WindowsPortableStub(),
31
  ]
32
  return {c.id: c for c in converters}
backend/tests/test_mcp.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MCP target: remote Gradio-MCP configs, gradio_client stdio server, generic HTTP server."""
2
+ import json
3
+ import zipfile
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+
8
+ from backend.app.converters import mcp_server as m
9
+ from backend.app.converters.base import BuildContext
10
+
11
+ GRADIO = {
12
+ "repo_id": "gradio/hello_world", "owner": "gradio", "name": "hello_world", "title": "Hello",
13
+ "sdk": "gradio", "embed_url": "https://gradio-hello-world.hf.space",
14
+ }
15
+ DOCKER = {
16
+ "repo_id": "2Btainment/repospace", "owner": "2Btainment", "name": "repospace", "title": "RepoSpace",
17
+ "sdk": "docker", "embed_url": "https://2btainment-repospace.hf.space",
18
+ }
19
+ INFO = {
20
+ "named_endpoints": {
21
+ "/predict": {
22
+ "parameters": [
23
+ {"label": "name", "parameter_name": "name", "parameter_has_default": False,
24
+ "type": {"type": "string"}, "python_type": {"type": "str"}, "component": "Textbox"},
25
+ {"label": "count", "parameter_name": "class", "parameter_has_default": True,
26
+ "parameter_default": 3, "type": {"type": "integer"}, "python_type": {"type": "int"}},
27
+ {"label": "img", "parameter_name": "img", "parameter_has_default": True,
28
+ "parameter_default": None, "type": {"$defs": {"FileData": {}}},
29
+ "python_type": {"type": "filepath"}, "component": "Image"},
30
+ ],
31
+ "returns": [{"label": "output"}],
32
+ "description": "evil\"\"\"); import os; os.system('x') #",
33
+ },
34
+ "/hidden": {"parameters": [], "returns": [], "api_visibility": "private"},
35
+ "/1-weird name!": {"parameters": [], "returns": []},
36
+ }
37
+ }
38
+
39
+
40
+ def _zip(path: Path) -> dict[str, bytes]:
41
+ with zipfile.ZipFile(path) as zf:
42
+ return {n.split("/", 1)[1]: zf.read(n) for n in zf.namelist()}
43
+
44
+
45
+ def test_endpoint_normalization_and_codegen_safe():
46
+ eps = m.gradio_endpoints(INFO)
47
+ assert [e["api_name"] for e in eps] == ["/predict", "/1-weird name!"]
48
+ assert eps[0]["params"][1]["py"] == "class_" # keyword-safe identifier, original name kept
49
+ assert eps[0]["params"][2]["kind"] == "file"
50
+ assert eps[1]["tool"].isidentifier()
51
+ src = m.generate_server(GRADIO, "gradio", eps)
52
+ compile(src, "s.py", "exec")
53
+ assert "def predict(name: str, class_: int = 3, img: str | None = None) -> str:" in src
54
+ assert "'class': class_" in src and "_file(img)" in src
55
+ assert "os.system('x')" not in src.replace(repr("evil\"\"\"); import os; os.system('x') #"), "")
56
+
57
+
58
+ @pytest.mark.asyncio
59
+ async def test_mcp_gradio_python_package(tmp_path, monkeypatch):
60
+ async def fake_probe(info):
61
+ return {"mcp_schema": None, "gradio_info": INFO}
62
+
63
+ monkeypatch.setattr(m, "probe_space", fake_probe)
64
+ r = await m.McpConverter().convert(BuildContext("t", tmp_path, GRADIO))
65
+ assert r.ok and r.artifact.filename == "hello_world-mcp.zip"
66
+ files = _zip(r.artifact.path)
67
+ mod = "spaceforge_mcp_gradio_hello_world.py"
68
+ assert mod in files and "pyproject.toml" in files and "install.sh" in files
69
+ assert b"gradio_client" in files["requirements.txt"] and b"mcp>=" in files["requirements.txt"]
70
+ cur = json.loads(files["configs/cursor-mcp.json"])
71
+ assert cur["mcpServers"]["gradio-hello-world"]["command"].endswith("/.venv/bin/spaceforge-mcp-gradio-hello-world")
72
+ assert "HF_TOKEN" in cur["mcpServers"]["gradio-hello-world"]["env"]
73
+ assert json.loads(files["spaceforge.json"])["mcp_mode"] == "gradio"
74
+ compile(files[mod].decode(), mod, "exec")
75
+
76
+
77
+ @pytest.mark.asyncio
78
+ async def test_mcp_gradio_dynamic_when_unreachable(tmp_path, monkeypatch):
79
+ async def fake_probe(info):
80
+ return {"mcp_schema": None, "gradio_info": None}
81
+
82
+ monkeypatch.setattr(m, "probe_space", fake_probe)
83
+ r = await m.McpConverter().convert(BuildContext("t", tmp_path, GRADIO))
84
+ files = _zip(r.artifact.path)
85
+ src = files["spaceforge_mcp_gradio_hello_world.py"].decode()
86
+ assert "def list_endpoints" in src and "def call_endpoint" in src
87
+
88
+
89
+ @pytest.mark.asyncio
90
+ async def test_mcp_remote_configs(tmp_path, monkeypatch):
91
+ async def fake_probe(info):
92
+ return {"mcp_schema": [{"name": "hello_predict", "inputSchema": {}}], "gradio_info": INFO}
93
+
94
+ monkeypatch.setattr(m, "probe_space", fake_probe)
95
+ r = await m.McpConverter().convert(BuildContext("t", tmp_path, GRADIO))
96
+ files = _zip(r.artifact.path)
97
+ sse = "https://gradio-hello-world.hf.space/gradio_api/mcp/sse"
98
+ assert json.loads(files["configs/cursor-mcp.json"])["mcpServers"]["gradio-hello-world"]["url"] == sse
99
+ cl = json.loads(files["configs/claude_desktop_config.json"])["mcpServers"]["gradio-hello-world"]
100
+ assert cl["command"] == "npx" and cl["args"] == ["mcp-remote", sse]
101
+ assert "schema.json" in files and b"hello_predict" in files["README.md"]
102
+ assert not any(k.endswith(".py") for k in files)
103
+
104
+
105
+ @pytest.mark.asyncio
106
+ async def test_mcp_docker_http_server(tmp_path):
107
+ r = await m.McpConverter().convert(BuildContext("t", tmp_path, DOCKER)) # no network for docker sdk
108
+ files = _zip(r.artifact.path)
109
+ src = files["spaceforge_mcp_2btainment_repospace.py"].decode()
110
+ assert "def call_space" in src and "def space_status" in src
111
+ assert "SPACE_URL = 'https://2btainment-repospace.hf.space'" in src
112
+ assert b"httpx" in files["requirements.txt"] and b"gradio_client" not in files["requirements.txt"]
113
+ assert json.loads(files["spaceforge.json"])["mcp_mode"] == "http"