forked from sevalla-templates/python-demo-mcp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
63 lines (49 loc) · 1.6 KB
/
server.py
File metadata and controls
63 lines (49 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
import logging
import os
import random
import sys
import requests
from mcp.server.fastmcp import FastMCP
name="demo-mcp-server"
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(name)s - %(levelname)s - %(message)s',
handlers=[logging.StreamHandler()]
)
logger = logging.getLogger(name)
# Get port from environment variable or use 8080 as default
port = int(os.environ.get('PORT', 8080))
# Create server with lifespan
mcp = FastMCP(name, logger=logger, port=port)
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
logger.info(f"Tool called: add({a}, {b})")
return a + b
@mcp.tool()
def get_secret_word() -> str:
"""Get a random secret word"""
logger.info("Tool called: get_secret_word()")
return random.choice(["apple", "banana", "cherry"])
@mcp.tool()
def get_current_weather(city: str) -> str:
"""Get current weather for a city"""
logger.info(f"Tool called: get_current_weather({city})")
try:
endpoint = "https://wttr.in"
response = requests.get(f"{endpoint}/{city}", timeout=10)
response.raise_for_status() # Raise an exception for bad responses
return response.text
except requests.RequestException as e:
logger.error(f"Error fetching weather data: {str(e)}")
return f"Error fetching weather data: {str(e)}"
if __name__ == "__main__":
logger.info(f"Starting MCP Server on port {port}...")
try:
mcp.run(transport="sse")
except Exception as e:
logger.error(f"Server error: {str(e)}")
sys.exit(1)
finally:
logger.info("Server terminated")