Створення вашого першого MCP-сервера

Вступ до Model Context Protocol (MCP)

James Chapman

AI Curriculum Manager, DataCamp

Конвертація між часовими поясами

 

timezone_server.png

1 https://opentimezone.com/
Вступ до Model Context Protocol (MCP)

mcp_code_flow_v2.png

Вступ до Model Context Protocol (MCP)

Крок 1: Ініціалізація сервера

from mcp.server.fastmcp import FastMCP
import requests

# Create an MCP server instance
mcp = FastMCP("Timezone Converter")
1 https://github.com/modelcontextprotocol/python-sdk
Вступ до Model Context Protocol (MCP)

Крок 2: Додавання інструментів

from mcp.server.fastmcp import FastMCP
import requests

# Create an MCP server instance
mcp = FastMCP("Timezone Converter")

@mcp.tool()
def convert_timezone(date_time, from_timezone, to_timezone):
Вступ до Model Context Protocol (MCP)

Крок 2: Додавання інструментів

@mcp.tool()
def convert_timezone(date_time, from_timezone, to_timezone):

    # Define the API endpoint and format input data

url = "https://api.opentimezone.com/convert" payload = {"dateTime": date_time, "fromTimezone": from_timezone, "toTimezone": to_timezone}
response = requests.post(url, json=payload)
data = response.json() converted_time = data.get('dateTime', 'N/A')
return f"Time in {to_timezone}: {converted_time}"
Вступ до Model Context Protocol (MCP)

Крок 3: Докстрінги та типи

@mcp.tool()
def convert_timezone(date_time: str, from_timezone: str, to_timezone: str) -> str:
    """
    Convert a datetime from one timezone to another.

    Args:
        date_time: The datetime string in ISO format (e.g., '2025-01-20T14:30:00')
        from_timezone: Source timezone (e.g., 'America/New_York')
        to_timezone: Target timezone (e.g., 'Europe/London')

    Returns:
        A string with the converted datetime and timezone information
    """
Вступ до Model Context Protocol (MCP)

mcp_code_flow_v2.png

Вступ до Model Context Protocol (MCP)

Passons à la pratique !

Вступ до Model Context Protocol (MCP)

Preparing Video For Download...