Skip to content

Commit 2189a3d

Browse files
cliffhallclaude
andcommitted
fix(time): exit with one line on an invalid --local-timezone (modelcontextprotocol#5001)
An unknown --local-timezone made serve() raise out of ZoneInfo before the stdio transport opened, so the process died with a traceback. serve() now checks the override first and exits through sys.exit with one line naming the value ("Error: invalid --local-timezone 'X': not a known IANA timezone name"), status 1. zoneinfo's own message is not shown, since for some keys it carries the installed tzdata path. The KNOWN BUG modelcontextprotocol#5001 pinning test now asserts the clean exit for three kinds of bad key, and a subprocess test checks the console script's stderr and exit status end to end. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 571e2b3 commit 2189a3d

3 files changed

Lines changed: 55 additions & 8 deletions

File tree

‎src/time/src/mcp_server_time/server.py‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
from datetime import datetime, timedelta
22
from enum import Enum
33
import json
4+
import sys
45
from typing import Sequence
56

6-
from zoneinfo import ZoneInfo
7+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
78
from tzlocal import get_localzone_name # ← returns "Europe/Paris", etc.
89

910
from mcp.server import Server
@@ -133,6 +134,18 @@ def convert_time(
133134
async def serve(local_timezone: str | None = None) -> None:
134135
server = Server("mcp-time")
135136
time_server = TimeServer()
137+
if local_timezone:
138+
# Fail before the transport opens, with one line naming the bad value
139+
# rather than a traceback. zoneinfo raises a different type per kind of
140+
# bad key (unknown name, a tzdata directory, a path, a null byte), and
141+
# its messages can carry a filesystem path, so none of them is shown.
142+
try:
143+
ZoneInfo(local_timezone)
144+
except (ZoneInfoNotFoundError, ValueError, OSError):
145+
sys.exit(
146+
f"Error: invalid --local-timezone {local_timezone!r}: "
147+
"not a known IANA timezone name"
148+
)
136149
local_tz = str(get_local_tz(local_timezone))
137150

138151
@server.list_tools()

‎src/time/tests/test_entrypoints.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import os
1111
import runpy
1212
import shutil
13+
import subprocess
1314
import sys
1415
from pathlib import Path
1516
from unittest.mock import AsyncMock, MagicMock, patch
@@ -114,3 +115,22 @@ async def test_console_script_boots_over_stdio() -> None:
114115
)
115116
assert [tool.name for tool in tools.tools] == ["get_current_time", "convert_time"]
116117
assert result.model_dump(by_alias=True, mode="json")["isError"] is False
118+
119+
120+
def test_console_script_rejects_an_invalid_local_timezone() -> None:
121+
# #5001: one line on stderr naming the value, a non-zero exit, and no
122+
# traceback.
123+
script = shutil.which("mcp-server-time", path=str(Path(sys.executable).parent))
124+
assert script is not None, "the console script is not installed in this venv"
125+
proc = subprocess.run(
126+
[script, "--local-timezone", "Not/AZone"],
127+
stdin=subprocess.DEVNULL,
128+
capture_output=True,
129+
text=True,
130+
timeout=60,
131+
)
132+
assert proc.returncode == 1
133+
assert proc.stdout == ""
134+
assert proc.stderr.splitlines() == [
135+
"Error: invalid --local-timezone 'Not/AZone': not a known IANA timezone name"
136+
]

‎src/time/tests/test_protocol.py‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434
from mcp import ClientSession
3535
from mcp.shared.memory import create_client_server_memory_streams
3636
from pydantic import BaseModel
37-
from zoneinfo import ZoneInfoNotFoundError
3837

3938
from mcp_server_time.server import serve
4039

@@ -235,16 +234,31 @@ async def test_empty_local_timezone_override_is_treated_as_absent() -> None:
235234
assert result == {"tools": expected_tools("Africa/Cairo")}
236235

237236

238-
# KNOWN BUG #5001: an invalid --local-timezone crashes serve() with a traceback instead of a clean error; the fix changes this assertion.
239-
async def test_invalid_local_timezone_fails_before_the_transport_opens() -> None:
240-
# An unknown `--local-timezone` raises out of `serve()` itself, before
241-
# stdio is opened: the process dies with a traceback instead of starting.
237+
@pytest.mark.parametrize(
238+
"local_timezone",
239+
[
240+
"Not/AZone", # unknown name: ZoneInfoNotFoundError
241+
"America", # a tzdata directory, not a zone: OSError
242+
"../etc/passwd", # outside TZPATH: ValueError
243+
],
244+
)
245+
async def test_invalid_local_timezone_fails_before_the_transport_opens(
246+
local_timezone: str,
247+
) -> None:
248+
# An invalid `--local-timezone` stops `serve()` before stdio is opened,
249+
# with a one-line message naming the value and a non-zero exit, rather
250+
# than a traceback (#5001). A `SystemExit` whose code is a string prints
251+
# that string to stderr and exits 1.
242252
def unexpected_stdio_server():
243253
raise AssertionError("stdio_server must not be reached")
244254

245255
with patch("mcp_server_time.server.stdio_server", unexpected_stdio_server):
246-
with pytest.raises(ZoneInfoNotFoundError, match="Not/AZone"):
247-
await serve("Not/AZone")
256+
with pytest.raises(SystemExit) as exit_info:
257+
await serve(local_timezone)
258+
assert exit_info.value.code == (
259+
f"Error: invalid --local-timezone {local_timezone!r}: "
260+
"not a known IANA timezone name"
261+
)
248262

249263

250264
# ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)