NiWaRe commited on
Commit
d1338b0
·
1 Parent(s): 561151f

add main route directly to mcp fastapi

Browse files
Files changed (1) hide show
  1. app.py +37 -70
app.py CHANGED
@@ -2,8 +2,7 @@
2
  """
3
  HuggingFace Spaces entry point for the Weights & Biases MCP Server.
4
 
5
- This script creates a FastAPI application with a landing page and mounts
6
- the MCP server using the Streamable HTTP transport at /mcp for Hugging Face Spaces deployment.
7
  """
8
 
9
  import os
@@ -14,18 +13,17 @@ from pathlib import Path
14
  # Add the src directory to Python path
15
  sys.path.insert(0, str(Path(__file__).parent / "src"))
16
 
17
- from fastapi import FastAPI
18
  from fastapi.responses import HTMLResponse
19
  from fastapi.middleware.cors import CORSMiddleware
20
- import uvicorn
21
 
22
- # Import and configure the MCP server
23
  from wandb_mcp_server.server import (
24
  validate_and_get_api_key,
25
  setup_wandb_login,
26
  configure_wandb_logging,
27
  initialize_weave_tracing,
28
- create_mcp_server,
29
  ServerMCPArgs
30
  )
31
  from wandb_mcp_server.utils import get_rich_logger
