deploy to huggingface spoace with hf token
Browse files- app.py +578 -450
- requirements.txt +1 -0
- src/hf_deployer.py +190 -0
- src/mcp_http_host.py +1 -15
app.py
CHANGED
|
@@ -1,450 +1,578 @@
|
|
| 1 |
-
"""
|
| 2 |
-
MCP Generator - Gradio Frontend
|
| 3 |
-
Turn any API into an MCP server in seconds!
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import asyncio
|
| 7 |
-
import gradio as gr
|
| 8 |
-
from pathlib import Path
|
| 9 |
-
import zipfile
|
| 10 |
-
import io
|
| 11 |
-
import os
|
| 12 |
-
|
| 13 |
-
from src.agents.factory import AgentFactory
|
| 14 |
-
from src.mcp_host import mcp_host
|
| 15 |
-
from src.mcp_http_host import mcp_http_host
|
| 16 |
-
from src.mcp_registry import mcp_registry
|
| 17 |
-
from src.
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
print(f"
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
"",
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
""
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
**
|
| 79 |
-
**
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
- **
|
| 86 |
-
- **
|
| 87 |
-
- **
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
""
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
"
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
}}
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
#
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
}}
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
if
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
zip_buffer.
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
{{
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
"",
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MCP Generator - Gradio Frontend
|
| 3 |
+
Turn any API into an MCP server in seconds!
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
import gradio as gr
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import zipfile
|
| 10 |
+
import io
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
from src.agents.factory import AgentFactory
|
| 14 |
+
from src.mcp_host import mcp_host
|
| 15 |
+
from src.mcp_http_host import mcp_http_host
|
| 16 |
+
from src.mcp_registry import mcp_registry
|
| 17 |
+
from src.hf_deployer import deploy_to_huggingface
|
| 18 |
+
from src.config import LLM_PROVIDER, ANTHROPIC_API_KEY, OPENAI_API_KEY, HOSTED_MCPS_DIR
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# Initialize agent factory
|
| 22 |
+
try:
|
| 23 |
+
agent_factory = AgentFactory()
|
| 24 |
+
print(f"β
Using {LLM_PROVIDER.upper()} for code generation")
|
| 25 |
+
except ValueError as e:
|
| 26 |
+
print(f"β Error: {e}")
|
| 27 |
+
print(f"Please set {'ANTHROPIC_API_KEY' if LLM_PROVIDER == 'anthropic' else 'OPENAI_API_KEY'} in .env file")
|
| 28 |
+
agent_factory = None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
async def generate_and_host_mcp(api_url: str, api_key: str = None, force_regenerate: bool = False, progress=gr.Progress()):
|
| 32 |
+
"""Generate and host an MCP server
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
api_url: The API URL to analyze
|
| 36 |
+
api_key: Optional API key for the target API
|
| 37 |
+
force_regenerate: If True, regenerate even if exists
|
| 38 |
+
progress: Gradio progress tracker
|
| 39 |
+
|
| 40 |
+
Returns:
|
| 41 |
+
Tuple of (status_text, code, download_file, readme, connection_config)
|
| 42 |
+
"""
|
| 43 |
+
if not agent_factory:
|
| 44 |
+
api_key_name = "ANTHROPIC_API_KEY" if LLM_PROVIDER == "anthropic" else "OPENAI_API_KEY"
|
| 45 |
+
return (
|
| 46 |
+
f"β Error: {api_key_name} not configured. Please set it in your .env file.",
|
| 47 |
+
"",
|
| 48 |
+
None,
|
| 49 |
+
"",
|
| 50 |
+
""
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
# Check if MCP already exists for this URL
|
| 55 |
+
existing_mcp = mcp_registry.find_by_url(api_url)
|
| 56 |
+
|
| 57 |
+
if existing_mcp and not force_regenerate:
|
| 58 |
+
progress(0.5, desc="Found existing MCP, reusing...")
|
| 59 |
+
|
| 60 |
+
# Reuse existing MCP
|
| 61 |
+
mcp_id = existing_mcp['mcp_id']
|
| 62 |
+
mcp_path = HOSTED_MCPS_DIR / mcp_id
|
| 63 |
+
|
| 64 |
+
# Update last used timestamp
|
| 65 |
+
mcp_registry.update_last_used(api_url)
|
| 66 |
+
|
| 67 |
+
# Load existing files
|
| 68 |
+
server_code = (mcp_path / "server.py").read_text()
|
| 69 |
+
readme = (mcp_path / "README.md").read_text()
|
| 70 |
+
|
| 71 |
+
# Get hosted URLs
|
| 72 |
+
base_url = os.getenv("SPACE_HOST", "http://localhost:7860")
|
| 73 |
+
hosted_base_url = f"{base_url}/{mcp_id}"
|
| 74 |
+
hosted_info_url = f"{base_url}/{mcp_id}/info"
|
| 75 |
+
|
| 76 |
+
status_text = f"""β»οΈ **Reusing Existing MCP!**
|
| 77 |
+
|
| 78 |
+
**MCP ID:** `{mcp_id}`
|
| 79 |
+
**Originally Created:** {existing_mcp['created_at']}
|
| 80 |
+
**Last Used:** {existing_mcp['last_used']}
|
| 81 |
+
|
| 82 |
+
This MCP was already generated for this API URL. Using existing version to save time and API calls!
|
| 83 |
+
|
| 84 |
+
**π HTTP Transport (MCP 2025-03-26):**
|
| 85 |
+
- **Base URL:** `{hosted_base_url}`
|
| 86 |
+
- **Info:** `{hosted_info_url}`
|
| 87 |
+
- **Protocol:** JSON-RPC 2.0 over HTTP Streamable
|
| 88 |
+
- **Note:** Claude Desktop automatically appends `/mcp` to the base URL
|
| 89 |
+
|
| 90 |
+
π‘ **Tip:** To regenerate from scratch, check "Force Regenerate" below.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
# Create ZIP file
|
| 94 |
+
zip_buffer = io.BytesIO()
|
| 95 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
| 96 |
+
for file_path in mcp_path.rglob('*'):
|
| 97 |
+
if file_path.is_file():
|
| 98 |
+
arcname = file_path.relative_to(mcp_path.parent)
|
| 99 |
+
zipf.write(file_path, arcname)
|
| 100 |
+
|
| 101 |
+
zip_buffer.seek(0)
|
| 102 |
+
temp_zip = f"/tmp/{mcp_id}.zip"
|
| 103 |
+
with open(temp_zip, 'wb') as f:
|
| 104 |
+
f.write(zip_buffer.read())
|
| 105 |
+
|
| 106 |
+
connection_config = f"""# Local stdio transport:
|
| 107 |
+
{{
|
| 108 |
+
"mcpServers": {{
|
| 109 |
+
"{mcp_id}": {{
|
| 110 |
+
"command": "python",
|
| 111 |
+
"args": ["server.py"]
|
| 112 |
+
}}
|
| 113 |
+
}}
|
| 114 |
+
}}
|
| 115 |
+
|
| 116 |
+
# HTTP transport (hosted):
|
| 117 |
+
# Claude Desktop will automatically append /mcp to this URL
|
| 118 |
+
{{
|
| 119 |
+
"mcpServers": {{
|
| 120 |
+
"{mcp_id}": {{
|
| 121 |
+
"url": "{hosted_base_url}"
|
| 122 |
+
}}
|
| 123 |
+
}}
|
| 124 |
+
}}"""
|
| 125 |
+
|
| 126 |
+
# Prepare MCP info for deployment
|
| 127 |
+
mcp_info = {
|
| 128 |
+
"api_name": existing_mcp['api_name'],
|
| 129 |
+
"mcp_id": mcp_id
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
return (
|
| 133 |
+
status_text,
|
| 134 |
+
server_code,
|
| 135 |
+
temp_zip,
|
| 136 |
+
readme,
|
| 137 |
+
connection_config,
|
| 138 |
+
mcp_info # For HF deployment
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
# Generate new MCP
|
| 142 |
+
if existing_mcp:
|
| 143 |
+
progress(0.1, desc="Regenerating MCP (forced)...")
|
| 144 |
+
else:
|
| 145 |
+
progress(0.1, desc="Analyzing API...")
|
| 146 |
+
|
| 147 |
+
# Generate the MCP
|
| 148 |
+
result = await agent_factory.generate_mcp(api_url, api_key)
|
| 149 |
+
|
| 150 |
+
if result["status"] == "error":
|
| 151 |
+
return (
|
| 152 |
+
f"β Error: {result['error']}",
|
| 153 |
+
"",
|
| 154 |
+
None,
|
| 155 |
+
"",
|
| 156 |
+
"",
|
| 157 |
+
None # mcp_info for state
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
progress(0.6, desc="Generating code...")
|
| 161 |
+
|
| 162 |
+
# Get the generated files
|
| 163 |
+
mcp_id = result["mcp_id"]
|
| 164 |
+
server_code = result["server_code"]
|
| 165 |
+
readme = result["readme_content"]
|
| 166 |
+
|
| 167 |
+
progress(0.8, desc="Starting MCP server...")
|
| 168 |
+
|
| 169 |
+
# Start the MCP server
|
| 170 |
+
start_result = await mcp_host.start_mcp(mcp_id)
|
| 171 |
+
|
| 172 |
+
# Get the hosted URL (will be updated when deployed to HuggingFace)
|
| 173 |
+
base_url = os.getenv("SPACE_HOST", "http://localhost:7860")
|
| 174 |
+
hosted_base_url = f"{base_url}/{mcp_id}"
|
| 175 |
+
hosted_info_url = f"{base_url}/{mcp_id}/info"
|
| 176 |
+
|
| 177 |
+
if not start_result["success"]:
|
| 178 |
+
status_text = f"β οΈ MCP generated but failed to start locally: {start_result.get('error')}\n\n**HTTP Base URL:** {hosted_base_url}"
|
| 179 |
+
else:
|
| 180 |
+
status_text = f"""β
**MCP Server Generated & Hosted!**
|
| 181 |
+
|
| 182 |
+
**MCP ID:** `{mcp_id}`
|
| 183 |
+
**Status:** {start_result['status']}
|
| 184 |
+
|
| 185 |
+
**π HTTP Transport (MCP 2025-03-26):**
|
| 186 |
+
- **Base URL:** `{hosted_base_url}`
|
| 187 |
+
- **Info:** `{hosted_info_url}`
|
| 188 |
+
- **Protocol:** JSON-RPC 2.0 over HTTP Streamable
|
| 189 |
+
- **Note:** Claude Desktop automatically appends `/mcp` to the base URL
|
| 190 |
+
|
| 191 |
+
**π¦ Local Use (stdio):**
|
| 192 |
+
- Download ZIP below and extract
|
| 193 |
+
- Configure in Claude Desktop (see Connection Config tab)
|
| 194 |
+
|
| 195 |
+
Your MCP server is live and accessible via HTTP! π
|
| 196 |
+
"""
|
| 197 |
+
|
| 198 |
+
progress(0.9, desc="Creating download package...")
|
| 199 |
+
|
| 200 |
+
# Create ZIP file for download
|
| 201 |
+
zip_buffer = io.BytesIO()
|
| 202 |
+
mcp_path = Path(result["download_path"])
|
| 203 |
+
|
| 204 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
| 205 |
+
for file_path in mcp_path.rglob('*'):
|
| 206 |
+
if file_path.is_file():
|
| 207 |
+
arcname = file_path.relative_to(mcp_path.parent)
|
| 208 |
+
zipf.write(file_path, arcname)
|
| 209 |
+
|
| 210 |
+
zip_buffer.seek(0)
|
| 211 |
+
|
| 212 |
+
# Save to temp file for Gradio
|
| 213 |
+
temp_zip = f"/tmp/{mcp_id}.zip"
|
| 214 |
+
with open(temp_zip, 'wb') as f:
|
| 215 |
+
f.write(zip_buffer.read())
|
| 216 |
+
|
| 217 |
+
# Create connection configs for both transports
|
| 218 |
+
connection_config = f"""# Local stdio transport (extract ZIP first):
|
| 219 |
+
{{
|
| 220 |
+
"mcpServers": {{
|
| 221 |
+
"{mcp_id}": {{
|
| 222 |
+
"command": "python",
|
| 223 |
+
"args": ["server.py"]
|
| 224 |
+
}}
|
| 225 |
+
}}
|
| 226 |
+
}}
|
| 227 |
+
|
| 228 |
+
# HTTP transport (use hosted endpoint):
|
| 229 |
+
# Claude Desktop will automatically append /mcp to this URL
|
| 230 |
+
{{
|
| 231 |
+
"mcpServers": {{
|
| 232 |
+
"{mcp_id}": {{
|
| 233 |
+
"url": "{hosted_base_url}"
|
| 234 |
+
}}
|
| 235 |
+
}}
|
| 236 |
+
}}"""
|
| 237 |
+
|
| 238 |
+
progress(1.0, desc="Done!")
|
| 239 |
+
|
| 240 |
+
# Prepare MCP info for deployment
|
| 241 |
+
mcp_info = {
|
| 242 |
+
"api_name": state['api_name'],
|
| 243 |
+
"mcp_id": mcp_id
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
return (
|
| 247 |
+
status_text,
|
| 248 |
+
server_code,
|
| 249 |
+
temp_zip,
|
| 250 |
+
readme,
|
| 251 |
+
connection_config,
|
| 252 |
+
mcp_info # For HF deployment
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
except Exception as e:
|
| 256 |
+
return (
|
| 257 |
+
f"β Unexpected error: {str(e)}",
|
| 258 |
+
"",
|
| 259 |
+
None,
|
| 260 |
+
"",
|
| 261 |
+
"",
|
| 262 |
+
None # mcp_info for state
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def deploy_to_hf_space(hf_token: str, mcp_info: dict) -> str:
|
| 267 |
+
"""Deploy generated MCP to HuggingFace Space
|
| 268 |
+
|
| 269 |
+
Args:
|
| 270 |
+
hf_token: HuggingFace API token
|
| 271 |
+
mcp_info: Dict with api_name and mcp_id
|
| 272 |
+
|
| 273 |
+
Returns:
|
| 274 |
+
Deployment status message
|
| 275 |
+
"""
|
| 276 |
+
if not hf_token:
|
| 277 |
+
return "β Please enter your HuggingFace token above"
|
| 278 |
+
|
| 279 |
+
if not mcp_info or not mcp_info.get("mcp_id"):
|
| 280 |
+
return "β Please generate an MCP first before deploying"
|
| 281 |
+
|
| 282 |
+
try:
|
| 283 |
+
api_name = mcp_info["api_name"]
|
| 284 |
+
mcp_id = mcp_info["mcp_id"]
|
| 285 |
+
mcp_dir = HOSTED_MCPS_DIR / mcp_id
|
| 286 |
+
|
| 287 |
+
if not mcp_dir.exists():
|
| 288 |
+
return f"β MCP directory not found: {mcp_id}"
|
| 289 |
+
|
| 290 |
+
# Deploy to HuggingFace
|
| 291 |
+
result = deploy_to_huggingface(
|
| 292 |
+
mcp_dir=mcp_dir,
|
| 293 |
+
api_name=api_name,
|
| 294 |
+
mcp_id=mcp_id,
|
| 295 |
+
hf_token=hf_token
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
if result["success"]:
|
| 299 |
+
return f"""β
**Deployed Successfully!**
|
| 300 |
+
|
| 301 |
+
**Space URL:** [{result['repo_id']}]({result['space_url']})
|
| 302 |
+
|
| 303 |
+
**MCP Endpoint:** `{result['mcp_endpoint']}`
|
| 304 |
+
|
| 305 |
+
**Next Steps:**
|
| 306 |
+
1. Visit your Space (may take 1-2 min to build)
|
| 307 |
+
2. Copy the MCP endpoint URL
|
| 308 |
+
3. Add to Claude Desktop config:
|
| 309 |
+
```json
|
| 310 |
+
{{
|
| 311 |
+
"mcpServers": {{
|
| 312 |
+
"{mcp_id}": {{
|
| 313 |
+
"url": "{result['mcp_endpoint'].replace('/mcp', '')}"
|
| 314 |
+
}}
|
| 315 |
+
}}
|
| 316 |
+
}}
|
| 317 |
+
```
|
| 318 |
+
|
| 319 |
+
π Your MCP is now live and accessible!
|
| 320 |
+
"""
|
| 321 |
+
else:
|
| 322 |
+
return f"β **Deployment Failed**\n\nError: {result['error']}"
|
| 323 |
+
|
| 324 |
+
except Exception as e:
|
| 325 |
+
return f"β **Deployment Error**\n\n{str(e)}"
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
# Build Gradio Interface
|
| 329 |
+
with gr.Blocks(
|
| 330 |
+
title="MCP Generator"
|
| 331 |
+
) as app:
|
| 332 |
+
|
| 333 |
+
gr.Markdown("""
|
| 334 |
+
# π€ MCP Generator
|
| 335 |
+
## Turn Any API into an MCP Server in Seconds!
|
| 336 |
+
|
| 337 |
+
Simply enter an API URL and we'll generate a complete, working MCP server with:
|
| 338 |
+
- β
Automatically analyzed endpoints
|
| 339 |
+
- β
Generated MCP tools
|
| 340 |
+
- β
Complete documentation
|
| 341 |
+
- β
Ready to use immediately!
|
| 342 |
+
|
| 343 |
+
**Built for the MCP 1st Birthday Hackathon** π
|
| 344 |
+
""")
|
| 345 |
+
|
| 346 |
+
with gr.Accordion("βΉοΈ API URL Guidelines & Tips", open=False):
|
| 347 |
+
gr.Markdown("""
|
| 348 |
+
### β
What Works Best:
|
| 349 |
+
- **Base API URLs** (e.g., `https://api.example.com`)
|
| 350 |
+
- **REST APIs** with clear endpoints
|
| 351 |
+
- **OpenAPI/Swagger** documented APIs
|
| 352 |
+
- **Public APIs** (no complex auth)
|
| 353 |
+
|
| 354 |
+
### π― Try These Free APIs:
|
| 355 |
+
|
| 356 |
+
**No Auth Required (Perfect for Testing!):**
|
| 357 |
+
- `https://jsonplaceholder.typicode.com` - Fake REST API (best for testing!)
|
| 358 |
+
- `https://api.github.com` - GitHub public API
|
| 359 |
+
- `https://dog.ceo/api` - Random dog images
|
| 360 |
+
- `https://catfact.ninja` - Random cat facts
|
| 361 |
+
- `https://api.coindesk.com/v1/bpi` - Bitcoin prices
|
| 362 |
+
- `https://api.ipify.org` - Get IP address
|
| 363 |
+
|
| 364 |
+
**With API Key (Free Tier):**
|
| 365 |
+
- `https://api.openweathermap.org/data/2.5` - Weather data
|
| 366 |
+
- `https://newsapi.org/v2` - News articles
|
| 367 |
+
- `https://api.stripe.com` - Payment processing (test mode)
|
| 368 |
+
|
| 369 |
+
### π‘ Tips:
|
| 370 |
+
- **Start with jsonplaceholder.typicode.com** - always works!
|
| 371 |
+
- Paste the **base URL** (not a specific endpoint)
|
| 372 |
+
- If API needs a key, add it in the "API Key" field below
|
| 373 |
+
- Cached URLs generate instantly (try the same URL twice!)
|
| 374 |
+
|
| 375 |
+
### β οΈ May Not Work Well:
|
| 376 |
+
- GraphQL APIs (REST only for now)
|
| 377 |
+
- APIs requiring OAuth flows
|
| 378 |
+
- WebSocket-only APIs
|
| 379 |
+
- APIs with very complex authentication
|
| 380 |
+
""")
|
| 381 |
+
|
| 382 |
+
with gr.Row():
|
| 383 |
+
with gr.Column(scale=2):
|
| 384 |
+
gr.Markdown("### π Input")
|
| 385 |
+
|
| 386 |
+
api_url = gr.Textbox(
|
| 387 |
+
label="API URL or Documentation URL",
|
| 388 |
+
placeholder="https://api.example.com",
|
| 389 |
+
info="Enter the base URL or documentation URL of the API"
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
api_key = gr.Textbox(
|
| 393 |
+
label="API Key (Optional)",
|
| 394 |
+
placeholder="sk-...",
|
| 395 |
+
type="password",
|
| 396 |
+
info="If the API requires authentication"
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
force_regenerate = gr.Checkbox(
|
| 400 |
+
label="Force Regenerate",
|
| 401 |
+
value=False,
|
| 402 |
+
info="Regenerate even if MCP already exists for this URL (saves API calls when unchecked)"
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
generate_btn = gr.Button(
|
| 406 |
+
"π Generate & Host MCP Server",
|
| 407 |
+
variant="primary",
|
| 408 |
+
size="lg"
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
with gr.Accordion("π Quick Start Examples", open=True):
|
| 412 |
+
gr.Markdown("""
|
| 413 |
+
**Click to copy and paste:**
|
| 414 |
+
|
| 415 |
+
```
|
| 416 |
+
https://jsonplaceholder.typicode.com
|
| 417 |
+
```
|
| 418 |
+
β **Recommended first try!** Always works, no API key needed.
|
| 419 |
+
|
| 420 |
+
---
|
| 421 |
+
|
| 422 |
+
**More examples:**
|
| 423 |
+
- `https://api.github.com` - GitHub API (no auth)
|
| 424 |
+
- `https://dog.ceo/api` - Dog images (fun!)
|
| 425 |
+
- `https://catfact.ninja` - Cat facts (simple)
|
| 426 |
+
|
| 427 |
+
π‘ **Tip:** MCPs are cached - try the same URL twice to see instant results!
|
| 428 |
+
""")
|
| 429 |
+
|
| 430 |
+
gr.Markdown("---")
|
| 431 |
+
|
| 432 |
+
with gr.Row():
|
| 433 |
+
with gr.Column():
|
| 434 |
+
gr.Markdown("### π Results")
|
| 435 |
+
|
| 436 |
+
status_output = gr.Markdown(label="Status")
|
| 437 |
+
|
| 438 |
+
with gr.Tab("Generated Code"):
|
| 439 |
+
code_output = gr.Code(
|
| 440 |
+
label="server.py",
|
| 441 |
+
language="python",
|
| 442 |
+
lines=20
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
with gr.Tab("README"):
|
| 446 |
+
readme_output = gr.Markdown()
|
| 447 |
+
|
| 448 |
+
with gr.Tab("Connection Config"):
|
| 449 |
+
connection_output = gr.Code(
|
| 450 |
+
label="Claude Desktop Config",
|
| 451 |
+
language="json"
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
download_output = gr.File(
|
| 455 |
+
label="π¦ Download Complete Package (ZIP)"
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
# HuggingFace Deployment Section
|
| 459 |
+
gr.Markdown("---")
|
| 460 |
+
gr.Markdown("### π One-Click Deploy to HuggingFace")
|
| 461 |
+
|
| 462 |
+
gr.Markdown("""
|
| 463 |
+
β οΈ **Security Best Practices:**
|
| 464 |
+
- Use a **temporary, disposable token** that you'll delete immediately after deployment
|
| 465 |
+
- **Required permissions:** `write` access (to create Spaces)
|
| 466 |
+
- **Recommended flow:** Create token β Deploy β Delete token
|
| 467 |
+
- Get tokens from: [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)
|
| 468 |
+
|
| 469 |
+
π‘ **How to create a safe token:**
|
| 470 |
+
1. Go to HuggingFace β Settings β Access Tokens
|
| 471 |
+
2. Click "New token"
|
| 472 |
+
3. Name: `mcp-temp-deploy` (or similar)
|
| 473 |
+
4. Type: **Write** (required to create Spaces)
|
| 474 |
+
5. Click "Generate" β Copy the token
|
| 475 |
+
6. Paste below and deploy
|
| 476 |
+
7. **β οΈ DELETE THE TOKEN** immediately after deployment succeeds!
|
| 477 |
+
""")
|
| 478 |
+
|
| 479 |
+
with gr.Row():
|
| 480 |
+
hf_token_input = gr.Textbox(
|
| 481 |
+
label="HuggingFace Token (hidden with β’β’β’β’β’β’)",
|
| 482 |
+
placeholder="hf_β’β’β’β’β’β’β’β’β’β’β’β’β’β’β’β’β’β’β’β’β’β’β’β’",
|
| 483 |
+
type="password",
|
| 484 |
+
info="β οΈ Use a TEMPORARY token with 'write' permission. Delete it after deploying!"
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
with gr.Row():
|
| 488 |
+
deploy_hf_btn = gr.Button(
|
| 489 |
+
"π Deploy to HuggingFace Space",
|
| 490 |
+
variant="secondary",
|
| 491 |
+
size="lg"
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
hf_deploy_status = gr.Markdown(label="Deployment Status")
|
| 495 |
+
|
| 496 |
+
# Store the last generated MCP info for deployment
|
| 497 |
+
last_mcp_state = gr.State(value=None)
|
| 498 |
+
|
| 499 |
+
# Wire up the generation button
|
| 500 |
+
generate_btn.click(
|
| 501 |
+
fn=generate_and_host_mcp,
|
| 502 |
+
inputs=[api_url, api_key, force_regenerate],
|
| 503 |
+
outputs=[
|
| 504 |
+
status_output,
|
| 505 |
+
code_output,
|
| 506 |
+
download_output,
|
| 507 |
+
readme_output,
|
| 508 |
+
connection_output,
|
| 509 |
+
last_mcp_state # Store MCP info for deployment
|
| 510 |
+
]
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
# Wire up the HuggingFace deployment button
|
| 514 |
+
deploy_hf_btn.click(
|
| 515 |
+
fn=deploy_to_hf_space,
|
| 516 |
+
inputs=[hf_token_input, last_mcp_state],
|
| 517 |
+
outputs=[hf_deploy_status]
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
with gr.Accordion("π Previously Generated MCPs", open=False):
|
| 521 |
+
def get_existing_mcps():
|
| 522 |
+
"""Get list of existing MCPs for display"""
|
| 523 |
+
mcps = mcp_registry.list_all()
|
| 524 |
+
if not mcps:
|
| 525 |
+
return "No MCPs generated yet. Generate your first one above! π"
|
| 526 |
+
|
| 527 |
+
output = "| API Name | URL | Created | Last Used |\n"
|
| 528 |
+
output += "|----------|-----|---------|----------|\n"
|
| 529 |
+
for mcp in mcps[:10]: # Show last 10
|
| 530 |
+
api_name = mcp['api_name']
|
| 531 |
+
api_url = mcp['api_url'][:40] + "..." if len(mcp['api_url']) > 40 else mcp['api_url']
|
| 532 |
+
created = mcp['created_at'].split('T')[0]
|
| 533 |
+
last_used = mcp['last_used'].split('T')[0]
|
| 534 |
+
output += f"| {api_name} | {api_url} | {created} | {last_used} |\n"
|
| 535 |
+
|
| 536 |
+
return output
|
| 537 |
+
|
| 538 |
+
existing_mcps_display = gr.Markdown(get_existing_mcps())
|
| 539 |
+
refresh_btn = gr.Button("π Refresh List", size="sm")
|
| 540 |
+
refresh_btn.click(fn=get_existing_mcps, outputs=existing_mcps_display)
|
| 541 |
+
|
| 542 |
+
gr.Markdown("""
|
| 543 |
+
---
|
| 544 |
+
### π― How to Use Your Generated MCP
|
| 545 |
+
|
| 546 |
+
1. **Download** the ZIP file above
|
| 547 |
+
2. **Extract** it to a folder
|
| 548 |
+
3. **Add** the connection config to your Claude Desktop settings
|
| 549 |
+
4. **Restart** Claude Desktop
|
| 550 |
+
|
| 551 |
+
Your MCP server is ready to use! π
|
| 552 |
+
|
| 553 |
+
### π About This Project
|
| 554 |
+
|
| 555 |
+
This is a meta-MCP: an MCP server that generates other MCP servers!
|
| 556 |
+
|
| 557 |
+
- Built with [Gradio](https://gradio.app)
|
| 558 |
+
- Powered by [LangGraph](https://github.com/langchain-ai/langgraph) agents
|
| 559 |
+
- Uses [Anthropic's Claude](https://anthropic.com) for code generation
|
| 560 |
+
- Integrates with [MCP Fetch Server](https://github.com/modelcontextprotocol/servers)
|
| 561 |
+
|
| 562 |
+
**For MCP 1st Birthday Hackathon - Track 2: MCP in Action** π
|
| 563 |
+
""")
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
if __name__ == "__main__":
|
| 567 |
+
# Check for API key
|
| 568 |
+
if not ANTHROPIC_API_KEY and not OPENAI_API_KEY:
|
| 569 |
+
print("β οΈ WARNING: No API key set!")
|
| 570 |
+
print("Please set either OPENAI_API_KEY or ANTHROPIC_API_KEY in your .env file")
|
| 571 |
+
print(f"Example: echo 'OPENAI_API_KEY=your_key_here' > .env")
|
| 572 |
+
|
| 573 |
+
# Launch Gradio UI
|
| 574 |
+
app.launch(
|
| 575 |
+
server_name="0.0.0.0",
|
| 576 |
+
server_port=7860,
|
| 577 |
+
share=False
|
| 578 |
+
)
|
requirements.txt
CHANGED
|
@@ -10,3 +10,4 @@ aiohttp
|
|
| 10 |
fastapi
|
| 11 |
uvicorn
|
| 12 |
httpx
|
|
|
|
|
|
| 10 |
fastapi
|
| 11 |
uvicorn
|
| 12 |
httpx
|
| 13 |
+
huggingface_hub>=0.20.0
|
src/hf_deployer.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HuggingFace Space Auto-Deployer - One-click MCP deployment"""
|
| 2 |
+
|
| 3 |
+
from huggingface_hub import HfApi, create_repo, upload_file
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import re
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class HFSpaceDeployer:
|
| 10 |
+
"""Deploys generated MCPs to HuggingFace Spaces"""
|
| 11 |
+
|
| 12 |
+
def __init__(self, token: str):
|
| 13 |
+
"""Initialize with HuggingFace token
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
token: HuggingFace API token
|
| 17 |
+
"""
|
| 18 |
+
self.api = HfApi(token=token)
|
| 19 |
+
self.token = token
|
| 20 |
+
|
| 21 |
+
def deploy_mcp(self, mcp_dir: Path, api_name: str, mcp_id: str) -> dict:
|
| 22 |
+
"""Deploy an MCP to a new HuggingFace Space
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
mcp_dir: Path to the MCP directory
|
| 26 |
+
api_name: Name of the API (for Space name)
|
| 27 |
+
mcp_id: MCP ID
|
| 28 |
+
|
| 29 |
+
Returns:
|
| 30 |
+
dict with deployment info (url, repo_id, etc.)
|
| 31 |
+
"""
|
| 32 |
+
try:
|
| 33 |
+
# Get username
|
| 34 |
+
user_info = self.api.whoami()
|
| 35 |
+
username = user_info['name']
|
| 36 |
+
|
| 37 |
+
# Create Space name (URL-safe)
|
| 38 |
+
space_name = f"mcp-{api_name.lower().replace(' ', '-')}"
|
| 39 |
+
repo_id = f"{username}/{space_name}"
|
| 40 |
+
|
| 41 |
+
# Create the Space
|
| 42 |
+
print(f"Creating Space: {repo_id}...")
|
| 43 |
+
create_repo(
|
| 44 |
+
repo_id=repo_id,
|
| 45 |
+
repo_type="space",
|
| 46 |
+
space_sdk="gradio",
|
| 47 |
+
exist_ok=True,
|
| 48 |
+
token=self.token
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# Create app.py wrapper for the Space
|
| 52 |
+
app_py_content = self._generate_space_app_py(mcp_id)
|
| 53 |
+
app_py_path = mcp_dir / "space_app.py"
|
| 54 |
+
app_py_path.write_text(app_py_content)
|
| 55 |
+
|
| 56 |
+
# Update README with Space frontmatter
|
| 57 |
+
self._update_readme_for_space(mcp_dir / "README.md", api_name, space_name)
|
| 58 |
+
|
| 59 |
+
# Upload files
|
| 60 |
+
print(f"Uploading files to {repo_id}...")
|
| 61 |
+
files_to_upload = [
|
| 62 |
+
("space_app.py", "app.py"), # Rename to app.py for Space
|
| 63 |
+
("server_http.py", "server_http.py"),
|
| 64 |
+
("requirements.txt", "requirements.txt"),
|
| 65 |
+
("README.md", "README.md"),
|
| 66 |
+
]
|
| 67 |
+
|
| 68 |
+
for local_name, remote_name in files_to_upload:
|
| 69 |
+
local_path = mcp_dir / local_name
|
| 70 |
+
if local_path.exists():
|
| 71 |
+
upload_file(
|
| 72 |
+
path_or_fileobj=str(local_path),
|
| 73 |
+
path_in_repo=remote_name,
|
| 74 |
+
repo_id=repo_id,
|
| 75 |
+
repo_type="space",
|
| 76 |
+
token=self.token
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
space_url = f"https://huggingface.co/spaces/{repo_id}"
|
| 80 |
+
|
| 81 |
+
return {
|
| 82 |
+
"success": True,
|
| 83 |
+
"space_url": space_url,
|
| 84 |
+
"repo_id": repo_id,
|
| 85 |
+
"mcp_endpoint": f"https://{username}-{space_name}.hf.space/mcp",
|
| 86 |
+
"message": f"β
Deployed to {space_url}"
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
except Exception as e:
|
| 90 |
+
return {
|
| 91 |
+
"success": False,
|
| 92 |
+
"error": str(e),
|
| 93 |
+
"message": f"β Deployment failed: {str(e)}"
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
def _generate_space_app_py(self, mcp_id: str) -> str:
|
| 97 |
+
"""Generate app.py for HuggingFace Space"""
|
| 98 |
+
return f'''"""
|
| 99 |
+
MCP Server Space - Auto-generated by MCP Generator
|
| 100 |
+
This Space runs an MCP server via HTTP transport.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
import gradio as gr
|
| 104 |
+
from server_http import app as fastapi_app
|
| 105 |
+
|
| 106 |
+
# Create a simple Gradio interface for the Space
|
| 107 |
+
with gr.Blocks() as demo:
|
| 108 |
+
gr.Markdown("""
|
| 109 |
+
# π€ MCP Server Running!
|
| 110 |
+
|
| 111 |
+
This Space is hosting an MCP server with HTTP transport.
|
| 112 |
+
|
| 113 |
+
## π How to Connect:
|
| 114 |
+
|
| 115 |
+
Add this to your Claude Desktop config:
|
| 116 |
+
|
| 117 |
+
```json
|
| 118 |
+
{{
|
| 119 |
+
"mcpServers": {{
|
| 120 |
+
"{mcp_id}": {{
|
| 121 |
+
"url": "https://YOUR-USERNAME-SPACE-NAME.hf.space"
|
| 122 |
+
}}
|
| 123 |
+
}}
|
| 124 |
+
}}
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
**Note:** Replace `YOUR-USERNAME-SPACE-NAME` with this Space's actual URL.
|
| 128 |
+
|
| 129 |
+
## π‘ Endpoints:
|
| 130 |
+
|
| 131 |
+
- `/mcp` - Main MCP endpoint (JSON-RPC 2.0)
|
| 132 |
+
- `/health` - Health check
|
| 133 |
+
- `/info` - Server information
|
| 134 |
+
|
| 135 |
+
## π Your MCP is live and ready to use!
|
| 136 |
+
|
| 137 |
+
Generated by [MCP Generator](https://huggingface.co/spaces/MCP-1st-Birthday/mcp-generator)
|
| 138 |
+
""")
|
| 139 |
+
|
| 140 |
+
# Mount Gradio to FastAPI
|
| 141 |
+
app = gr.routes.App.create_app(demo)
|
| 142 |
+
fastapi_app.mount("/ui", app)
|
| 143 |
+
|
| 144 |
+
# Export the FastAPI app for HuggingFace Spaces
|
| 145 |
+
# Spaces will run this with: uvicorn app:fastapi_app
|
| 146 |
+
'''
|
| 147 |
+
|
| 148 |
+
def _update_readme_for_space(self, readme_path: Path, api_name: str, space_name: str):
|
| 149 |
+
"""Update README.md with Space-specific YAML frontmatter"""
|
| 150 |
+
content = readme_path.read_text()
|
| 151 |
+
|
| 152 |
+
# Add YAML frontmatter
|
| 153 |
+
frontmatter = f"""---
|
| 154 |
+
title: {api_name} MCP Server
|
| 155 |
+
emoji: π€
|
| 156 |
+
colorFrom: blue
|
| 157 |
+
colorTo: purple
|
| 158 |
+
sdk: gradio
|
| 159 |
+
sdk_version: 5.9.1
|
| 160 |
+
app_file: app.py
|
| 161 |
+
pinned: false
|
| 162 |
+
license: mit
|
| 163 |
+
tags:
|
| 164 |
+
- mcp
|
| 165 |
+
- model-context-protocol
|
| 166 |
+
- api
|
| 167 |
+
- mcp-server
|
| 168 |
+
---
|
| 169 |
+
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
+
# Prepend frontmatter to existing README
|
| 173 |
+
updated_content = frontmatter + content
|
| 174 |
+
readme_path.write_text(updated_content)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def deploy_to_huggingface(mcp_dir: Path, api_name: str, mcp_id: str, hf_token: str) -> dict:
|
| 178 |
+
"""Helper function to deploy an MCP to HuggingFace Spaces
|
| 179 |
+
|
| 180 |
+
Args:
|
| 181 |
+
mcp_dir: Path to MCP directory
|
| 182 |
+
api_name: API name
|
| 183 |
+
mcp_id: MCP ID
|
| 184 |
+
hf_token: HuggingFace API token
|
| 185 |
+
|
| 186 |
+
Returns:
|
| 187 |
+
dict with deployment result
|
| 188 |
+
"""
|
| 189 |
+
deployer = HFSpaceDeployer(token=hf_token)
|
| 190 |
+
return deployer.deploy_mcp(mcp_dir, api_name, mcp_id)
|
src/mcp_http_host.py
CHANGED
|
@@ -17,21 +17,7 @@ class MCPHTTPHost:
|
|
| 17 |
self.app = FastAPI(title="MCP Generator - Hosted MCPs")
|
| 18 |
self.loaded_mcps: Dict[str, Any] = {}
|
| 19 |
|
| 20 |
-
#
|
| 21 |
-
@self.app.get("/")
|
| 22 |
-
async def root():
|
| 23 |
-
return {
|
| 24 |
-
"service": "MCP Generator",
|
| 25 |
-
"hosted_mcps": list(self.loaded_mcps.keys()),
|
| 26 |
-
"endpoints": {
|
| 27 |
-
"list_all": "/mcps",
|
| 28 |
-
"mcp_endpoint": "/{mcp_id}/mcp",
|
| 29 |
-
"mcp_info": "/{mcp_id}/info",
|
| 30 |
-
"mcp_health": "/{mcp_id}/health"
|
| 31 |
-
},
|
| 32 |
-
"usage": "Configure in Claude Desktop with: {\"url\": \"https://your-space.hf.space/{mcp_id}\"}"
|
| 33 |
-
}
|
| 34 |
-
|
| 35 |
@self.app.get("/mcps")
|
| 36 |
async def list_mcps():
|
| 37 |
"""List all hosted MCPs"""
|
|
|
|
| 17 |
self.app = FastAPI(title="MCP Generator - Hosted MCPs")
|
| 18 |
self.loaded_mcps: Dict[str, Any] = {}
|
| 19 |
|
| 20 |
+
# List all hosted MCPs endpoint
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
@self.app.get("/mcps")
|
| 22 |
async def list_mcps():
|
| 23 |
"""List all hosted MCPs"""
|