Introduction to Model Context Protocol (MCP)
James Chapman
AI Curriculum Manager, DataCamp




import requests @mcp.tool() def convert_timezone(date_time: str, from_timezone: str, to_timezone: str) -> str: payload = {"dateTime": date_time, "fromTimezone": from_timezone, "toTimezone": to_timezone}try: r = requests.post("https://api.opentimezone.com/convert", json=payload, timeout=10)r.raise_for_status()data = r.json() converted_time = data.get("dateTime", "N/A") return f"Time in {to_timezone}: {converted_time}"except requests.exceptions.RequestException as e: return f"Error converting timezone: {e}"

.env

.env

.envThe client never sends, receives, or accesses the credentials

.envThe client never sends, receives, or accesses the credentials
❌ Hard-coded, inserted into URLs, logged
❌ Tools argument or tool results

import os import requests @mcp.tool() def convert_timezone(date_time: str, from_timezone: str, to_timezone: str) -> str:headers = {"Content-Type": "application/json"}api_key = os.environ.get("TIMEZONE_API_KEY") if api_key: headers["Authorization"] = f"Bearer {api_key}"payload = {"dateTime": date_time, "fromTimezone": from_timezone, "toTimezone": to_timezone} try: r = requests.post("https://api.opentimezone.com/convert", json=payload, headers=headers, timeout=10) r.raise_for_status() data = r.json() converted_time = data.get("dateTime", "N/A") return f"Time in {to_timezone}: {converted_time}" except requests.exceptions.RequestException as e: return f"Error converting timezone: {e}"
Introduction to Model Context Protocol (MCP)