mcp-server / deploy_to_hf.py
Peter Yang
Move docker-mcp-server contents to root
d884bf1
#!/usr/bin/env python3
"""
Deployment script for Hugging Face Spaces
This script helps deploy the MCP server to Hugging Face Spaces.
"""
import os
import shutil
import subprocess
import sys
import argparse
from pathlib import Path
def check_git():
"""Check if git is available."""
try:
subprocess.run(["git", "--version"], capture_output=True, check=True)
return True
except (subprocess.CalledProcessError, FileNotFoundError):
print("❌ Git is not installed or not available in PATH")
return False
def check_huggingface_hub():
"""Check if huggingface_hub is available."""
try:
import huggingface_hub
return True
except ImportError:
print("❌ huggingface_hub is not installed")
print("Install it with: pip install huggingface_hub")
return False
def create_space_files(space_dir: Path):
"""Create the necessary files for Hugging Face Spaces."""
# Copy main files
shutil.copy("app.py", space_dir / "app.py")
shutil.copy("requirements.txt", space_dir / "requirements.txt")
# Create README for the space
readme_content = """---
title: MCP Sentiment Analysis Server
emoji: 🎭
colorFrom: blue
colorTo: purple
sdk: gradio
sdk_version: "5.0.0"
app_file: app.py
pinned: false
license: mit
---
# MCP Sentiment Analysis Server
This is a Model Context Protocol (MCP) server that provides sentiment analysis capabilities.
## Features
- Comprehensive sentiment analysis
- Numerical sentiment scoring
- Emotion classification
- Batch text processing
- Full MCP protocol support
## Usage
### Web Interface
Use the interface above to test the sentiment analysis tools.
### MCP Endpoint
Connect your MCP clients to: `https://YOUR_USERNAME-SPACE_NAME.hf.space/gradio_api/mcp/sse`
### Available Tools
- `analyze_sentiment`: Comprehensive sentiment analysis
- `get_sentiment_score`: Numerical sentiment scoring (-1 to 1)
- `classify_emotion`: Basic emotion classification
- `batch_analyze`: Analyze multiple texts at once
## Example with smolagents
```python
from smolagents.mcp_client import MCPClient
with MCPClient(
{"url": "https://YOUR_USERNAME-SPACE_NAME.hf.space/gradio_api/mcp/sse"}
) as tools:
for tool in tools:
print(f"{tool.name}: {tool.description}")
```
## Example with Cursor IDE
Add to your MCP configuration:
```json
{
"mcpServers": {
"sentiment-analysis": {
"command": "npx",
"args": [
"-y",
"mcp-remote",
"https://YOUR_USERNAME-SPACE_NAME.hf.space/gradio_api/mcp/sse",
"--transport",
"sse-only"
]
}
}
}
```
"""
with open(space_dir / "README.md", "w") as f:
f.write(readme_content)
print(f"βœ… Created space files in {space_dir}")
def deploy_with_git(space_name: str, username: str):
"""Deploy using git commands."""
space_dir = Path(f"./hf_space_{space_name}")
if space_dir.exists():
print(f"Directory {space_dir} already exists. Remove it first or use a different name.")
return False
try:
# Clone the space repository
repo_url = f"https://huggingface.co/spaces/{username}/{space_name}"
print(f"Cloning {repo_url}...")
subprocess.run(["git", "clone", repo_url, str(space_dir)], check=True)
# Create space files
create_space_files(space_dir)
# Git operations
os.chdir(space_dir)
subprocess.run(["git", "add", "."], check=True)
subprocess.run(["git", "commit", "-m", "Deploy MCP sentiment analysis server"], check=True)
subprocess.run(["git", "push"], check=True)
print(f"βœ… Successfully deployed to {repo_url}")
print(f"🌐 Your space will be available at: https://{username}-{space_name}.hf.space")
print(f"πŸ”— MCP endpoint: https://{username}-{space_name}.hf.space/gradio_api/mcp/sse")
return True
except subprocess.CalledProcessError as e:
print(f"❌ Git operation failed: {e}")
return False
except Exception as e:
print(f"❌ Deployment failed: {e}")
return False
finally:
# Go back to original directory
os.chdir("..")
def deploy_with_hub_api(space_name: str, username: str):
"""Deploy using Hugging Face Hub API."""
try:
from huggingface_hub import HfApi, create_repo
api = HfApi()
# Create the space repository
repo_id = f"{username}/{space_name}"
print(f"Creating space {repo_id}...")
create_repo(
repo_id=repo_id,
repo_type="space",
space_sdk="gradio",
exist_ok=True
)
# Upload files
print("Uploading files...")
api.upload_file(
path_or_fileobj="app.py",
path_in_repo="app.py",
repo_id=repo_id,
repo_type="space"
)
api.upload_file(
path_or_fileobj="requirements.txt",
path_in_repo="requirements.txt",
repo_id=repo_id,
repo_type="space"
)
# Create and upload README
space_dir = Path("./temp_space")
space_dir.mkdir(exist_ok=True)
create_space_files(space_dir)
api.upload_file(
path_or_fileobj=str(space_dir / "README.md"),
path_in_repo="README.md",
repo_id=repo_id,
repo_type="space"
)
# Cleanup
shutil.rmtree(space_dir)
print(f"βœ… Successfully deployed to https://huggingface.co/spaces/{repo_id}")
print(f"🌐 Your space will be available at: https://{username}-{space_name}.hf.space")
print(f"πŸ”— MCP endpoint: https://{username}-{space_name}.hf.space/gradio_api/mcp/sse")
return True
except Exception as e:
print(f"❌ Hub API deployment failed: {e}")
return False
def main():
parser = argparse.ArgumentParser(description="Deploy MCP server to Hugging Face Spaces")
parser.add_argument("space_name", help="Name of the Hugging Face Space")
parser.add_argument("username", help="Your Hugging Face username")
parser.add_argument("--method", choices=["git", "api"], default="git",
help="Deployment method (default: git)")
parser.add_argument("--check-only", action="store_true",
help="Only check prerequisites without deploying")
args = parser.parse_args()
print("πŸš€ MCP Server Deployment to Hugging Face Spaces")
print("=" * 50)
# Check prerequisites
print("Checking prerequisites...")
if not Path("app.py").exists():
print("❌ app.py not found in current directory")
return 1
if not Path("requirements.txt").exists():
print("❌ requirements.txt not found in current directory")
return 1
git_ok = check_git()
hub_ok = check_huggingface_hub()
if args.method == "git" and not git_ok:
print("❌ Git method selected but git is not available")
return 1
if args.method == "api" and not hub_ok:
print("❌ API method selected but huggingface_hub is not available")
return 1
if args.check_only:
print("βœ… All prerequisites check passed")
return 0
# Deploy
print(f"\nDeploying '{args.space_name}' for user '{args.username}' using {args.method} method...")
if args.method == "git":
success = deploy_with_git(args.space_name, args.username)
else:
success = deploy_with_hub_api(args.space_name, args.username)
if success:
print("\nπŸŽ‰ Deployment completed successfully!")
print("\nNext steps:")
print("1. Wait a few minutes for the space to build")
print("2. Test the web interface")
print("3. Test the MCP endpoint with your clients")
return 0
else:
print("\nπŸ’₯ Deployment failed!")
return 1
if __name__ == "__main__":
sys.exit(main())