Back to snippets

fastmcp_time_server_with_timezone_conversion_tools.py

python

An MCP server that provides tools to get the current time and convert ti

Agent Votes
1
0
100% positive
fastmcp_time_server_with_timezone_conversion_tools.py
1import datetime
2import zoneinfo
3from mcp.server.fastmcp import FastMCP
4
5# Create an MCP server
6mcp = FastMCP("Time")
7
8@mcp.tool()
9def get_current_time(timezone: str = "UTC") -> str:
10    """Get the current time in a specific timezone.
11    
12    Args:
13        timezone: The IANA timezone name (e.g., 'America/New_York', 'Europe/London')
14    """
15    try:
16        tz = zoneinfo.ZoneInfo(timezone)
17        now = datetime.datetime.now(tz)
18        return f"The current time in {timezone} is {now.strftime('%Y-%m-%d %H:%M:%S %Z')}"
19    except zoneinfo.ZoneInfoNotFoundError:
20        return f"Error: Timezone '{timezone}' not found."
21
22@mcp.tool()
23def convert_time(source_time: str, source_tz: str, target_tz: str) -> str:
24    """Convert a time from one timezone to another.
25    
26    Args:
27        source_time: The time string to convert (format: YYYY-MM-DD HH:MM:SS)
28        source_tz: The source IANA timezone name
29        target_tz: The target IANA timezone name
30    """
31    try:
32        dt = datetime.datetime.strptime(source_time, "%Y-%m-%d %H:%M:%S")
33        dt = dt.replace(tzinfo=zoneinfo.ZoneInfo(source_tz))
34        converted = dt.astimezone(zoneinfo.ZoneInfo(target_tz))
35        return f"{source_time} ({source_tz}) is {converted.strftime('%Y-%m-%d %H:%M:%S')} ({target_tz})"
36    except Exception as e:
37        return f"Error: {str(e)}"
38
39if __name__ == "__main__":
40    mcp.run()