Back to Course|MCP Mastery: Building AI-Powered Integrations with Model Context Protocol
Lab

Build a Weather MCP Tool

30 min
Intermediate
3 Free Attempts

Instructions

Objective

Build a Python class that represents an MCP weather tool, complete with input validation, error handling, and proper response formatting.

Requirements

Create a class WeatherTool that:

  1. Defines the tool schema with a get_tool_definition() method that returns:

    {
        "name": "get_weather",
        "description": "Get current weather for a city",
        "inputSchema": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "City name"},
                "units": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            },
            "required": ["city"]
        }
    }
    
  2. Validates input with a validate(arguments: dict) -> bool method:

    • Returns True if valid
    • Raises ValueError with message if invalid
    • Must check: city is non-empty string, units (if provided) is valid
  3. Executes the tool with execute(arguments: dict) -> dict method:

    • Simulates weather data (use mock data, no real API needed)
    • Returns: {"city": str, "temperature": int, "units": str, "condition": str}
    • Default units is "celsius"
  4. Formats response with format_response(result: dict) -> str method:

    • Returns human-readable string like: "Weather in London: 15°C, Partly cloudy"

Example Usage

tool = WeatherTool()

# Get definition
definition = tool.get_tool_definition()
print(definition["name"])  # "get_weather"

# Validate
tool.validate({"city": "London"})  # True
tool.validate({"city": ""})  # Raises ValueError

# Execute
result = tool.execute({"city": "London", "units": "celsius"})
# {"city": "London", "temperature": 15, "units": "celsius", "condition": "Partly cloudy"}

# Format
text = tool.format_response(result)
# "Weather in London: 15°C, Partly cloudy"

Hints

  • For mock weather, you can use a simple dict mapping cities to temperatures
  • Use °C for celsius and °F for fahrenheit in formatted output
  • Validation should be strict but handle optional fields gracefully

Grading Rubric

Correctly implements get_tool_definition with proper schema25 points
Validate method properly checks required fields and raises ValueError25 points
Execute method returns complete result dict with all required fields25 points
Format_response produces correct human-readable output with proper units25 points

Your Solution

This lab requires Python
🐍Python(required)
3 free attempts remaining