Skip to content

Commit e33f079

Browse files
committed
refactor(time): port to MCP Python SDK v2
Migrate src/time to the v2 low-level Server API (same shape as #4565): constructor callbacks, MCPError(code/message), ListToolsResult / CallToolResult, snake_case tool fields, mcp>=2,<3 + uv.lock. Fixes #4570 follow-up beyond the short-term dependency cap.
1 parent 76d64c8 commit e33f079

4 files changed

Lines changed: 143 additions & 142 deletions

File tree

‎src/time/pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ classifiers = [
1717
"Programming Language :: Python :: 3.10",
1818
]
1919
dependencies = [
20-
"mcp>=1.23.0",
20+
"mcp>=2,<3",
2121
"pydantic>=2.0.0",
2222
"tzdata>=2024.2",
2323
"tzlocal>=5.3.1",

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

Lines changed: 79 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,23 @@
11
from datetime import datetime, timedelta
22
from enum import Enum
33
import json
4-
from typing import Sequence
54

65
from zoneinfo import ZoneInfo
76
from tzlocal import get_localzone_name # ← returns "Europe/Paris", etc.
87

9-
from mcp.server import Server
8+
from mcp.server import Server, ServerRequestContext
109
from mcp.server.stdio import stdio_server
11-
from mcp.types import Tool, ToolAnnotations, TextContent, ImageContent, EmbeddedResource, ErrorData, INVALID_PARAMS
12-
from mcp.shared.exceptions import McpError
10+
from mcp.types import (
11+
CallToolRequestParams,
12+
CallToolResult,
13+
ListToolsResult,
14+
PaginatedRequestParams,
15+
Tool,
16+
ToolAnnotations,
17+
TextContent,
18+
INVALID_PARAMS,
19+
)
20+
from mcp.shared.exceptions import MCPError
1321

1422
from pydantic import BaseModel
1523

@@ -54,7 +62,7 @@ def get_zoneinfo(timezone_name: str) -> ZoneInfo:
5462
try:
5563
return ZoneInfo(timezone_name)
5664
except Exception as e:
57-
raise McpError(ErrorData(code=INVALID_PARAMS, message=f"Invalid timezone: {str(e)}"))
65+
raise MCPError(code=INVALID_PARAMS, message=f"Invalid timezone: {str(e)}")
5866

5967

6068
class TimeServer:
@@ -121,71 +129,73 @@ def convert_time(
121129

122130

123131
async def serve(local_timezone: str | None = None) -> None:
124-
server = Server("mcp-time")
125132
time_server = TimeServer()
126133
local_tz = str(get_local_tz(local_timezone))
127134

128-
@server.list_tools()
129-
async def list_tools() -> list[Tool]:
135+
async def list_tools(
136+
ctx: ServerRequestContext, params: PaginatedRequestParams | None
137+
) -> ListToolsResult:
130138
"""List available time tools."""
131-
return [
132-
Tool(
133-
name=TimeTools.GET_CURRENT_TIME.value,
134-
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-
}
139+
return ListToolsResult(
140+
tools=[
141+
Tool(
142+
name=TimeTools.GET_CURRENT_TIME.value,
143+
description="Get current time in a specific timezone",
144+
input_schema={
145+
"type": "object",
146+
"properties": {
147+
"timezone": {
148+
"type": "string",
149+
"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.",
150+
}
151+
},
152+
"required": ["timezone"],
142153
},
143-
"required": ["timezone"],
144-
},
145-
annotations=ToolAnnotations(
146-
readOnlyHint=True,
147-
destructiveHint=False,
148-
idempotentHint=True,
149-
openWorldHint=False,
154+
annotations=ToolAnnotations(
155+
read_only_hint=True,
156+
destructive_hint=False,
157+
idempotent_hint=True,
158+
open_world_hint=False,
159+
),
150160
),
151-
),
152-
Tool(
153-
name=TimeTools.CONVERT_TIME.value,
154-
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.",
161+
Tool(
162+
name=TimeTools.CONVERT_TIME.value,
163+
description="Convert time between timezones",
164+
input_schema={
165+
"type": "object",
166+
"properties": {
167+
"source_timezone": {
168+
"type": "string",
169+
"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.",
170+
},
171+
"time": {
172+
"type": "string",
173+
"description": "Time to convert in 24-hour format (HH:MM)",
174+
},
175+
"target_timezone": {
176+
"type": "string",
177+
"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.",
178+
},
169179
},
180+
"required": ["source_timezone", "time", "target_timezone"],
170181
},
171-
"required": ["source_timezone", "time", "target_timezone"],
172-
},
173-
annotations=ToolAnnotations(
174-
readOnlyHint=True,
175-
destructiveHint=False,
176-
idempotentHint=True,
177-
openWorldHint=False,
182+
annotations=ToolAnnotations(
183+
read_only_hint=True,
184+
destructive_hint=False,
185+
idempotent_hint=True,
186+
open_world_hint=False,
187+
),
178188
),
179-
),
180-
]
189+
]
190+
)
181191

182-
@server.call_tool()
183192
async def call_tool(
184-
name: str, arguments: dict
185-
) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
193+
ctx: ServerRequestContext, params: CallToolRequestParams
194+
) -> CallToolResult:
186195
"""Handle tool calls for time queries."""
196+
arguments = params.arguments or {}
187197
try:
188-
match name:
198+
match params.name:
189199
case TimeTools.GET_CURRENT_TIME.value:
190200
timezone = arguments.get("timezone")
191201
if not timezone:
@@ -206,15 +216,23 @@ async def call_tool(
206216
arguments["target_timezone"],
207217
)
208218
case _:
209-
raise ValueError(f"Unknown tool: {name}")
219+
raise ValueError(f"Unknown tool: {params.name}")
210220

211-
return [
212-
TextContent(type="text", text=json.dumps(result.model_dump(), indent=2))
213-
]
221+
return CallToolResult(
222+
content=[
223+
TextContent(type="text", text=json.dumps(result.model_dump(), indent=2))
224+
]
225+
)
214226

215227
except Exception as e:
216228
raise ValueError(f"Error processing mcp-server-time query: {str(e)}")
217229

230+
server = Server(
231+
"mcp-time",
232+
on_list_tools=list_tools,
233+
on_call_tool=call_tool,
234+
)
235+
218236
options = server.create_initialization_options()
219237
async with stdio_server() as (read_stream, write_stream):
220238
await server.run(read_stream, write_stream, options)

‎src/time/test/time_server_test.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11

22
from freezegun import freeze_time
3-
from mcp.shared.exceptions import McpError
3+
from mcp.shared.exceptions import MCPError
44
import pytest
55
from unittest.mock import patch
66
from zoneinfo import ZoneInfo
@@ -85,7 +85,7 @@ def test_get_current_time(test_time, timezone, expected):
8585
def test_get_current_time_with_invalid_timezone():
8686
time_server = TimeServer()
8787
with pytest.raises(
88-
McpError,
88+
MCPError,
8989
match=r"Invalid timezone: 'No time zone found with key Invalid/Timezone'",
9090
):
9191
time_server.get_current_time("Invalid/Timezone")
@@ -116,7 +116,7 @@ def test_get_current_time_with_invalid_timezone():
116116
)
117117
def test_convert_time_errors(source_tz, time_str, target_tz, expected_error):
118118
time_server = TimeServer()
119-
with pytest.raises((McpError, ValueError), match=expected_error):
119+
with pytest.raises((MCPError, ValueError), match=expected_error):
120120
time_server.convert_time(source_tz, time_str, target_tz)
121121

122122

0 commit comments

Comments
 (0)