mcp_ / tools /time_tool.py
eienmojiki's picture
++
49cb9f5
raw
history blame
2.58 kB
import datetime
import pytz # You need to install pytz: pip install pytz
import typing as ty
import gradio as gr
# Import the decorator instance
from utils.mcp_decorator import mcp_tool
# --- Tool Definition ---
@mcp_tool.define(
name="Get current time",
api_name="get_current_time",
)
def get_current_time(timezone: str = "UTC") -> str:
"""
Gets the current time for the given timezone string.
This tool takes an IANA timezone name (like "UTC", "America/New_York",
"Asia/Ho_Chi_Minh") and returns the current datetime in that zone.
Defaults to "UTC" if no timezone is provided.
Args:
timezone (str): The IANA timezone string (e.g., "UTC").
Returns:
str: The current time in the specified timezone, or an error message.
"""
try:
# Get the timezone object
tz = pytz.timezone(timezone)
# Get the current UTC time and convert it to the target timezone
now_utc = datetime.datetime.utcnow()
now_in_tz = pytz.utc.localize(now_utc).astimezone(tz)
# Format the time
return now_in_tz.strftime('%Y-%m-%d %H:%M:%S %Z%z')
except pytz.UnknownTimeZoneError:
return f"Error: Unknown timezone '{timezone}'. Please provide a valid IANA timezone name."
except Exception as e:
return f"An unexpected error occurred: {e}"
# --- UI Control Builder ---
@mcp_tool.build_ui_control(api_name="get_current_time")
def build_time_ui_control() -> gr.Group:
"""
Builds Gradio UI components for the Get current time tool.
Returns a gr.Group containing the controls.
"""
# Use a gr.Group to contain the controls for this tool
# We will manage the visibility of this group in the main app
with gr.Group(visible=False) as time_tool_group:
gr.Markdown("Configure **Get current time** tool:")
# Create a textbox for the 'timezone' argument
timezone_input = gr.Textbox(
label="Timezone",
value="UTC",
placeholder="e.g., America/New_York, Asia/Ho_Chi_Minh",
interactive=True,
)
# Note: We are only building the *display* components here.
# If you wanted a "Run" button in the UI, you would add it here
# and define an event handler in the main app.
# For dynamic display based on tool selection, returning a container
# (like gr.Group or gr.Column) is a good pattern.
return time_tool_group # Return the group containing the controls
# When this file is imported, the decorators register the tool and its UI builder