convert_temperature
Convert temperature values between Celsius, Fahrenheit, and Kelvin using precise calculations for accurate unit transformations.
Instructions
Convert temperature between units.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| from_unit | Yes | Source unit | |
| to_unit | Yes | Target unit | |
| value | Yes | Temperature value to convert |
Implementation Reference
- src/unit_converter_mcp/server.py:62-76 (handler)MCP tool handler for 'convert_temperature', decorated with @app.tool(). Calls the helper function and returns formatted response.@app.tool() def convert_temperature( value: Annotated[float, Field(description="Temperature value to convert")], from_unit: Annotated[TEMPERATURE_UNIT, Field(description="Source unit")], to_unit: Annotated[TEMPERATURE_UNIT, Field(description="Target unit")], ) -> dict: """Convert temperature between units.""" converted_value = convert_temperature_tool(value, from_unit, to_unit) return { "original_value": value, "original_unit": from_unit, "converted_value": converted_value, "converted_unit": to_unit, "conversion_type": "temperature", }
- Literal type defining valid temperature units used in the tool parameters.TEMPERATURE_UNIT = Literal["celsius", "fahrenheit", "kelvin"]
- Core helper function implementing the temperature conversion logic by converting via intermediate Celsius values.def convert_temperature_tool( value: float, from_unit: TEMPERATURE_UNIT, to_unit: TEMPERATURE_UNIT, ) -> float: """Convert temperature between units.""" # Dictionary mapping units to their conversion functions to Celsius to_celsius: dict[TEMPERATURE_UNIT, Callable[[float], float]] = { "fahrenheit": _fahrenheit_to_celsius, "kelvin": _kelvin_to_celsius, "celsius": lambda x: x, } # Dictionary mapping units to their conversion functions from Celsius from_celsius: dict[TEMPERATURE_UNIT, Callable[[float], float]] = { "fahrenheit": _celsius_to_fahrenheit, "kelvin": _celsius_to_kelvin, "celsius": lambda x: x, } # Convert to Celsius first celsius = to_celsius[from_unit](value) # Convert from Celsius to target unit return from_celsius[to_unit](celsius)
- Helper function for Fahrenheit to Celsius conversion.def _fahrenheit_to_celsius(value: float) -> float: """Convert Fahrenheit to Celsius.""" return (value - 32) * 5 / 9
- Helper function for Celsius to Fahrenheit conversion.def _celsius_to_fahrenheit(value: float) -> float: """Convert Celsius to Fahrenheit.""" return value * 9 / 5 + 32