@@ -254,6 +254,11 @@ Tools automatically generate JSON Schema definitions for their return types, hel
254
254
255
255
``` python
256
256
from pydantic import BaseModel
257
+ from mcp.server.fastmcp import FastMCP
258
+
259
+ # Create server
260
+ mcp = FastMCP(" Output Schema Demo" )
261
+
257
262
258
263
# Tools with primitive return types
259
264
@mcp.tool ()
@@ -262,50 +267,60 @@ def get_temperature(city: str) -> float:
262
267
# In a real implementation, this would fetch actual weather data
263
268
return 72.5
264
269
270
+
265
271
# Tools with dictionary return types
266
272
@mcp.tool ()
267
273
def get_user (user_id : int ) -> dict :
268
274
""" Get user information by ID"""
269
275
return {" id" : user_id, " name" : " John Doe" , " email" : " john@example.com" }
270
276
277
+
271
278
# Using Pydantic models for structured output
272
279
class WeatherData (BaseModel ):
273
280
temperature: float
274
281
humidity: float
275
282
conditions: str
276
283
284
+
277
285
@mcp.tool ()
278
286
def get_weather_data (city : str ) -> WeatherData:
279
287
""" Get structured weather data for a city"""
280
288
# In a real implementation, this would fetch actual weather data
281
289
return WeatherData(
282
290
temperature = 72.5 ,
283
291
humidity = 65.0 ,
284
- conditions = " Partly cloudy"
292
+ conditions = " Partly cloudy" ,
285
293
)
286
294
295
+
287
296
# Complex nested models
288
297
class Location (BaseModel ):
289
298
city: str
290
299
country: str
291
300
coordinates: tuple[float , float ]
292
301
302
+
293
303
class WeatherForecast (BaseModel ):
294
304
current: WeatherData
295
305
location: Location
296
306
forecast: list[WeatherData]
297
307
308
+
298
309
@mcp.tool ()
299
310
def get_weather_forecast (city : str ) -> WeatherForecast:
300
311
""" Get detailed weather forecast for a city"""
301
312
# In a real implementation, this would fetch actual forecast data
302
313
return WeatherForecast(
303
- current = WeatherData(temperature = 72.5 , humidity = 65.0 , conditions = " Partly cloudy" ),
314
+ current = WeatherData(
315
+ temperature = 72.5 ,
316
+ humidity = 65.0 ,
317
+ conditions = " Partly cloudy" ,
318
+ ),
304
319
location = Location(city = city, country = " USA" , coordinates = (37.7749 , - 122.4194 )),
305
320
forecast = [
306
321
WeatherData(temperature = 75.0 , humidity = 62.0 , conditions = " Sunny" ),
307
- WeatherData(temperature = 68.0 , humidity = 80.0 , conditions = " Rainy" )
308
- ]
322
+ WeatherData(temperature = 68.0 , humidity = 80.0 , conditions = " Rainy" ),
323
+ ],
309
324
)
310
325
```
311
326
0 commit comments