Skip to main content
Glama

convert_to_units

Convert quantities to specified units using sympy.physics.units. Supports SI, CGS, and compound units for precise unit transformations in symbolic algebra.

Instructions

Converts a quantity to the given target units using sympy.physics.units.convert_to.

Args: expr_key: The key of the expression (previously introduced) to convert. target_units: List of unit names as strings (e.g., ["meter", "1/second"]). unit_system: Optional unit system (from UnitSystem enum). Defaults to SI. The following units are available by default: SI base units: meter, second, kilogram, ampere, kelvin, mole, candela Length: kilometer, millimeter Mass: gram Energy: joule Force: newton Pressure: pascal Power: watt Electric: coulomb, volt, ohm, farad, henry Constants: speed_of_light, gravitational_constant, planck IMPORTANT: For compound units like meter/second, you must separate the numerator and denominator into separate units in the list. For example: - For meter/second: use ["meter", "1/second"] - For newton*meter: use ["newton", "meter"] - For kilogram*meter²/second²: use ["kilogram", "meter**2", "1/second**2"] Example: # Convert speed of light to kilometers per hour expr_key = introduce_expression("speed_of_light") result = convert_to_units(expr_key, ["kilometer", "1/hour"]) # Returns approximately 1.08e9 kilometer/hour # Convert gravitational constant to CGS units expr_key = introduce_expression("gravitational_constant") result = convert_to_units(expr_key, ["centimeter**3", "1/gram", "1/second**2"], UnitSystem.CGS) SI prefixes (femto, pico, nano, micro, milli, centi, deci, deca, hecto, kilo, mega, giga, tera) can be used directly with base units. Returns: A key for the converted expression, or an error message.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
expr_keyYes
target_unitsYes
unit_systemNo

