Skip to content

Commit 718e8d1

Browse files
authored
Merge pull request #5369 from modelcontextprotocol/v2/feat/2710-time-get-time-ago
feat(time): add get_time_ago for past times
2 parents 8d6ea2f + cb01940 commit 718e8d1

5 files changed

Lines changed: 296 additions & 2 deletions

File tree

‎src/time/README.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ Requires MCP Python SDK 2.x (`mcp>=2.3,<3`).
2121
- `source_timezone` (string): Source IANA timezone name. Defaults to the server's local timezone.
2222
- `target_timezone` (string): Target IANA timezone name. Defaults to the server's local timezone.
2323

24+
- `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?".
25+
- Optional arguments:
26+
- `timezone` (string): IANA timezone name; defaults to the server's local timezone
27+
- `days_ago`, `hours_ago`, `minutes_ago`, `seconds_ago` (non-negative JSON integers, default 0; a fraction, numeric string or boolean is rejected): how far back to go. They add up, so two and a half hours ago is `hours_ago: 2, minutes_ago: 30`.
28+
- 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.
29+
2430
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.
2531

2632
### Protocol versions
@@ -274,6 +280,27 @@ Response (`structuredContent`, and the same JSON as text):
274280
}
275281
```
276282

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

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

299327
## Development
300328

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

Lines changed: 65 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):
@@ -135,6 +136,37 @@ def get_current_time(self, timezone_name: str) -> TimeResult:
135136
is_dst=bool(current_time.dst()),
136137
)
137138

139+
def get_time_ago(
140+
self,
141+
timezone_name: str,
142+
days: int = 0,
143+
hours: int = 0,
144+
minutes: int = 0,
145+
seconds: int = 0,
146+
) -> TimeResult:
147+
"""Get the time an elapsed span before now, in specified timezone.
148+
149+
The span is subtracted from the current instant in UTC, not from the
150+
local wall clock, so "5 hours ago" across a clock change is the instant
151+
five real hours back (#2710). An offset that reaches past what
152+
`datetime` can hold is a `ToolError`, not an `OverflowError`.
153+
"""
154+
timezone = get_zoneinfo(timezone_name)
155+
try:
156+
span = timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
157+
past_time = (datetime.now(ZoneInfo("UTC")) - span).astimezone(timezone)
158+
except OverflowError:
159+
raise ToolError(
160+
"Time offset out of range: the result would be before year 1"
161+
)
162+
163+
return TimeResult(
164+
timezone=timezone_name,
165+
datetime=past_time.isoformat(timespec="seconds"),
166+
day_of_week=past_time.strftime("%A"),
167+
is_dst=bool(past_time.dst()),
168+
)
169+
138170
def convert_time(
139171
self, source_tz: str, time_str: str, target_tz: str
140172
) -> TimeConversionResult:
@@ -318,6 +350,39 @@ def convert_time(
318350
require("target_timezone", target_timezone)
319351
return time_server.convert_time(source_timezone, time, target_timezone)
320352

353+
@server.tool(
354+
name=TimeTools.GET_TIME_AGO.value,
355+
description=(
356+
"Get the time a given number of days, hours, minutes and seconds "
357+
"ago in a specific timezone"
358+
),
359+
annotations=READ_ONLY,
360+
)
361+
def get_time_ago(
362+
timezone: Annotated[
363+
str,
364+
Field(
365+
description=f"IANA timezone name (e.g., 'America/New_York', 'Europe/London'). Optional: defaults to the server's local timezone, '{local_tz}', when omitted."
366+
),
367+
] = local_tz,
368+
days_ago: Annotated[
369+
int, Field(description="Whole days before now", ge=0, strict=True)
370+
] = 0,
371+
hours_ago: Annotated[
372+
int, Field(description="Whole hours before now", ge=0, strict=True)
373+
] = 0,
374+
minutes_ago: Annotated[
375+
int, Field(description="Whole minutes before now", ge=0, strict=True)
376+
] = 0,
377+
seconds_ago: Annotated[
378+
int, Field(description="Whole seconds before now", ge=0, strict=True)
379+
] = 0,
380+
) -> TimeResult:
381+
require("timezone", timezone)
382+
return time_server.get_time_ago(
383+
timezone, days_ago, hours_ago, minutes_ago, seconds_ago
384+
)
385+
321386
return server
322387

323388

‎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: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,41 @@ def expected_tools(local_tz: str) -> list[dict[str, Any]]:
295295
},
296296
"annotations": READ_ONLY_ANNOTATIONS,
297297
},
298+
{
299+
"name": "get_time_ago",
300+
"description": (
301+
"Get the time a given number of days, hours, minutes and seconds "
302+
"ago in a specific timezone"
303+
),
304+
"inputSchema": {
305+
"type": "object",
306+
"title": "get_time_agoArguments",
307+
"properties": {
308+
"timezone": {
309+
"type": "string",
310+
"title": "Timezone",
311+
"default": local_tz,
312+
"description": (
313+
"IANA timezone name (e.g., 'America/New_York', "
314+
"'Europe/London'). Optional: defaults to the server's "
315+
f"local timezone, '{local_tz}', when omitted."
316+
),
317+
},
318+
**{
319+
f"{unit}_ago": {
320+
"type": "integer",
321+
"title": f"{unit.capitalize()} Ago",
322+
"default": 0,
323+
"minimum": 0,
324+
"description": f"Whole {unit} before now",
325+
}
326+
for unit in ("days", "hours", "minutes", "seconds")
327+
},
328+
},
329+
},
330+
"outputSchema": TIME_RESULT_SCHEMA,
331+
"annotations": READ_ONLY_ANNOTATIONS,
332+
},
298333
]
299334

