LeoWalker's picture
feat(auth): add FastAPI token proxy for MCP HTTP, dual-server mode in main.py; add tests; docs and env example
aee78d5
#!/usr/bin/env python3
"""
FoodWise Remote MCP Server Entry Point
Entry point for HuggingFace Spaces deployment
"""
import os
import sys
from pathlib import Path
# Add the src directory to Python path
sys.path.insert(0, str(Path(__file__).parent / "src"))
# Load environment variables from a .env file if present
try:
from dotenv import load_dotenv
load_dotenv()
except Exception:
# Safe to continue if dotenv isn't available
pass
# Import and run the existing FastMCP server
from foodwise.mcp_server.main import mcp
"""
Minimal FastMCP HTTP entrypoint for Hugging Face Spaces.
Serves Streamable-HTTP at /mcp/ using FastMCP's built-in transport.
If MCP_AUTH_TOKEN is set, run in proxy mode:
- Start FastMCP HTTP on internal 127.0.0.1:7870
- Start FastAPI auth proxy on public PORT (default 7860)
"""
def main():
"""Start the MCP server for HuggingFace Spaces using FastMCP HTTP runner.
- If MCP_AUTH_TOKEN is present, run MCP upstream + auth proxy on public port
- Otherwise, run MCP directly on PORT for simplicity (current default)
"""
host = os.getenv("HOST", "0.0.0.0")
port = int(os.getenv("PORT", "7860"))
environment = os.getenv("ENVIRONMENT", "production")
print("πŸš€ Starting FoodWise MCP Server")
print(f" Environment: {environment}")
auth_token = os.getenv("MCP_AUTH_TOKEN")
if auth_token:
# Proxy mode: run MCP upstream on 127.0.0.1:7870 and proxy on PORT
upstream_host = os.getenv("UPSTREAM_HOST", "127.0.0.1")
upstream_port = int(os.getenv("UPSTREAM_PORT", "7870"))
print(f" Mode: Proxy (token enabled)")
print(f" Upstream MCP: http://{upstream_host}:{upstream_port}")
print(f" Proxy: http://{host}:{port}")
import threading
import uvicorn
def run_upstream() -> None:
mcp.run(transport="http", host=upstream_host, port=upstream_port, log_level="info")
upstream_thread = threading.Thread(target=run_upstream, name="mcp-upstream", daemon=True)
upstream_thread.start()
# Run proxy in main thread
from foodwise.mcp_server.auth_proxy import app as proxy_app
uvicorn.run(proxy_app, host=host, port=port, log_level="info")
return
# Default: direct MCP HTTP on PORT
print(f" Host: {host}:{port}")
print(" Mode: Direct HTTP (no auth token set)")
mcp.run(transport="http", host=host, port=port, log_level="info")
if __name__ == "__main__":
main()