|
1 | 1 | from datetime import datetime, timedelta |
| 2 | +from functools import cache |
2 | 3 | from importlib.metadata import version |
3 | 4 | from enum import Enum |
4 | 5 | import json |
5 | 6 | import sys |
6 | 7 | from typing import Sequence |
7 | 8 |
|
8 | | -from zoneinfo import ZoneInfo, ZoneInfoNotFoundError |
| 9 | +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError, available_timezones |
9 | 10 | from tzlocal import get_localzone_name # ← returns "Europe/Paris", etc. |
10 | 11 |
|
11 | 12 | from mcp.server import Server |
@@ -65,9 +66,30 @@ def get_local_tz(local_tz_override: str | None = None) -> ZoneInfo: |
65 | 66 | return ZoneInfo("UTC") |
66 | 67 |
|
67 | 68 |
|
| 69 | +@cache |
| 70 | +def known_timezones() -> frozenset[str]: |
| 71 | + """The exact IANA keys this host's tz database holds, read once.""" |
| 72 | + return frozenset(available_timezones()) |
| 73 | + |
| 74 | + |
| 75 | +def load_zoneinfo(timezone_name: str) -> ZoneInfo: |
| 76 | + """`ZoneInfo(timezone_name)`, accepting only an exact IANA key. |
| 77 | +
|
| 78 | + zoneinfo looks a key up as a file path, so on a case-insensitive |
| 79 | + filesystem (macOS's APFS) `europe/warsaw` resolves to `Europe/Warsaw` |
| 80 | + while Linux rejects it (#5060). Checking the key against the database's |
| 81 | + own list makes every platform reject it. `ZoneInfo` runs first so a path |
| 82 | + or a directory keeps the error zoneinfo gives it. |
| 83 | + """ |
| 84 | + zone = ZoneInfo(timezone_name) |
| 85 | + if timezone_name not in known_timezones(): |
| 86 | + raise ZoneInfoNotFoundError(f"No time zone found with key {timezone_name}") |
| 87 | + return zone |
| 88 | + |
| 89 | + |
68 | 90 | def get_zoneinfo(timezone_name: str) -> ZoneInfo: |
69 | 91 | try: |
70 | | - return ZoneInfo(timezone_name) |
| 92 | + return load_zoneinfo(timezone_name) |
71 | 93 | except Exception as e: |
72 | 94 | raise McpError( |
73 | 95 | ErrorData(code=INVALID_PARAMS, message=f"Invalid timezone: {str(e)}") |
@@ -155,7 +177,7 @@ async def serve(local_timezone: str | None = None) -> None: |
155 | 177 | # bad key (unknown name, a tzdata directory, a path, a null byte), and |
156 | 178 | # its messages can carry a filesystem path, so none of them is shown. |
157 | 179 | try: |
158 | | - ZoneInfo(local_timezone) |
| 180 | + load_zoneinfo(local_timezone) |
159 | 181 | except (ZoneInfoNotFoundError, ValueError, OSError): |
160 | 182 | sys.exit( |
161 | 183 | f"Error: invalid --local-timezone {local_timezone!r}: " |
|
0 commit comments