Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/time/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ classifiers = [
"Programming Language :: Python :: 3.10",
]
dependencies = [
"mcp>=1.23.0",
"mcp>=2,<3",
"pydantic>=2.0.0",
"tzdata>=2024.2",
"tzlocal>=5.3.1",
Expand Down
150 changes: 88 additions & 62 deletions src/time/src/mcp_server_time/server.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
from datetime import datetime, timedelta
from enum import Enum
import json
from typing import Sequence

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

from mcp.server import Server
from mcp.server import Server, ServerRequestContext
from mcp.server.stdio import stdio_server
from mcp.types import Tool, ToolAnnotations, TextContent, ImageContent, EmbeddedResource, ErrorData, INVALID_PARAMS
from mcp.shared.exceptions import McpError
from mcp.types import (
CallToolRequestParams,
CallToolResult,
ListToolsResult,
PaginatedRequestParams,
Tool,
ToolAnnotations,
TextContent,
INVALID_PARAMS,
)
from mcp.shared.exceptions import MCPError

from pydantic import BaseModel

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


class TimeServer:
Expand Down Expand Up @@ -120,72 +128,75 @@ def convert_time(
)


async def serve(local_timezone: str | None = None) -> None:
server = Server("mcp-time")
def create_tool_handlers(local_timezone: str | None = None):
"""Build list_tools / call_tool handlers for the time MCP server."""
time_server = TimeServer()
local_tz = str(get_local_tz(local_timezone))

@server.list_tools()
async def list_tools() -> list[Tool]:
async def list_tools(
ctx: ServerRequestContext, params: PaginatedRequestParams | None
) -> ListToolsResult:
"""List available time tools."""
return [
Tool(
name=TimeTools.GET_CURRENT_TIME.value,
description="Get current time in a specific timezone",
inputSchema={
"type": "object",
"properties": {
"timezone": {
"type": "string",
"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.",
}
return ListToolsResult(
tools=[
Tool(
name=TimeTools.GET_CURRENT_TIME.value,
description="Get current time in a specific timezone",
input_schema={
"type": "object",
"properties": {
"timezone": {
"type": "string",
"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.",
}
},
"required": ["timezone"],
},
"required": ["timezone"],
},
annotations=ToolAnnotations(
readOnlyHint=True,
destructiveHint=False,
idempotentHint=True,
openWorldHint=False,
annotations=ToolAnnotations(
read_only_hint=True,
destructive_hint=False,
idempotent_hint=True,
open_world_hint=False,
),
),
),
Tool(
name=TimeTools.CONVERT_TIME.value,
description="Convert time between timezones",
inputSchema={
"type": "object",
"properties": {
"source_timezone": {
"type": "string",
"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.",
},
"time": {
"type": "string",
"description": "Time to convert in 24-hour format (HH:MM)",
},
"target_timezone": {
"type": "string",
"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.",
Tool(
name=TimeTools.CONVERT_TIME.value,
description="Convert time between timezones",
input_schema={
"type": "object",
"properties": {
"source_timezone": {
"type": "string",
"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.",
},
"time": {
"type": "string",
"description": "Time to convert in 24-hour format (HH:MM)",
},
"target_timezone": {
"type": "string",
"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.",
},
},
"required": ["source_timezone", "time", "target_timezone"],
},
"required": ["source_timezone", "time", "target_timezone"],
},
annotations=ToolAnnotations(
readOnlyHint=True,
destructiveHint=False,
idempotentHint=True,
openWorldHint=False,
annotations=ToolAnnotations(
read_only_hint=True,
destructive_hint=False,
idempotent_hint=True,
open_world_hint=False,
),
),
),
]
]
)

@server.call_tool()
async def call_tool(
name: str, arguments: dict
) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
ctx: ServerRequestContext, params: CallToolRequestParams
) -> CallToolResult:
"""Handle tool calls for time queries."""
arguments = params.arguments or {}
try:
match name:
match params.name:
case TimeTools.GET_CURRENT_TIME.value:
timezone = arguments.get("timezone")
if not timezone:
Expand All @@ -206,15 +217,30 @@ async def call_tool(
arguments["target_timezone"],
)
case _:
raise ValueError(f"Unknown tool: {name}")
raise ValueError(f"Unknown tool: {params.name}")

return [
TextContent(type="text", text=json.dumps(result.model_dump(), indent=2))
]
return CallToolResult(
content=[
TextContent(type="text", text=json.dumps(result.model_dump(), indent=2))
]
)

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

return list_tools, call_tool


async def serve(local_timezone: str | None = None) -> None:
list_tools, call_tool = create_tool_handlers(local_timezone)
server = Server(
"mcp-time",
on_list_tools=list_tools,
on_call_tool=call_tool,
)

options = server.create_initialization_options()
async with stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream, options)
71 changes: 67 additions & 4 deletions src/time/test/time_server_test.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@

import asyncio
import json

from freezegun import freeze_time
from mcp.shared.exceptions import McpError
from mcp.shared.exceptions import MCPError
from mcp.types import CallToolRequestParams, INVALID_PARAMS, TextContent
import pytest
from unittest.mock import patch
from zoneinfo import ZoneInfo

from mcp_server_time.server import TimeServer, get_local_tz
from mcp_server_time.server import TimeServer, create_tool_handlers, get_local_tz


@pytest.mark.parametrize(
Expand Down Expand Up @@ -85,7 +89,7 @@ def test_get_current_time(test_time, timezone, expected):
def test_get_current_time_with_invalid_timezone():
time_server = TimeServer()
with pytest.raises(
McpError,
MCPError,
match=r"Invalid timezone: 'No time zone found with key Invalid/Timezone'",
):
time_server.get_current_time("Invalid/Timezone")
Expand Down Expand Up @@ -116,7 +120,7 @@ def test_get_current_time_with_invalid_timezone():
)
def test_convert_time_errors(source_tz, time_str, target_tz, expected_error):
time_server = TimeServer()
with pytest.raises((McpError, ValueError), match=expected_error):
with pytest.raises((MCPError, ValueError), match=expected_error):
time_server.convert_time(source_tz, time_str, target_tz)


Expand Down Expand Up @@ -526,3 +530,62 @@ def test_get_local_tz_various_timezones(mock_get_localzone, timezone_name):
result = get_local_tz()
assert str(result) == timezone_name
assert isinstance(result, ZoneInfo)


def test_list_tools_returns_expected_tools():
list_tools, _ = create_tool_handlers("UTC")

async def _run():
return await list_tools(None, None) # type: ignore[arg-type]

result = asyncio.run(_run())
assert [tool.name for tool in result.tools] == [
"get_current_time",
"convert_time",
]


def test_call_tool_get_current_time():
_, call_tool = create_tool_handlers("UTC")
params = CallToolRequestParams(
name="get_current_time",
arguments={"timezone": "Europe/Warsaw"},
)

async def _run():
with freeze_time("2024-01-01 12:00:00+00:00"):
return await call_tool(None, params) # type: ignore[arg-type]

result = asyncio.run(_run())
assert len(result.content) == 1
content = result.content[0]
assert isinstance(content, TextContent)
payload = json.loads(content.text)
assert payload["timezone"] == "Europe/Warsaw"
assert payload["datetime"] == "2024-01-01T13:00:00+01:00"


def test_call_tool_invalid_timezone_raises_mcp_error():
_, call_tool = create_tool_handlers("UTC")
params = CallToolRequestParams(
name="get_current_time",
arguments={"timezone": "Invalid/Timezone"},
)

async def _run():
await call_tool(None, params) # type: ignore[arg-type]

with pytest.raises(MCPError) as exc_info:
asyncio.run(_run())
assert exc_info.value.code == INVALID_PARAMS


def test_call_tool_unknown_tool_raises_value_error():
_, call_tool = create_tool_handlers("UTC")
params = CallToolRequestParams(name="unknown_tool", arguments={})

async def _run():
await call_tool(None, params) # type: ignore[arg-type]

with pytest.raises(ValueError, match="Error processing mcp-server-time query"):
asyncio.run(_run())
Loading