fast2 / calculator_server.py
deepak191z's picture
Update calculator_server.py
97a889c verified
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError
import logging
import os
# Set up logging to see what's happening
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# 1. Create a FastMCP server instance
mcp = FastMCP(name="Calculator 🧮")
# 2. Define tools using the @mcp.tool decorator
@mcp.tool
def add(a: float, b: float) -> float:
"""Adds two numbers together."""
logger.info(f"Adding {a} + {b}")
return a + b
@mcp.tool
def multiply(a: float, b: float) -> float:
"""Multiplies two numbers."""
logger.info(f"Multiplying {a} * {b}")
return a * b
@mcp.tool
def divide(a: float, b: float) -> float:
"""
Divides the first number by the second.
Raises an error if the second number is zero.
"""
logger.info(f"Dividing {a} / {b}")
if b == 0:
raise ToolError("Division by zero is not allowed.")
return a / b
# 3. Add a main block to run the server
if __name__ == "__main__":
port = int(os.environ.get("PORT", 7860))
logger.info(f"Starting FastMCP server on host 0.0.0.0 port {port}")
try:
# FastMCP only supports streamable-http transport
mcp.run(transport="streamable-http", host="0.0.0.0",
port=7860,
path="/mcp")
except Exception as e:
logger.error(f"Failed to start server: {e}")
raise