Skip to content

Commit bd29867

Browse files
committed
Add time server schema constraints
1 parent 3a32d10 commit bd29867

2 files changed

Lines changed: 120 additions & 38 deletions

File tree

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

Lines changed: 65 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,15 @@
88

99
from mcp.server import Server
1010
from mcp.server.stdio import stdio_server
11-
from mcp.types import Tool, ToolAnnotations, TextContent, ImageContent, EmbeddedResource, ErrorData, INVALID_PARAMS
11+
from mcp.types import (
12+
Tool,
13+
ToolAnnotations,
14+
TextContent,
15+
ImageContent,
16+
EmbeddedResource,
17+
ErrorData,
18+
INVALID_PARAMS,
19+
)
1220
from mcp.shared.exceptions import McpError
1321

1422
from pydantic import BaseModel
@@ -38,6 +46,57 @@ class TimeConversionInput(BaseModel):
3846
target_tz_list: list[str]
3947

4048

49+
TIMEZONE_NAME_PATTERN = r"^[A-Za-z0-9_+\-./]+$"
50+
TIMEZONE_NAME_MAX_LENGTH = 128
51+
TIME_24H_PATTERN = r"^([01]?[0-9]|2[0-3]):[0-5][0-9]$"
52+
53+
54+
def timezone_schema(description: str) -> dict[str, object]:
55+
return {
56+
"type": "string",
57+
"description": description,
58+
"maxLength": TIMEZONE_NAME_MAX_LENGTH,
59+
"pattern": TIMEZONE_NAME_PATTERN,
60+
}
61+
62+
63+
def time_24h_schema() -> dict[str, object]:
64+
return {
65+
"type": "string",
66+
"description": "Time to convert in 24-hour format (HH:MM)",
67+
"maxLength": 5,
68+
"pattern": TIME_24H_PATTERN,
69+
}
70+
71+
72+
def get_current_time_input_schema(local_tz: str) -> dict[str, object]:
73+
return {
74+
"type": "object",
75+
"properties": {
76+
"timezone": timezone_schema(
77+
f"IANA timezone name (e.g., 'America/New_York', 'Europe/London'). Use '{local_tz}' as local timezone if no timezone provided by the user."
78+
)
79+
},
80+
"required": ["timezone"],
81+
}
82+
83+
84+
def convert_time_input_schema(local_tz: str) -> dict[str, object]:
85+
return {
86+
"type": "object",
87+
"properties": {
88+
"source_timezone": timezone_schema(
89+
f"Source IANA timezone name (e.g., 'America/New_York', 'Europe/London'). Use '{local_tz}' as local timezone if no source timezone provided by the user."
90+
),
91+
"time": time_24h_schema(),
92+
"target_timezone": timezone_schema(
93+
f"Target IANA timezone name (e.g., 'Asia/Tokyo', 'America/San_Francisco'). Use '{local_tz}' as local timezone if no target timezone provided by the user."
94+
),
95+
},
96+
"required": ["source_timezone", "time", "target_timezone"],
97+
}
98+
99+
41100
def get_local_tz(local_tz_override: str | None = None) -> ZoneInfo:
42101
if local_tz_override:
43102
return ZoneInfo(local_tz_override)
@@ -54,7 +113,9 @@ def get_zoneinfo(timezone_name: str) -> ZoneInfo:
54113
try:
55114
return ZoneInfo(timezone_name)
56115
except Exception as e:
57-
raise McpError(ErrorData(code=INVALID_PARAMS, message=f"Invalid timezone: {str(e)}"))
116+
raise McpError(
117+
ErrorData(code=INVALID_PARAMS, message=f"Invalid timezone: {str(e)}")
118+
)
58119

59120

