Skip to content

Commit 44d3659

Browse files
cliffhallclaude
andcommitted
feat(time): add get_time_ago for past times
A new read-only tool returns the instant a given number of days, hours, minutes and seconds before now, in an optional timezone that defaults to the server's local one. The span is elapsed time, subtracted in UTC, and an offset past year 1 is a tool error. Closes #2710 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
1 parent 446be48 commit 44d3659

5 files changed

Lines changed: 293 additions & 2 deletions

File tree

‎src/time/README.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ Requires MCP Python SDK 2.x (`mcp>=2.3,<3`).
2020
- `time` (string): Time in 24-hour format (HH:MM)
2121
- `target_timezone` (string): Target IANA timezone name
2222

23+
- `get_time_ago` - Get the time a given number of days, hours, minutes and seconds ago in a specific timezone, for questions such as "what happened in the last 5 hours?".
24+
- Optional arguments:
25+
- `timezone` (string): IANA timezone name; defaults to the server's local timezone
26+
- `days_ago`, `hours_ago`, `minutes_ago`, `seconds_ago` (non-negative integers, default 0): how far back to go. They add up, so two and a half hours ago is `hours_ago: 2, minutes_ago: 30`.
27+
- The offset is elapsed time, counted back from the current instant, so across a daylight-saving change "a day ago" is exactly 24 hours ago and its wall-clock reading can differ from now by an hour. An offset reaching before year 1 is an error.
28+
2329
A timezone name, here and in `--local-timezone`, must be an exact IANA key, case included: `Europe/Warsaw` is accepted and `europe/warsaw` is rejected on every platform, including macOS, whose case-insensitive filesystem would otherwise resolve it.
2430

