Lab
Build a Weather MCP Tool
30 min
Intermediate3 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:
-
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"] } } -
Validates input with a
validate(arguments: dict) -> boolmethod:- Returns
Trueif valid - Raises
ValueErrorwith message if invalid - Must check: city is non-empty string, units (if provided) is valid
- Returns
-
Executes the tool with
execute(arguments: dict) -> dictmethod:- Simulates weather data (use mock data, no real API needed)
- Returns:
{"city": str, "temperature": int, "units": str, "condition": str} - Default units is "celsius"
-
Formats response with
format_response(result: dict) -> strmethod:- 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
°Cfor celsius and°Ffor 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