@@ -38,46 +36,13 @@ logging.basicConfig(
38
 
39
  logger = get_rich_logger("huggingface-spaces-app")
40
 
41
- # Create the main FastAPI app
42
- app = FastAPI(
43
- title="Weights & Biases MCP Server",
44
- description="Model Context Protocol server for querying W&B data on Hugging Face Spaces",
45
- version="0.1.0"
46
- )
47
-
48
- # Add CORS middleware for browser compatibility
49
- app.add_middleware(
50
- CORSMiddleware,
51
- allow_origins=["*"],
52
- allow_credentials=True,
53
- allow_methods=["*"],
54
- allow_headers=["*"],
55
- )
56
-
57
  # Read the index.html file content
58
  INDEX_HTML_PATH = Path(__file__).parent / "index.html"
59
  with open(INDEX_HTML_PATH, "r") as f:
60
  INDEX_HTML_CONTENT = f.read()
61
 
62
- @app.get("/", response_class=HTMLResponse)
63
- async def index():
64
- """Serve the landing page."""
65
- return INDEX_HTML_CONTENT
66
-
67
- @app.get("/health")
68
- async def health():
69
- """Health check endpoint."""
70
- wandb_configured = bool(os.environ.get("WANDB_API_KEY"))
71
- return {
72
- "status": "healthy",
73
- "service": "wandb-mcp-server",
74
- "wandb_configured": wandb_configured
75
- }
76
-
77
- # Initialize W&B and MCP server on app startup
78
- @app.on_event("startup")
79
- async def startup_event():
80
- """Initialize W&B and MCP server on startup."""
81
  logger.info("Starting Weights & Biases MCP Server on HuggingFace Spaces")
82
 
83
  # Configure W&B logging behavior
@@ -108,41 +73,43 @@ async def startup_event():
108
  logger.warning("MCP server will start but operations will fail without a valid API key")
109
  logger.warning("Please set WANDB_API_KEY in the Space's environment variables")
110
 
111
- # Create and mount the MCP server
112
  logger.info("Creating MCP server for HTTP transport")
113
- mcp_server = create_mcp_server("http", "0.0.0.0", 7860)
114
-
115
- # Mount the MCP server to the /mcp path
116
- mcp_server.run(
117
- transport="streamable-http",
118
- http_app=app,
119
- http_path="/mcp"
120
  )
121
 
122
- logger.info("MCP server mounted at /mcp")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  logger.info("Landing page available at: /")
 
124
  logger.info("MCP endpoint (Streamable HTTP) available at: /mcp")
125
-
126
- @app.on_event("shutdown")
127
- async def shutdown_event():
128
- """Clean shutdown."""
129
- logger.info("Shutting down Weights & Biases MCP Server")
130
-
131
- def main():
132
- """Main entry point for HuggingFace Spaces."""
133
- # Force specific settings for HF Spaces
134
- port = 7860 # HF Spaces expects port 7860
135
- host = "0.0.0.0" # HF Spaces requires binding to all interfaces
136
 
137
- logger.info(f"Starting server on {host}:{port}")
138
-
139
- uvicorn.run(
140
- app,
141
- host=host,
142
- port=port,
143
- log_level="info",
144
- reload=False # Disable reload in production
145
- )
146
 
147
  if __name__ == "__main__":
148
  main()
 
2
  """
3
  HuggingFace Spaces entry point for the Weights & Biases MCP Server.
4
 
5
+ This script runs the MCP server with streamable HTTP transport for HF Spaces.
 
6
  """
7
 
8
  import os
 
13
  # Add the src directory to Python path
14
  sys.path.insert(0, str(Path(__file__).parent / "src"))
15
 
 
16
  from fastapi.responses import HTMLResponse
17
  from fastapi.middleware.cors import CORSMiddleware
18
+ from mcp.server.fastmcp import FastMCP
19
 
20
+ # Import and configure the MCP server components
21
  from wandb_mcp_server.server import (
22
  validate_and_get_api_key,
23
  setup_wandb_login,
24
  configure_wandb_logging,
25
  initialize_weave_tracing,
26
+ register_tools,
27
  ServerMCPArgs
28
  )
29
  from wandb_mcp_server.utils import get_rich_logger
 
36
 
37
  logger = get_rich_logger("huggingface-spaces-app")
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  # Read the index.html file content
40
  INDEX_HTML_PATH = Path(__file__).parent / "index.html"
41
  with open(INDEX_HTML_PATH, "r") as f:
42
  INDEX_HTML_CONTENT = f.read()
43
 
44
+ def main():
45
+ """Main entry point for HuggingFace Spaces."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  logger.info("Starting Weights & Biases MCP Server on HuggingFace Spaces")
47
 
48
  # Configure W&B logging behavior
 
73
  logger.warning("MCP server will start but operations will fail without a valid API key")
74
  logger.warning("Please set WANDB_API_KEY in the Space's environment variables")
75
 
76
+ # Create the MCP server
77
  logger.info("Creating MCP server for HTTP transport")
78
+ mcp = FastMCP(
79
+ "wandb-mcp-server",
80
+ host="0.0.0.0",
81
+ port=7860,
82
+ stateless_http=True
 
 
83
  )
84
 
85
+ # Register all W&B tools
86
+ register_tools(mcp)
87
+
88
+ # Add custom routes to the MCP server
89
+ # FastMCP creates routes using decorators, we can add our own
90
+ @mcp.get("/")
91
+ async def index():
92
+ """Serve the landing page."""
93
+ return HTMLResponse(content=INDEX_HTML_CONTENT)
94
+
95
+ @mcp.get("/health")
96
+ async def health():
97
+ """Health check endpoint."""
98
+ wandb_configured = bool(os.environ.get("WANDB_API_KEY"))
99
+ return {
100
+ "status": "healthy",
101
+ "service": "wandb-mcp-server",
102
+ "wandb_configured": wandb_configured
103
+ }
104
+
105
  logger.info("Landing page available at: /")
106
+ logger.info("Health check available at: /health")
107
  logger.info("MCP endpoint (Streamable HTTP) available at: /mcp")
108
+ logger.info(f"Starting server on 0.0.0.0:7860")
 
 
 
 
 
 
 
 
 
 
109
 
110
+ # Run the MCP server with streamable-http transport
111
+ # This will start the uvicorn server internally
112
+ mcp.run(transport="streamable-http")
 
 
 
 
 
 
113
 
114
  if __name__ == "__main__":
115
  main()