300335

@@ -1163,6 +1198,164 @@ async def test_convert_time_checks_timezones_before_the_time_string() -> None:
11631198
)
11641199

11651200

1201+
# ---------------------------------------------------------------------------
1202+
# tools/call get_time_ago
1203+
# ---------------------------------------------------------------------------
1204+
1205+
1206+
async def test_get_time_ago_wire_result() -> None:
1207+
# The issue's own example (#2710): two and a half hours ago.
1208+
async with connected() as session:
1209+
with frozen_at("2024-01-01 12:00:00+00:00"):
1210+
result = await call(
1211+
session,
1212+
"get_time_ago",
1213+
{"timezone": "UTC", "hours_ago": 2, "minutes_ago": 30},
1214+
)
1215+
expected = {
1216+
"timezone": "UTC",
1217+
"datetime": "2024-01-01T09:30:00+00:00",
1218+
"day_of_week": "Monday",
1219+
"is_dst": False,
1220+
}
1221+
assert result == {
1222+
"content": [{"type": "text", "text": json.dumps(expected, indent=2)}],
1223+
"structuredContent": expected,
1224+
"isError": False,
1225+
}
1226+
1227+
1228+
@pytest.mark.parametrize(
1229+
"arguments,expected",
1230+
[
1231+
# No offset at all is now.
1232+
({}, "2024-01-01T12:00:00+00:00"),
1233+
({"seconds_ago": 1}, "2024-01-01T11:59:59+00:00"),
1234+
({"minutes_ago": 90}, "2024-01-01T10:30:00+00:00"),
1235+
# Every unit at once, crossing back into the previous year.
1236+
(
1237+
{"days_ago": 1, "hours_ago": 2, "minutes_ago": 3, "seconds_ago": 4},
1238+
"2023-12-31T09:56:56+00:00",
1239+
),
1240+
# 2023 is not a leap year: 365 days back is the same date.
1241+
({"days_ago": 365}, "2023-01-01T12:00:00+00:00"),
1242+
],
1243+
)
1244+
async def test_get_time_ago_offsets(arguments: dict[str, Any], expected: str) -> None:
1245+
async with connected() as session:
1246+
with frozen_at("2024-01-01 12:00:00+00:00"):
1247+
result = await call_json(
1248+
session, "get_time_ago", {"timezone": "UTC", **arguments}
1249+
)
1250+
assert result["datetime"] == expected
1251+
1252+
1253+
async def test_get_time_ago_defaults_to_the_local_timezone() -> None:
1254+
# An omitted timezone is the server's local timezone, as the schema's
1255+
# `default` says.
1256+
async with connected("Europe/Warsaw") as session:
1257+
with frozen_at("2024-01-01 12:00:00+00:00"):
1258+
result = await call_json(session, "get_time_ago", {"hours_ago": 1})
1259+
assert result == {
1260+
"timezone": "Europe/Warsaw",
1261+
"datetime": "2024-01-01T12:00:00+01:00",
1262+
"day_of_week": "Monday",
1263+
"is_dst": False,
1264+
}
1265+
1266+
1267+
@pytest.mark.parametrize(
1268+
"arguments,expected,is_dst",
1269+
[
1270+
# 03:30 CEST on the spring-forward day is 01:30 UTC; two real hours
1271+
# back is 23:30 UTC, 00:30 CET. Subtracting from the wall clock would
1272+
# wrongly give 01:30.
1273+
({"hours_ago": 2}, "2024-03-31T00:30:00+01:00", False),
1274+
# A day ago is 24 elapsed hours, 01:30 UTC the day before, so across
1275+
# the change the wall clock reads 02:30 CET, not 03:30.
1276+
({"days_ago": 1}, "2024-03-30T02:30:00+01:00", False),
1277+
({"minutes_ago": 30}, "2024-03-31T03:00:00+02:00", True),
1278+
],
1279+
)
1280+
async def test_get_time_ago_counts_elapsed_time_across_a_clock_change(
1281+
arguments: dict[str, Any], expected: str, is_dst: bool
1282+
) -> None:
1283+
async with connected() as session:
1284+
with frozen_at("2024-03-31 01:30:00+00:00"):
1285+
result = await call_json(
1286+
session, "get_time_ago", {"timezone": "Europe/Warsaw", **arguments}
1287+
)
1288+
assert (result["datetime"], result["is_dst"]) == (expected, is_dst)
1289+
1290+
1291+
async def test_get_time_ago_echoes_the_requested_name_not_a_canonical_one() -> None:
1292+
async with connected() as session:
1293+
with frozen_at("2024-01-01 12:00:00+00:00"):
1294+
result = await call_json(
1295+
session, "get_time_ago", {"timezone": "US/Eastern", "days_ago": 1}
1296+
)
1297+
assert result["timezone"] == "US/Eastern"
1298+
assert result["datetime"] == "2023-12-31T07:00:00-05:00"
1299+
assert result["day_of_week"] == "Sunday"
1300+
1301+
1302+
@pytest.mark.parametrize(
1303+
"arguments,needles",
1304+
[
1305+
# Rejected by MCPServer against the tool's signature, before it runs.
1306+
(
1307+
{"hours_ago": -1},
1308+
["hours_ago\n Input should be greater than or equal to 0"],
1309+
),
1310+
# The offsets are strict integers: no fraction, numeric string or
1311+
# boolean is coerced into a different cutoff.
1312+
({"days_ago": 1.5}, ["days_ago\n Input should be a valid integer"]),
1313+
({"hours_ago": "2"}, ["hours_ago\n Input should be a valid integer"]),
1314+
({"hours_ago": True}, ["hours_ago\n Input should be a valid integer"]),
1315+
({"minutes_ago": "ten"}, ["minutes_ago\n Input should be a valid integer"]),
1316+
({"seconds_ago": None}, ["seconds_ago\n Input should be a valid integer"]),
1317+
({"timezone": None}, ["timezone\n Input should be a valid string"]),
1318+
],
1319+
)
1320+
async def test_get_time_ago_argument_validation(
1321+
arguments: dict[str, Any], needles: list[str]
1322+
) -> None:
1323+
async with connected() as session:
1324+
result = await call(session, "get_time_ago", arguments)
1325+
assert_validation_error(result, "get_time_ago", *needles)
1326+
1327+
1328+
@pytest.mark.parametrize(
1329+
"arguments,message",
1330+
[
1331+
# Raised by the tool as a ToolError.
1332+
({"timezone": ""}, "Missing required argument: timezone"),
1333+
(
1334+
{"timezone": "europe/warsaw"},
1335+
"Invalid timezone: 'No time zone found with key europe/warsaw'",
1336+
),
1337+
# Past what timedelta can hold, and past year 1.
1338+
(
1339+
{"days_ago": 10**10},
1340+
"Time offset out of range: the result would be before year 1",
1341+
),
1342+
(
1343+
{"days_ago": 999_999_999},
1344+
"Time offset out of range: the result would be before year 1",
1345+
),
1346+
# The timezone is checked before the offset.
1347+
(
1348+
{"timezone": "Bad/Zone", "days_ago": 10**10},
1349+
"Invalid timezone: 'No time zone found with key Bad/Zone'",
1350+
),
1351+
],
1352+
)
1353+
async def test_get_time_ago_errors(arguments: dict[str, Any], message: str) -> None:
1354+
async with connected() as session:
1355+
result = await call(session, "get_time_ago", arguments)
1356+
assert result == tool_error("get_time_ago", message)
1357+
1358+
11661359
# ---------------------------------------------------------------------------
11671360
# Unknown tools
11681361
# ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)