60121
class TimeServer:
@@ -132,16 +193,7 @@ async def list_tools() -> list[Tool]:
132193
Tool(
133194
name=TimeTools.GET_CURRENT_TIME.value,
134195
description="Get current time in a specific timezone",
135-
inputSchema={
136-
"type": "object",
137-
"properties": {
138-
"timezone": {
139-
"type": "string",
140-
"description": f"IANA timezone name (e.g., 'America/New_York', 'Europe/London'). Use '{local_tz}' as local timezone if no timezone provided by the user.",
141-
}
142-
},
143-
"required": ["timezone"],
144-
},
196+
inputSchema=get_current_time_input_schema(local_tz),
145197
annotations=ToolAnnotations(
146198
readOnlyHint=True,
147199
destructiveHint=False,
@@ -152,24 +204,7 @@ async def list_tools() -> list[Tool]:
152204
Tool(
153205
name=TimeTools.CONVERT_TIME.value,
154206
description="Convert time between timezones",
155-
inputSchema={
156-
"type": "object",
157-
"properties": {
158-
"source_timezone": {
159-
"type": "string",
160-
"description": f"Source IANA timezone name (e.g., 'America/New_York', 'Europe/London'). Use '{local_tz}' as local timezone if no source timezone provided by the user.",
161-
},
162-
"time": {
163-
"type": "string",
164-
"description": "Time to convert in 24-hour format (HH:MM)",
165-
},
166-
"target_timezone": {
167-
"type": "string",
168-
"description": f"Target IANA timezone name (e.g., 'Asia/Tokyo', 'America/San_Francisco'). Use '{local_tz}' as local timezone if no target timezone provided by the user.",
169-
},
170-
},
171-
"required": ["source_timezone", "time", "target_timezone"],
172-
},
207+
inputSchema=convert_time_input_schema(local_tz),
173208
annotations=ToolAnnotations(
174209
readOnlyHint=True,
175210
destructiveHint=False,

‎src/time/test/time_server_test.py‎

Lines changed: 55 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,20 @@
1-
1+
import re
22
from freezegun import freeze_time
33
from mcp.shared.exceptions import McpError
44
import pytest
55
from unittest.mock import patch
66
from zoneinfo import ZoneInfo
77

8-
from mcp_server_time.server import TimeServer, get_local_tz
8+
from mcp_server_time.server import (
9+
TIMEZONE_NAME_MAX_LENGTH,
10+
TIMEZONE_NAME_PATTERN,
11+
TIME_24H_PATTERN,
12+
TimeServer,
13+
convert_time_input_schema,
14+
get_current_time_input_schema,
15+
get_local_tz,
16+
time_24h_schema,
17+
)
918

1019

1120
@pytest.mark.parametrize(
@@ -91,6 +100,44 @@ def test_get_current_time_with_invalid_timezone():
91100
time_server.get_current_time("Invalid/Timezone")
92101

93102

103+
def test_tool_input_schemas_include_string_constraints():
104+
current_time_schema = get_current_time_input_schema("UTC")
105+
convert_time_schema = convert_time_input_schema("UTC")
106+
timezone = current_time_schema["properties"]["timezone"]
107+
source_timezone = convert_time_schema["properties"]["source_timezone"]
108+
target_timezone = convert_time_schema["properties"]["target_timezone"]
109+
time = convert_time_schema["properties"]["time"]
110+
111+
assert timezone["maxLength"] == TIMEZONE_NAME_MAX_LENGTH
112+
assert timezone["pattern"] == TIMEZONE_NAME_PATTERN
113+
assert source_timezone["maxLength"] == TIMEZONE_NAME_MAX_LENGTH
114+
assert source_timezone["pattern"] == TIMEZONE_NAME_PATTERN
115+
assert target_timezone["maxLength"] == TIMEZONE_NAME_MAX_LENGTH
116+
assert target_timezone["pattern"] == TIMEZONE_NAME_PATTERN
117+
assert time["maxLength"] == 5
118+
assert time["pattern"] == TIME_24H_PATTERN
119+
120+
121+
@pytest.mark.parametrize("timezone", ["America/New_York", "Etc/GMT+5", "UTC"])
122+
def test_timezone_schema_pattern_accepts_common_iana_names(timezone):
123+
assert re.fullmatch(TIMEZONE_NAME_PATTERN, timezone)
124+
125+
126+
@pytest.mark.parametrize("timezone", ["America/New York", "Bad\tZone"])
127+
def test_timezone_schema_pattern_rejects_whitespace(timezone):
128+
assert not re.fullmatch(TIMEZONE_NAME_PATTERN, timezone)
129+
130+
131+
@pytest.mark.parametrize("time", ["00:00", "7:30", "23:59"])
132+
def test_time_schema_pattern_accepts_runtime_compatible_times(time):
133+
assert re.fullmatch(time_24h_schema()["pattern"], time)
134+
135+
136+
@pytest.mark.parametrize("time", ["24:00", "12:60", "12:345"])
137+
def test_time_schema_pattern_rejects_invalid_times(time):
138+
assert not re.fullmatch(time_24h_schema()["pattern"], time)
139+
140+
94141
@pytest.mark.parametrize(
95142
"source_tz,time_str,target_tz,expected_error",
96143
[
@@ -475,7 +522,7 @@ def test_get_local_tz_with_invalid_override():
475522
get_local_tz("Invalid/Timezone")
476523

477524

478-
@patch('mcp_server_time.server.get_localzone_name')
525+
@patch("mcp_server_time.server.get_localzone_name")
479526
def test_get_local_tz_with_valid_iana_name(mock_get_localzone):
480527
"""Test that valid IANA timezone names from tzlocal work correctly."""
481528
mock_get_localzone.return_value = "Europe/London"
@@ -484,18 +531,18 @@ def test_get_local_tz_with_valid_iana_name(mock_get_localzone):
484531
assert isinstance(result, ZoneInfo)
485532

486533

487-
@patch('mcp_server_time.server.get_localzone_name')
534+
@patch("mcp_server_time.server.get_localzone_name")
488535
def test_get_local_tz_when_none_returned(mock_get_localzone):
489536
"""Test default to UTC when tzlocal returns None."""
490537
mock_get_localzone.return_value = None
491538
result = get_local_tz()
492539
assert str(result) == "UTC"
493540

494541

495-
@patch('mcp_server_time.server.get_localzone_name')
542+
@patch("mcp_server_time.server.get_localzone_name")
496543
def test_get_local_tz_handles_windows_timezones(mock_get_localzone):
497544
"""Test that tzlocal properly handles Windows timezone names.
498-
545+
499546
Note: tzlocal should convert Windows names like 'Pacific Standard Time'
500547
to proper IANA names like 'America/Los_Angeles'.
501548
"""
@@ -510,7 +557,7 @@ def test_get_local_tz_handles_windows_timezones(mock_get_localzone):
510557
"timezone_name",
511558
[
512559
"America/New_York",
513-
"Europe/Paris",
560+
"Europe/Paris",
514561
"Asia/Tokyo",
515562
"Australia/Sydney",
516563
"Africa/Cairo",
@@ -519,7 +566,7 @@ def test_get_local_tz_handles_windows_timezones(mock_get_localzone):
519566
"UTC",
520567
],
521568
)
522-
@patch('mcp_server_time.server.get_localzone_name')
569+
@patch("mcp_server_time.server.get_localzone_name")
523570
def test_get_local_tz_various_timezones(mock_get_localzone, timezone_name):
524571
"""Test various timezone names that tzlocal might return."""
525572
mock_get_localzone.return_value = timezone_name

0 commit comments

Comments
 (0)