Skip to content

Commit e05bef2

Browse files
cliffhallclaude
andcommitted
fix(time): report the second occurrence of an ambiguous fall-back time
convert_time attached the source zone to today's date and the given HH:MM, which always resolves to fold=0: on a DST fall-back day a repeated wall time (01:30 in America/New_York on 2024-11-03) has two instants, and the tool silently answered with the first. TimeConversionResult gains an optional later_occurrence (a LaterOccurrence: a note, and the source, target and time_difference at the second instant), set only when the source time's fold=1 reading has a different UTC offset. source and target keep the first occurrence, so an unambiguous conversion is unchanged apart from later_occurrence: null. Closes modelcontextprotocol#5196 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 446be48 commit e05bef2

3 files changed

Lines changed: 232 additions & 26 deletions

File tree

‎src/time/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ The server speaks both eras of the Model Context Protocol over stdio, with nothi
3131
The server is built on the SDK's high-level `MCPServer`. Each tool declares an `outputSchema` and returns its result twice: as `structuredContent`, and as the same object in indented JSON in a text block, for a client that does not read structured output.
3232

3333
- **A tool failure is an `isError` result** whose text the model can read and act on, prefixed `Error executing tool <name>: `. That covers an unknown or non-exact timezone (`Invalid timezone: ...`), an empty timezone (`Missing required argument: <argument>`), a time not in `HH:MM` 24-hour form, a wall-clock time skipped by a clock change, and an argument missing or of the wrong type (the SDK's validation message).
34+
- **An ambiguous time is reported, not guessed.** On the day a clock change repeats a wall-clock time (a DST fall-back, such as 01:30 on 2024-11-03 in `America/New_York`), `convert_time` returns its first occurrence in `source` and `target`, and the second in `later_occurrence`: a `note` saying the time occurs twice, with that occurrence's own `source`, `target` and `time_difference`. For any other time `later_occurrence` is `null`.
3435
- **An unknown tool name is a JSON-RPC `-32602` error** (`Unknown tool: <name>`), not an `isError` result, as both protocol versions specify.
3536
- The server registers no prompts or resources. Their list methods answer with empty lists.
3637

@@ -267,7 +268,8 @@ Response (`structuredContent`, and the same JSON as text):
267268
"day_of_week": "Tuesday",
268269
"is_dst": false
269270
},
270-
"time_difference": "+14.0h"
271+
"time_difference": "+14.0h",
272+
"later_occurrence": null
271273
}
272274
```
273275

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

Lines changed: 74 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,26 @@ class TimeConversionResult(BaseModel):
5353
source: TimeResult
5454
target: TimeResult
5555
time_difference: str
56+
later_occurrence: "LaterOccurrence | None" = Field(
57+
default=None,
58+
description=(
59+
"Set only when the source time occurs twice on this date because "
60+
"a clock change repeats it (a DST fall-back): the same conversion "
61+
"at its second occurrence. source and target are the first."
62+
),
63+
)
64+
65+
66+
class LaterOccurrence(BaseModel):
67+
"""The second reading of an ambiguous source time (#5196)."""
68+
69+
note: str
70+
source: TimeResult
71+
target: TimeResult
72+
time_difference: str
73+
74+
75+
TimeConversionResult.model_rebuild()
5676

5777

5878
class TimeConversionInput(BaseModel):
@@ -146,31 +166,63 @@ def convert_time(
146166
f"{source_time.date().isoformat()} (skipped by a clock change)"
147167
)
148168

149-
target_time = source_time.astimezone(target_timezone)
150-
source_offset = source_time.utcoffset() or timedelta()
151-
target_offset = target_time.utcoffset() or timedelta()
152-
hours_difference = (target_offset - source_offset).total_seconds() / 3600
169+
def convert(at: datetime) -> tuple[TimeResult, TimeResult, str]:
170+
"""`at` as a source and target `TimeResult`, and their difference."""
171+
target_time = at.astimezone(target_timezone)
172+
source_offset = at.utcoffset() or timedelta()
173+
target_offset = target_time.utcoffset() or timedelta()
174+
hours_difference = (target_offset - source_offset).total_seconds() / 3600
175+
176+
if hours_difference.is_integer():
177+
time_diff_str = f"{hours_difference:+.1f}h"
178+
else:
179+
# For fractional hours like Nepal's UTC+5:45
180+
time_diff_str = f"{hours_difference:+.2f}".rstrip("0").rstrip(".") + "h"
181+
182+
return (
183+
TimeResult(
184+
timezone=source_tz,
185+
datetime=at.isoformat(timespec="seconds"),
186+
day_of_week=at.strftime("%A"),
187+
is_dst=bool(at.dst()),
188+
),
189+
TimeResult(
190+
timezone=target_tz,
191+
datetime=target_time.isoformat(timespec="seconds"),
192+
day_of_week=target_time.strftime("%A"),
193+
is_dst=bool(target_time.dst()),
194+
),
195+
time_diff_str,
196+
)
153197

154-
if hours_difference.is_integer():
155-
time_diff_str = f"{hours_difference:+.1f}h"
156-
else:
157-
# For fractional hours like Nepal's UTC+5:45
158-
time_diff_str = f"{hours_difference:+.2f}".rstrip("0").rstrip(".") + "h"
198+
source, target, time_difference = convert(source_time)
199+
200+
# A wall-clock time a clock change repeats (e.g. 01:30 on a DST
201+
# fall-back day) has two instants. The datetime above is the first
202+
# (fold=0); fold=1 is the second, at a different UTC offset. Report
203+
# both rather than presenting the first as the only answer (#5196).
204+
later_occurrence = None
205+
later_time = source_time.replace(fold=1)
206+
if later_time.utcoffset() != source_time.utcoffset():
207+
later_source, later_target, later_difference = convert(later_time)
208+
later_occurrence = LaterOccurrence(
209+
note=(
210+
f"{time_str} occurs twice in {source_tz} on "
211+
f"{source_time.date().isoformat()} because a clock change "
212+
f"repeats it: first at {source.datetime}, then at "
213+
f"{later_source.datetime}. source and target are the first "
214+
"occurrence; this is the second."
215+
),
216+
source=later_source,
217+
target=later_target,
218+
time_difference=later_difference,
219+
)
159220

160221
return TimeConversionResult(
161-
source=TimeResult(
162-
timezone=source_tz,
163-
datetime=source_time.isoformat(timespec="seconds"),
164-
day_of_week=source_time.strftime("%A"),
165-
is_dst=bool(source_time.dst()),
166-
),
167-
target=TimeResult(
168-
timezone=target_tz,
169-
datetime=target_time.isoformat(timespec="seconds"),
170-
day_of_week=target_time.strftime("%A"),
171-
is_dst=bool(target_time.dst()),
172-
),
173-
time_difference=time_diff_str,
222+
source=source,
223+
target=target,
224+
time_difference=time_difference,
225+
later_occurrence=later_occurrence,
174226
)
175227

176228

‎src/time/tests/test_protocol.py‎

Lines changed: 155 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -255,9 +255,41 @@ def expected_tools(local_tz: str) -> list[dict[str, Any]]:
255255
"source": {"$ref": "#/$defs/TimeResult"},
256256
"target": {"$ref": "#/$defs/TimeResult"},
257257
"time_difference": {"title": "Time Difference", "type": "string"},
258+
"later_occurrence": {
259+
"anyOf": [
260+
{"$ref": "#/$defs/LaterOccurrence"},
261+
{"type": "null"},
262+
],
263+
"default": None,
264+
"description": (
265+
"Set only when the source time occurs twice on this "
266+
"date because a clock change repeats it (a DST "
267+
"fall-back): the same conversion at its second "
268+
"occurrence. source and target are the first."
269+
),
270+
},
258271
},
259272
"required": ["source", "target", "time_difference"],
260-
"$defs": {"TimeResult": TIME_RESULT_SCHEMA},
273+
"$defs": {
274+
"LaterOccurrence": {
275+
"type": "object",
276+
"title": "LaterOccurrence",
277+
"description": (
278+
"The second reading of an ambiguous source time (#5196)."
279+
),
280+
"properties": {
281+
"note": {"title": "Note", "type": "string"},
282+
"source": {"$ref": "#/$defs/TimeResult"},
283+
"target": {"$ref": "#/$defs/TimeResult"},
284+
"time_difference": {
285+
"title": "Time Difference",
286+
"type": "string",
287+
},
288+
},
289+
"required": ["note", "source", "target", "time_difference"],
290+
},
291+
"TimeResult": TIME_RESULT_SCHEMA,
292+
},
261293
},
262294
"annotations": READ_ONLY_ANNOTATIONS,
263295
},
@@ -599,6 +631,8 @@ async def test_convert_time_wire_result() -> None:
599631
"is_dst": False,
600632
},
601633
"time_difference": "+8.0h",
634+
# Only an ambiguous source time sets it (#5196).
635+
"later_occurrence": None,
602636
}
603637
assert result == {
604638
"content": [{"type": "text", "text": json.dumps(expected, indent=2)}],
@@ -795,8 +829,10 @@ async def test_convert_time_into_a_nonexistent_local_time() -> None:
795829

796830

797831
async def test_convert_time_at_an_ambiguous_local_time() -> None:
798-
# 01:30 on 2024-11-03 happens twice in New York. fold=0 picks the first
799-
# occurrence, still on EDT.
832+
# 01:30 on 2024-11-03 happens twice in New York: first on EDT, then, after
833+
# the clocks go back at 02:00, on EST. source and target are the first
834+
# occurrence; later_occurrence carries the second, with a note saying the
835+
# time is ambiguous rather than presenting one answer as certain (#5196).
800836
async with connected() as session:
801837
with frozen_at("2024-11-03 12:00:00+00:00"):
802838
result = await call_json(
@@ -816,6 +852,122 @@ async def test_convert_time_at_an_ambiguous_local_time() -> None:
816852
}
817853
assert result["target"]["datetime"] == "2024-11-03T05:30:00+00:00"
818854
assert result["time_difference"] == "+4.0h"
855+
assert result["later_occurrence"] == {
856+
"note": (
857+
"01:30 occurs twice in America/New_York on 2024-11-03 because a "
858+
"clock change repeats it: first at 2024-11-03T01:30:00-04:00, then "
859+
"at 2024-11-03T01:30:00-05:00. source and target are the first "
860+
"occurrence; this is the second."
861+
),
862+
"source": {
863+
"timezone": "America/New_York",
864+
"datetime": "2024-11-03T01:30:00-05:00",
865+
"day_of_week": "Sunday",
866+
"is_dst": False,
867+
},
868+
"target": {
869+
"timezone": "UTC",
870+
"datetime": "2024-11-03T06:30:00+00:00",
871+
"day_of_week": "Sunday",
872+
"is_dst": False,
873+
},
874+
"time_difference": "+5.0h",
875+
}
876+
877+
878+
async def test_convert_time_ambiguity_is_in_the_structured_result() -> None:
879+
# The structured content carries the same later_occurrence as the text.
880+
async with connected() as session:
881+
with frozen_at("2024-10-27 12:00:00+00:00"):
882+
result = await call(
883+
session,
884+
"convert_time",
885+
{
886+
"source_timezone": "Europe/Warsaw",
887+
"time": "02:30",
888+
"target_timezone": "UTC",
889+
},
890+
)
891+
structured = result["structuredContent"]
892+
assert structured == json.loads(result["content"][0]["text"])
893+
assert structured["source"]["datetime"] == "2024-10-27T02:30:00+02:00"
894+
assert structured["target"]["datetime"] == "2024-10-27T00:30:00+00:00"
895+
later = structured["later_occurrence"]
896+
assert later["source"]["datetime"] == "2024-10-27T02:30:00+01:00"
897+
assert later["target"]["datetime"] == "2024-10-27T01:30:00+00:00"
898+
assert later["time_difference"] == "-1.0h"
899+
900+
901+
@pytest.mark.parametrize(
902+
"instant,source,time,target,later_target,later_difference",
903+
[
904+
# Lord Howe Island moves its clocks back by only 30 minutes (02:00 ->
905+
# 01:30), so 01:45 repeats with a fractional difference.
906+
(
907+
"2024-04-07 00:00:00+00:00",
908+
"Australia/Lord_Howe",
909+
"01:45",
910+
"UTC",
911+
"2024-04-06T15:15:00+00:00",
912+
"-10.5h",
913+
),
914+
# The target's own zone does not matter: only the source is ambiguous.
915+
(
916+
"2024-11-03 12:00:00+00:00",
917+
"America/New_York",
918+
"01:00",
919+
"Asia/Kolkata",
920+
"2024-11-03T11:30:00+05:30",
921+
"+10.5h",
922+
),
923+
],
924+
)
925+
async def test_convert_time_later_occurrence_in_other_zones(
926+
instant: str,
927+
source: str,
928+
time: str,
929+
target: str,
930+
later_target: str,
931+
later_difference: str,
932+
) -> None:
933+
async with connected() as session:
934+
with frozen_at(instant):
935+
result = await call_json(
936+
session,
937+
"convert_time",
938+
{"source_timezone": source, "time": time, "target_timezone": target},
939+
)
940+
later = result["later_occurrence"]
941+
assert later["note"].startswith(f"{time} occurs twice in {source} on ")
942+
assert later["source"]["timezone"] == source
943+
assert later["target"]["datetime"] == later_target
944+
assert later["time_difference"] == later_difference
945+
946+
947+
@pytest.mark.parametrize(
948+
"instant,source,time",
949+
[
950+
# The hour after the repeated one, on the fall-back day itself.
951+
("2024-11-03 12:00:00+00:00", "America/New_York", "02:00"),
952+
# The hour before it, also on the fall-back day.
953+
("2024-11-03 12:00:00+00:00", "America/New_York", "00:59"),
954+
# The same wall time on an ordinary day.
955+
("2024-11-10 12:00:00+00:00", "America/New_York", "01:30"),
956+
# The same date in a zone with no clock change.
957+
("2024-11-03 12:00:00+00:00", "UTC", "01:30"),
958+
],
959+
)
960+
async def test_convert_time_unambiguous_time_has_no_later_occurrence(
961+
instant: str, source: str, time: str
962+
) -> None:
963+
async with connected() as session:
964+
with frozen_at(instant):
965+
result = await call_json(
966+
session,
967+
"convert_time",
968+
{"source_timezone": source, "time": time, "target_timezone": "UTC"},
969+
)
970+
assert result["later_occurrence"] is None
819971

820972

821973
async def test_convert_time_difference_uses_offsets_at_the_converted_instant() -> None:

0 commit comments

Comments
 (0)