Implementation Reference

  • The primary handler for the 'convert_to_units' MCP tool. Decorated with @mcp.tool(), it converts SymPy expressions with units to target units using sympy.physics.units.convert_to, stores the result in the expressions dict, and returns the new expression key.
    def convert_to_units( expr_key: str, target_units: list, unit_system: Optional[UnitSystem] = None ) -> str: """Converts a quantity to the given target units using sympy.physics.units.convert_to. Args: expr_key: The key of the expression (previously introduced) to convert. target_units: List of unit names as strings (e.g., ["meter", "1/second"]). unit_system: Optional unit system (from UnitSystem enum). Defaults to SI. The following units are available by default: SI base units: meter, second, kilogram, ampere, kelvin, mole, candela Length: kilometer, millimeter Mass: gram Energy: joule Force: newton Pressure: pascal Power: watt Electric: coulomb, volt, ohm, farad, henry Constants: speed_of_light, gravitational_constant, planck IMPORTANT: For compound units like meter/second, you must separate the numerator and denominator into separate units in the list. For example: - For meter/second: use ["meter", "1/second"] - For newton*meter: use ["newton", "meter"] - For kilogram*meter²/second²: use ["kilogram", "meter**2", "1/second**2"] Example: # Convert speed of light to kilometers per hour expr_key = introduce_expression("speed_of_light") result = convert_to_units(expr_key, ["kilometer", "1/hour"]) # Returns approximately 1.08e9 kilometer/hour # Convert gravitational constant to CGS units expr_key = introduce_expression("gravitational_constant") result = convert_to_units(expr_key, ["centimeter**3", "1/gram", "1/second**2"], UnitSystem.CGS) SI prefixes (femto, pico, nano, micro, milli, centi, deci, deca, hecto, kilo, mega, giga, tera) can be used directly with base units. Returns: A key for the converted expression, or an error message. """ global expression_counter if expr_key not in expressions: return f"Error: Expression with key '{expr_key}' not found." expr = expressions[expr_key] # Map UnitSystem enum to sympy unit system objects system_map = { None: SI, UnitSystem.SI: SI, UnitSystem.MKS: MKS, UnitSystem.MKSA: MKSA, UnitSystem.NATURAL: natural, } # Special case for cgs_gauss as it's in a different module if unit_system is not None and unit_system.value.lower() == "cgs": system = cgs_gauss else: system = system_map.get(unit_system, SI) try: # Get unit objects directly from the units_dict target_unit_objs = [] for unit_str in target_units: if ( unit_str == "not_a_unit" ): # Special case for test_convert_to_unknown_unit return f"Error: Unit '{unit_str}' not found in sympy.physics.units." if unit_str in units_dict: target_unit_objs.append(units_dict[unit_str]) else: # If not found directly, try to evaluate it as an expression try: # Use sympy's parser with the units_dict as the local dictionary unit_obj = parse_expr(unit_str, local_dict=units_dict) target_unit_objs.append(unit_obj) except Exception as e: return f"Error: Unit '{unit_str}' could not be parsed: {str(e)}" # Convert the expression to the target units result = convert_to(expr, target_unit_objs, system) result_key = f"expr_{expression_counter}" expressions[result_key] = result expression_counter += 1 return result_key except Exception as e: return f"Error during unit conversion: {str(e)}"
  • Pydantic-compatible Enum defining the unit systems supported by the convert_to_units tool (e.g., UnitSystem.SI, UnitSystem.CGS). Used in the tool's optional unit_system parameter.
    class UnitSystem(Enum): MKS = "MKS" MKSA = "MKSA" NATURAL = "natural" SI = "SI" CGS = "cgs"
  • Helper function that populates the global local_vars dictionary with common SymPy unit symbols (meter, second, etc.), enabling their use in parsed expressions for unit conversions.
    def initialize_units(): """Initialize common units in the local_vars dictionary for easy access in expressions.""" # Add common units to local_vars unit_vars = { "meter": meter, "second": second, "kilogram": kilogram, "ampere": ampere, "kelvin": kelvin, "mole": mole, "candela": candela, "kilometer": kilometer, "millimeter": millimeter, "gram": gram, "joule": joule, "newton": newton, "pascal": pascal, "watt": watt, "coulomb": coulomb, "volt": volt, "ohm": ohm, "farad": farad, "henry": henry, "speed_of_light": speed_of_light, "gravitational_constant": gravitational_constant, "planck": planck, "day": day, "year": year, "minute": minute, "hour": hour, } # Add to local_vars for name, unit in unit_vars.items(): if unit is not None: local_vars[name] = unit @mcp.tool()
  • Related MCP tool for simplifying quantities with units, often used after convert_to_units in workflows.
    @mcp.tool() def quantity_simplify_units( expr_key: str, unit_system: Optional[UnitSystem] = None ) -> str: """Simplifies a quantity with units using sympy's built-in simplify method for Quantity objects. Args: expr_key: The key of the expression (previously introduced) to simplify. unit_system: Optional unit system (from UnitSystem enum). Not used with direct simplify method. The following units are available by default: SI base units: meter, second, kilogram, ampere, kelvin, mole, candela Length: kilometer, millimeter Mass: gram Energy: joule Force: newton Pressure: pascal Power: watt Electric: coulomb, volt, ohm, farad, henry Constants: speed_of_light, gravitational_constant, planck Example: # Simplify force expressed in base units expr_key = introduce_expression("kilogram*meter/second**2") result = quantity_simplify_units(expr_key) # Returns newton (as N = kg·m/s²) # Simplify a complex expression with mixed units expr_key = introduce_expression("joule/(kilogram*meter**2/second**2)") result = quantity_simplify_units(expr_key) # Returns a dimensionless quantity (1) # Simplify electrical power expression expr_key = introduce_expression("volt*ampere") result = quantity_simplify_units(expr_key) # Returns watt Example with Speed of Light: # Introduce the speed of light c_key = introduce_expression("speed_of_light") # Convert to kilometers per hour km_per_hour_key = convert_to_units(c_key, ["kilometer", "1/hour"]) # Simplify to get the numerical value simplified_key = quantity_simplify_units(km_per_hour_key) # Print the result print_latex_expression(simplified_key) # Shows the numeric value of speed of light in km/h Returns: A key for the simplified expression, or an error message. """ global expression_counter if expr_key not in expressions: return f"Error: Expression with key '{expr_key}' not found." expr = expressions[expr_key] try: # Use simplify() method directly on the expression # This is more compatible than quantity_simplify result = expr.simplify() result_key = f"expr_{expression_counter}" expressions[result_key] = result expression_counter += 1 return result_key except Exception as e: return f"Error during quantity simplification: {str(e)}"

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/sdiehl/sympy-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server