|
9 | 9 | # loop only; serving 2026-07-28 is #4853. |
10 | 10 |
|
11 | 11 | from datetime import datetime, timedelta |
| 12 | +from functools import cache |
12 | 13 | from importlib.metadata import version |
13 | 14 | from enum import Enum |
14 | 15 | import json |
15 | 16 | import sys |
16 | 17 | from typing import Any |
17 | 18 |
|
18 | | -from zoneinfo import ZoneInfo, ZoneInfoNotFoundError |
| 19 | +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError, available_timezones |
19 | 20 | from tzlocal import get_localzone_name # ← returns "Europe/Paris", etc. |
20 | 21 |
|
21 | 22 | import jsonschema |
@@ -79,9 +80,30 @@ def get_local_tz(local_tz_override: str | None = None) -> ZoneInfo: |
79 | 80 | return ZoneInfo("UTC") |
80 | 81 |
|
81 | 82 |
|
| 83 | +@cache |
| 84 | +def known_timezones() -> frozenset[str]: |
| 85 | + """The exact IANA keys this host's tz database holds, read once.""" |
| 86 | + return frozenset(available_timezones()) |
| 87 | + |
| 88 | + |
| 89 | +def load_zoneinfo(timezone_name: str) -> ZoneInfo: |
| 90 | + """`ZoneInfo(timezone_name)`, accepting only an exact IANA key. |
| 91 | +
|
| 92 | + zoneinfo looks a key up as a file path, so on a case-insensitive |
| 93 | + filesystem (macOS's APFS) `europe/warsaw` resolves to `Europe/Warsaw` |
| 94 | + while Linux rejects it (#5060). Checking the key against the database's |
| 95 | + own list makes every platform reject it. `ZoneInfo` runs first so a path |
| 96 | + or a directory keeps the error zoneinfo gives it. |
| 97 | + """ |
| 98 | + zone = ZoneInfo(timezone_name) |
| 99 | + if timezone_name not in known_timezones(): |
| 100 | + raise ZoneInfoNotFoundError(f"No time zone found with key {timezone_name}") |
| 101 | + return zone |
| 102 | + |
| 103 | + |
82 | 104 | def get_zoneinfo(timezone_name: str) -> ZoneInfo: |
83 | 105 | try: |
84 | | - return ZoneInfo(timezone_name) |
| 106 | + return load_zoneinfo(timezone_name) |
85 | 107 | except Exception as e: |
86 | 108 | raise MCPError(code=INVALID_PARAMS, message=f"Invalid timezone: {str(e)}") |
87 | 109 |
|
@@ -173,7 +195,7 @@ async def serve(local_timezone: str | None = None) -> None: |
173 | 195 | # bad key (unknown name, a tzdata directory, a path, a null byte), and |
174 | 196 | # its messages can carry a filesystem path, so none of them is shown. |
175 | 197 | try: |
176 | | - ZoneInfo(local_timezone) |
| 198 | + load_zoneinfo(local_timezone) |
177 | 199 | except (ZoneInfoNotFoundError, ValueError, OSError): |
178 | 200 | sys.exit( |
179 | 201 | f"Error: invalid --local-timezone {local_timezone!r}: " |
|
0 commit comments