2531
### Protocol versions
@@ -271,6 +277,27 @@ Response (`structuredContent`, and the same JSON as text):
271277
}
272278
```
273279

280+
3. Get a past time:
281+
```json
282+
{
283+
"name": "get_time_ago",
284+
"arguments": {
285+
"timezone": "Europe/Warsaw",
286+
"hours_ago": 2,
287+
"minutes_ago": 30
288+
}
289+
}
290+
```
291+
Response (`structuredContent`, and the same JSON as text):
292+
```json
293+
{
294+
"timezone": "Europe/Warsaw",
295+
"datetime": "2024-01-01T10:30:00+01:00",
296+
"day_of_week": "Monday",
297+
"is_dst": false
298+
}
299+
```
300+
274301
## Debugging
275302

276303
You can use the MCP inspector to debug the server. For uvx installations:
@@ -292,6 +319,7 @@ npx @modelcontextprotocol/inspector uv run mcp-server-time
292319
2. "What time is it in Tokyo?"
293320
3. "When it's 4 PM in New York, what time is it in London?"
294321
4. "Convert 9:30 AM Tokyo time to New York time"
322+
5. "What time was it two and a half hours ago?"
295323

296324
## Development
297325

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

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
class TimeTools(str, Enum):
4141
GET_CURRENT_TIME = "get_current_time"
4242
CONVERT_TIME = "convert_time"
43+
GET_TIME_AGO = "get_time_ago"
4344

4445

4546
class TimeResult(BaseModel):
@@ -115,6 +116,37 @@ def get_current_time(self, timezone_name: str) -> TimeResult:
115116
is_dst=bool(current_time.dst()),
116117
)
117118

119+
def get_time_ago(
120+
self,
121+
timezone_name: str,
122+
days: int = 0,
123+
hours: int = 0,
124+
minutes: int = 0,
125+
seconds: int = 0,
126+
) -> TimeResult:
127+
"""Get the time an elapsed span before now, in specified timezone.
128+
129+
The span is subtracted from the current instant in UTC, not from the
130+
local wall clock, so "5 hours ago" across a clock change is the instant
131+
five real hours back (#2710). An offset that reaches past what
132+
`datetime` can hold is a `ToolError`, not an `OverflowError`.
133+
"""
134+
timezone = get_zoneinfo(timezone_name)
135+
try:
136+
span = timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
137+
past_time = (datetime.now(ZoneInfo("UTC")) - span).astimezone(timezone)
138+
except OverflowError:
139+
raise ToolError(
140+
"Time offset out of range: the result would be before year 1"
141+
)
142+
143+
return TimeResult(
144+
timezone=timezone_name,
145+
datetime=past_time.isoformat(timespec="seconds"),
146+
day_of_week=past_time.strftime("%A"),
147+
is_dst=bool(past_time.dst()),
148+
)
149+
118150
def convert_time(
119151
self, source_tz: str, time_str: str, target_tz: str
120152
) -> TimeConversionResult:
@@ -263,6 +295,37 @@ def convert_time(
263295
require("target_timezone", target_timezone)
264296
return time_server.convert_time(source_timezone, time, target_timezone)
265297

298+
@server.tool(
299+
name=TimeTools.GET_TIME_AGO.value,
300+
description=(
301+
"Get the time a given number of days, hours, minutes and seconds "
302+
"ago in a specific timezone"
303+
),
304+
annotations=READ_ONLY,
305+
)
306+
def get_time_ago(
307+
timezone: Annotated[
308+
str,
309+
Field(
310+
description=f"IANA timezone name (e.g., 'America/New_York', 'Europe/London'). Optional: defaults to the server's local timezone, '{local_tz}', when omitted."
311+
),
312+
] = local_tz,
313+
days_ago: Annotated[int, Field(description="Whole days before now", ge=0)] = 0,
314+
hours_ago: Annotated[
315+
int, Field(description="Whole hours before now", ge=0)
316+
] = 0,
317+
minutes_ago: Annotated[
318+
int, Field(description="Whole minutes before now", ge=0)
319+
] = 0,
320+
seconds_ago: Annotated[
321+
int, Field(description="Whole seconds before now", ge=0)
322+
] = 0,
323+
) -> TimeResult:
324+
require("timezone", timezone)
325+
return time_server.get_time_ago(
326+
timezone, days_ago, hours_ago, minutes_ago, seconds_ago
327+
)
328+
266329
return server
267330

268331

‎src/time/tests/test_entrypoints.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,11 @@ async def test_console_script_boots_over_stdio() -> None:
113113
assert init.model_dump(by_alias=True, mode="json")["serverInfo"]["name"] == (
114114
"mcp-time"
115115
)
116-
assert [tool.name for tool in tools.tools] == ["get_current_time", "convert_time"]
116+
assert [tool.name for tool in tools.tools] == [
117+
"get_current_time",
118+
"convert_time",
119+
"get_time_ago",
120+
]
117121
assert result.model_dump(by_alias=True, mode="json")["isError"] is False
118122

119123

‎src/time/tests/test_eras.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,11 @@ async def test_tools_list_is_the_same_in_both_eras() -> None:
104104
again = tool_wire((await client.list_tools()).tools)
105105
async with connect("legacy") as client:
106106
legacy = tool_wire((await client.list_tools()).tools)
107-
assert [t["name"] for t in modern] == ["get_current_time", "convert_time"]
107+
assert [t["name"] for t in modern] == [
108+
"get_current_time",
109+
"convert_time",
110+
"get_time_ago",
111+
]
108112
assert modern == again == legacy
109113

110114

‎src/time/tests/test_protocol.py‎

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,41 @@ def expected_tools(local_tz: str) -> list[dict[str, Any]]:
261261
},
262262
"annotations": READ_ONLY_ANNOTATIONS,
263263
},
264+
{
265+
"name": "get_time_ago",
266+
"description": (
267+
"Get the time a given number of days, hours, minutes and seconds "
268+
"ago in a specific timezone"
269+
),
270+
"inputSchema": {
271+
"type": "object",
272+
"title": "get_time_agoArguments",
273+
"properties": {
274+
"timezone": {
275+
"type": "string",
276+
"title": "Timezone",
277+
"default": local_tz,
278+
"description": (
279+
"IANA timezone name (e.g., 'America/New_York', "
280+
"'Europe/London'). Optional: defaults to the server's "
281+
f"local timezone, '{local_tz}', when omitted."
282+
),
283+
},
284+
**{
285+
f"{unit}_ago": {
286+
"type": "integer",
287+
"title": f"{unit.capitalize()} Ago",
288+
"default": 0,
289+
"minimum": 0,
290+
"description": f"Whole {unit} before now",
291+
}
292+
for unit in ("days", "hours", "minutes", "seconds")
293+
},
294+
},
295+
},
296+
"outputSchema": TIME_RESULT_SCHEMA,
297+
"annotations": READ_ONLY_ANNOTATIONS,
298+
},
264299
]
265300

266301

@@ -949,6 +984,163 @@ async def test_convert_time_checks_timezones_before_the_time_string() -> None:
949984
)
950985

951986

987+
# ---------------------------------------------------------------------------
988+
# tools/call get_time_ago
989+
# ---------------------------------------------------------------------------
990+
991+
992+
async def test_get_time_ago_wire_result() -> None:
993+
# The issue's own example (#2710): two and a half hours ago.
994+
async with connected() as session:
995+
with frozen_at("2024-01-01 12:00:00+00:00"):
996+
result = await call(
997+
session,
998+
"get_time_ago",
999+
{"timezone": "UTC", "hours_ago": 2, "minutes_ago": 30},
1000+
)
1001+
expected = {
1002+
"timezone": "UTC",
1003+
"datetime": "2024-01-01T09:30:00+00:00",
1004+
"day_of_week": "Monday",
1005+
"is_dst": False,
1006+
}
1007+
assert result == {
1008+
"content": [{"type": "text", "text": json.dumps(expected, indent=2)}],
1009+
"structuredContent": expected,
1010+
"isError": False,
1011+
}
1012+
1013+
1014+
@pytest.mark.parametrize(
1015+
"arguments,expected",
1016+
[
1017+
# No offset at all is now.
1018+
({}, "2024-01-01T12:00:00+00:00"),
1019+
({"seconds_ago": 1}, "2024-01-01T11:59:59+00:00"),
1020+
({"minutes_ago": 90}, "2024-01-01T10:30:00+00:00"),
1021+
# Every unit at once, crossing back into the previous year.
1022+
(
1023+
{"days_ago": 1, "hours_ago": 2, "minutes_ago": 3, "seconds_ago": 4},
1024+
"2023-12-31T09:56:56+00:00",
1025+
),
1026+
# 2023 is not a leap year: 365 days back is the same date.
1027+
({"days_ago": 365}, "2023-01-01T12:00:00+00:00"),
1028+
],
1029+
)
1030+
async def test_get_time_ago_offsets(arguments: dict[str, Any], expected: str) -> None:
1031+
async with connected() as session:
1032+
with frozen_at("2024-01-01 12:00:00+00:00"):
1033+
result = await call_json(
1034+
session, "get_time_ago", {"timezone": "UTC", **arguments}
1035+
)
1036+
assert result["datetime"] == expected
1037+
1038+
1039+
async def test_get_time_ago_defaults_to_the_local_timezone() -> None:
1040+
# An omitted timezone is the server's local timezone, as the schema's
1041+
# `default` says.
1042+
async with connected("Europe/Warsaw") as session:
1043+
with frozen_at("2024-01-01 12:00:00+00:00"):
1044+
result = await call_json(session, "get_time_ago", {"hours_ago": 1})
1045+
assert result == {
1046+
"timezone": "Europe/Warsaw",
1047+
"datetime": "2024-01-01T12:00:00+01:00",
1048+
"day_of_week": "Monday",
1049+
"is_dst": False,
1050+
}
1051+
1052+
1053+
@pytest.mark.parametrize(
1054+
"arguments,expected,is_dst",
1055+
[
1056+
# 03:30 CEST on the spring-forward day is 01:30 UTC; two real hours
1057+
# back is 23:30 UTC, 00:30 CET. Subtracting from the wall clock would
1058+
# wrongly give 01:30.
1059+
({"hours_ago": 2}, "2024-03-31T00:30:00+01:00", False),
1060+
# A day ago is 24 elapsed hours, 01:30 UTC the day before, so across
1061+
# the change the wall clock reads 02:30 CET, not 03:30.
1062+
({"days_ago": 1}, "2024-03-30T02:30:00+01:00", False),
1063+
({"minutes_ago": 30}, "2024-03-31T03:00:00+02:00", True),
1064+
],
1065+
)
1066+
async def test_get_time_ago_counts_elapsed_time_across_a_clock_change(
1067+
arguments: dict[str, Any], expected: str, is_dst: bool
1068+
) -> None:
1069+
async with connected() as session:
1070+
with frozen_at("2024-03-31 01:30:00+00:00"):
1071+
result = await call_json(
1072+
session, "get_time_ago", {"timezone": "Europe/Warsaw", **arguments}
1073+
)
1074+
assert (result["datetime"], result["is_dst"]) == (expected, is_dst)
1075+
1076+
1077+
async def test_get_time_ago_echoes_the_requested_name_not_a_canonical_one() -> None:
1078+
async with connected() as session:
1079+
with frozen_at("2024-01-01 12:00:00+00:00"):
1080+
result = await call_json(
1081+
session, "get_time_ago", {"timezone": "US/Eastern", "days_ago": 1}
1082+
)
1083+
assert result["timezone"] == "US/Eastern"
1084+
assert result["datetime"] == "2023-12-31T07:00:00-05:00"
1085+
assert result["day_of_week"] == "Sunday"
1086+
1087+
1088+
@pytest.mark.parametrize(
1089+
"arguments,needles",
1090+
[
1091+
# Rejected by MCPServer against the tool's signature, before it runs.
1092+
(
1093+
{"hours_ago": -1},
1094+
["hours_ago\n Input should be greater than or equal to 0"],
1095+
),
1096+
(
1097+
{"days_ago": 1.5},
1098+
["days_ago\n Input should be a valid integer, got a number with a"],
1099+
),
1100+
({"minutes_ago": "ten"}, ["minutes_ago\n Input should be a valid integer"]),
1101+
({"seconds_ago": None}, ["seconds_ago\n Input should be a valid integer"]),
1102+
({"timezone": None}, ["timezone\n Input should be a valid string"]),
1103+
],
1104+
)
1105+
async def test_get_time_ago_argument_validation(
1106+
arguments: dict[str, Any], needles: list[str]
1107+
) -> None:
1108+
async with connected() as session:
1109+
result = await call(session, "get_time_ago", arguments)
1110+
assert_validation_error(result, "get_time_ago", *needles)
1111+
1112+
1113+
@pytest.mark.parametrize(
1114+
"arguments,message",
1115+
[
1116+
# Raised by the tool as a ToolError.
1117+
({"timezone": ""}, "Missing required argument: timezone"),
1118+
(
1119+
{"timezone": "europe/warsaw"},
1120+
"Invalid timezone: 'No time zone found with key europe/warsaw'",
1121+
),
1122+
# Past what timedelta can hold, and past year 1.
1123+
(
1124+
{"days_ago": 10**10},
1125+
"Time offset out of range: the result would be before year 1",
1126+
),
1127+
(
1128+
{"days_ago": 999_999_999},
1129+
"Time offset out of range: the result would be before year 1",
1130+
),
1131+
# The timezone is checked before the offset.
1132+
(
1133+
{"timezone": "Bad/Zone", "days_ago": 10**10},
1134+
"Invalid timezone: 'No time zone found with key Bad/Zone'",
1135+
),
1136+
],
1137+
)
1138+
async def test_get_time_ago_errors(arguments: dict[str, Any], message: str) -> None:
1139+
async with connected() as session:
1140+
result = await call(session, "get_time_ago", arguments)
1141+
assert result == tool_error("get_time_ago", message)
1142+
1143+
9521144
# ---------------------------------------------------------------------------
9531145
# Unknown tools
9541146
# ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)