convert_energy
Convert energy values between units such as joules, watt hours, BTUs, and more. Simplify calculations for scientific, engineering, or everyday use with precise unit conversions.
Instructions
Convert energy between units.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| from_unit | Yes | Source unit | |
| to_unit | Yes | Target unit | |
| value | Yes | Energy value to convert |
Implementation Reference
- src/unit_converter_mcp/server.py:113-127 (handler)MCP tool handler for 'convert_energy' registered via @app.tool(). Calls convert_energy_tool for logic and returns formatted dict response.@app.tool() def convert_energy( value: Annotated[float, Field(description="Energy value to convert")], from_unit: Annotated[ENERGY_UNIT, Field(description="Source unit")], to_unit: Annotated[ENERGY_UNIT, Field(description="Target unit")], ) -> dict: """Convert energy between units.""" converted_value = convert_energy_tool(value, from_unit, to_unit) return { "original_value": value, "original_unit": from_unit, "converted_value": converted_value, "converted_unit": to_unit, "conversion_type": "energy", }
- Core helper function implementing the energy unit conversion logic by normalizing to joules.def convert_energy_tool( value: float, from_unit: ENERGY_UNIT, to_unit: ENERGY_UNIT, ) -> float: """Convert energy between units.""" # Convert to joules first to_joules = { # SI and metric prefixes "joule": 1.0, "kilojoule": 1_000.0, "megajoule": 1_000_000.0, "gigajoule": 1_000_000_000.0, "terajoule": 1_000_000_000_000.0, "petajoule": 1_000_000_000_000_000.0, "exajoule": 1_000_000_000_000_000_000.0, # Electrical‑energy units "watt hour": 3_600.0, "kilowatt hour": 3_600_000.0, "megawatt hour": 3_600_000_000.0, "gigawatt hour": 3_600_000_000_000.0, "terawatt hour": 3_600_000_000_000_000.0, # Heat / nutrition "Btu": 1_054.35, "calorie": 4.184, "kilocalorie": 4_184.0, "therm": 105_505_585.257348, # Mechanical & particle‑physics units "foot‑pound force": 1.355_817_948_331, "inch‑pound force": 0.112_984_829_028, "erg": 1e-7, "electron volt": 1.602_176_634e-19, } joules = value * to_joules[from_unit] return joules / to_joules[to_unit]
- Pydantic-compatible type definition (Literal) for all supported ENERGY_UNIT strings, used in tool signatures for input validation.ENERGY_UNIT = Literal[ "joule", "kilojoule", "megajoule", "gigajoule", "terajoule", "petajoule", "exajoule", "watt hour", "kilowatt hour", "megawatt hour", "gigawatt hour", "terawatt hour", "Btu", "calorie", "kilocalorie", "therm", "foot‑pound force", "inch‑pound force", "erg", "electron volt", ]