Skip to content

Commit 8d6ea2f

Browse files
authored
Merge pull request #5366 from modelcontextprotocol/v2/fix/5196-time-ambiguous-fall-back
fix(time): report the second occurrence of an ambiguous fall-back time in convert_time
2 parents 91f1ab7 + e05bef2 commit 8d6ea2f

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
@@ -32,6 +32,7 @@ The server speaks both eras of the Model Context Protocol over stdio, with nothi
3232
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.
3333

3434
- **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).
35+
- **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`.
3536
- **An unknown tool name is a JSON-RPC `-32602` error** (`Unknown tool: <name>`), not an `isError` result, as both protocol versions specify.
3637
- The server registers no prompts or resources. Their list methods answer with empty lists.
3738

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

‎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
@@ -257,9 +257,41 @@ def expected_tools(local_tz: str) -> list[dict[str, Any]]:
257257
"source": {"$ref": "#/$defs/TimeResult"},
258258
"target": {"$ref": "#/$defs/TimeResult"},
259259
"time_difference": {"title": "Time Difference", "type": "string"},
260+
"later_occurrence": {
261+
"anyOf": [
262+
{"$ref": "#/$defs/LaterOccurrence"},
263+
{"type": "null"},
264+
],
265+
"default": None,
266+
"description": (
267+
"Set only when the source time occurs twice on this "
268+
"date because a clock change repeats it (a DST "
269+
"fall-back): the same conversion at its second "
270+
"occurrence. source and target are the first."
271+
),
272+
},
260273
},
261274
"required": ["source", "target", "time_difference"],
262-
"$defs": {"TimeResult": TIME_RESULT_SCHEMA},
275+
"$defs": {
276+
"LaterOccurrence": {
277+
"type": "object",
278+
"title": "LaterOccurrence",
279+
"description": (
280+
"The second reading of an ambiguous source time (#5196)."
281+
),
282+
"properties": {
283+
"note": {"title": "Note", "type": "string"},
284+
"source": {"$ref": "#/$defs/TimeResult"},
285+
"target": {"$ref": "#/$defs/TimeResult"},
286+
"time_difference": {
287+
"title": "Time Difference",
288+
"type": "string",
289+
},
290+
},
291+
"required": ["note", "source", "target", "time_difference"],
292+
},
293+
"TimeResult": TIME_RESULT_SCHEMA,
294+
},
263295
},
264296
"annotations": READ_ONLY_ANNOTATIONS,
265297
},
@@ -660,6 +692,8 @@ async def test_convert_time_wire_result() -> None:
660692
"is_dst": False,
661693
},
662694
"time_difference": "+8.0h",
695+
# Only an ambiguous source time sets it (#5196).
696+
"later_occurrence": None,
663697
}
664698
assert result == {
665699
"content": [{"type": "text", "text": json.dumps(expected, indent=2)}],
@@ -856,8 +890,10 @@ async def test_convert_time_into_a_nonexistent_local_time() -> None:
856890

857891

858892
async def test_convert_time_at_an_ambiguous_local_time() -> None:
859-
# 01:30 on 2024-11-03 happens twice in New York. fold=0 picks the first
860-
# occurrence, still on EDT.
893+
# 01:30 on 2024-11-03 happens twice in New York: first on EDT, then, after
894+
# the clocks go back at 02:00, on EST. source and target are the first
895+
# occurrence; later_occurrence carries the second, with a note saying the
896+
# time is ambiguous rather than presenting one answer as certain (#5196).
861897
async with connected() as session:
862898
with frozen_at("2024-11-03 12:00:00+00:00"):
863899
result = await call_json(
@@ -877,6 +913,122 @@ async def test_convert_time_at_an_ambiguous_local_time() -> None:
877913
}
878914
assert result["target"]["datetime"] == "2024-11-03T05:30:00+00:00"
879915
assert result["time_difference"] == "+4.0h"
916+
assert result["later_occurrence"] == {
917+
"note": (
918+
"01:30 occurs twice in America/New_York on 2024-11-03 because a "
919+
"clock change repeats it: first at 2024-11-03T01:30:00-04:00, then "
920+
"at 2024-11-03T01:30:00-05:00. source and target are the first "
921+
"occurrence; this is the second."
922+
),
923+
"source": {
924+
"timezone": "America/New_York",
925+
"datetime": "2024-11-03T01:30:00-05:00",
926+
"day_of_week": "Sunday",
927+
"is_dst": False,
928+
},
929+
"target": {
930+
"timezone": "UTC",
931+
"datetime": "2024-11-03T06:30:00+00:00",
932+
"day_of_week": "Sunday",
933+
"is_dst": False,
934+
},
935+
"time_difference": "+5.0h",
936+
}
937+
938+
939+
async def test_convert_time_ambiguity_is_in_the_structured_result() -> None:
940+
# The structured content carries the same later_occurrence as the text.
941+
async with connected() as session:
942+
with frozen_at("2024-10-27 12:00:00+00:00"):
943+
result = await call(
944+
session,
945+
"convert_time",
946+
{
947+
"source_timezone": "Europe/Warsaw",
948+
"time": "02:30",
949+
"target_timezone": "UTC",
950+
},
951+
)
952+
structured = result["structuredContent"]
953+
assert structured == json.loads(result["content"][0]["text"])
954+
assert structured["source"]["datetime"] == "2024-10-27T02:30:00+02:00"
955+
assert structured["target"]["datetime"] == "2024-10-27T00:30:00+00:00"
956+
later = structured["later_occurrence"]
957+
assert later["source"]["datetime"] == "2024-10-27T02:30:00+01:00"
958+
assert later["target"]["datetime"] == "2024-10-27T01:30:00+00:00"
959+
assert later["time_difference"] == "-1.0h"
960+
961+
962+
@pytest.mark.parametrize(
963+
"instant,source,time,target,later_target,later_difference",
964+
[
965+
# Lord Howe Island moves its clocks back by only 30 minutes (02:00 ->
966+
# 01:30), so 01:45 repeats with a fractional difference.
967+
(
968+
"2024-04-07 00:00:00+00:00",
969+
"Australia/Lord_Howe",
970+
"01:45",
971+
"UTC",
972+
"2024-04-06T15:15:00+00:00",
973+
"-10.5h",
974+
),
975+
# The target's own zone does not matter: only the source is ambiguous.
976+
(
977+
"2024-11-03 12:00:00+00:00",
978+
"America/New_York",
979+
"01:00",
980+
"Asia/Kolkata",
981+
"2024-11-03T11:30:00+05:30",
982+
"+10.5h",
983+
),
984+
],
985+
)
986+
async def test_convert_time_later_occurrence_in_other_zones(
987+
instant: str,
988+
source: str,
989+
time: str,
990+
target: str,
991+
later_target: str,
992+
later_difference: str,
993+
) -> None:
994+
async with connected() as session:
995+
with frozen_at(instant):
996+
result = await call_json(
997+
session,
998+
"convert_time",
999+
{"source_timezone": source, "time": time, "target_timezone": target},
1000+
)
1001+
later = result["later_occurrence"]
1002+
assert later["note"].startswith(f"{time} occurs twice in {source} on ")
1003+
assert later["source"]["timezone"] == source
1004+
assert later["target"]["datetime"] == later_target
1005+
assert later["time_difference"] == later_difference
1006+
1007+
1008+
@pytest.mark.parametrize(
1009+
"instant,source,time",
1010+
[
1011+
# The hour after the repeated one, on the fall-back day itself.
1012+
("2024-11-03 12:00:00+00:00", "America/New_York", "02:00"),
1013+
# The hour before it, also on the fall-back day.
1014+
("2024-11-03 12:00:00+00:00", "America/New_York", "00:59"),
1015+
# The same wall time on an ordinary day.
1016+
("2024-11-10 12:00:00+00:00", "America/New_York", "01:30"),
1017+
# The same date in a zone with no clock change.
1018+
("2024-11-03 12:00:00+00:00", "UTC", "01:30"),
1019+
],
1020+
)
1021+
async def test_convert_time_unambiguous_time_has_no_later_occurrence(
1022+
instant: str, source: str, time: str
1023+
) -> None:
1024+
async with connected() as session:
1025+
with frozen_at(instant):
1026+
result = await call_json(
1027+
session,
1028+
"convert_time",
1029+
{"source_timezone": source, "time": time, "target_timezone": "UTC"},
1030+
)
1031+
assert result["later_occurrence"] is None
8801032

8811033

8821034
async def test_convert_time_difference_uses_offsets_at_the_converted_instant() -> None:

0 commit comments

Comments
 (0)