Skip to main content
Glama
zazencodes

Unit Converter MCP

by zazencodes

convert_batch

Convert multiple measurement units simultaneously in a single operation, handling temperature, length, mass, and volume conversions with structured results.

Instructions

Perform multiple unit conversions in a single batch request.

Each request in the batch should contain:

  • value: The numeric value to convert

  • from_unit: Source unit for conversion

  • to_unit: Target unit for conversion

  • conversion_type: Type of conversion (temperature, length, mass, etc.)

  • request_id: Optional identifier for tracking individual requests

Returns a structured response with individual results for each conversion, including success/failure status and either converted values or error messages.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
requestsYesList of conversion requests. Each request should contain: value (float), from_unit (str), to_unit (str), conversion_type (str), and optionally request_id (str)

Implementation Reference

  • The primary MCP tool handler for 'convert_batch'. This FastMCP-registered function processes the input list of conversion requests, delegates to convert_batch_tool for execution, adds a summary of results, and returns the batch response.
    @app.tool()
    def convert_batch(
        requests: Annotated[
            list[dict],
            Field(
                description="List of conversion requests. Each request should contain: value (float), from_unit (str), to_unit (str), conversion_type (str), and optionally request_id (str)"
            ),
        ],
    ) -> dict:
        """Perform multiple unit conversions in a single batch request.
    
        Each request in the batch should contain:
        - value: The numeric value to convert
        - from_unit: Source unit for conversion
        - to_unit: Target unit for conversion
        - conversion_type: Type of conversion (temperature, length, mass, etc.)
        - request_id: Optional identifier for tracking individual requests
    
        Returns a structured response with individual results for each conversion,
        including success/failure status and either converted values or error messages.
        """
        results = convert_batch_tool(requests)
    
        # Count successful and failed conversions
        successful = sum(1 for result in results if result["success"])
        failed = len(results) - successful
    
        return {
            "batch_results": results,
            "summary": {
                "total_requests": len(requests),
                "successful_conversions": successful,
                "failed_conversions": failed,
            },
        }
  • Core implementation of batch conversion logic. Parses requests, validates inputs, routes to appropriate single-unit converters via CONVERSION_FUNCTIONS mapping, handles exceptions, and formats results.
    def convert_batch_tool(requests: list[dict[str, Any]]) -> list[dict[str, Any]]:
        """Perform batch unit conversions.
    
        Args:
            requests: List of conversion request dictionaries, each containing:
                - value: float - The numeric value to convert
                - from_unit: str - Source unit
                - to_unit: str - Target unit
                - conversion_type: str - Type of conversion
                - request_id: str (optional) - Identifier for tracking
    
        Returns:
            List of conversion result dictionaries with success/failure status
            and either converted values or error messages.
        """
        results: list[dict[str, Any]] = []
    
        for request_data in requests:
            try:
                # Validate required fields first
                value = request_data.get("value")
                from_unit = request_data.get("from_unit")
                to_unit = request_data.get("to_unit")
                conversion_type = request_data.get("conversion_type")
                request_id = request_data.get("request_id")
    
                if value is None:
                    raise ValueError("Missing required field: value")
                if not from_unit:
                    raise ValueError("Missing required field: from_unit")
                if not to_unit:
                    raise ValueError("Missing required field: to_unit")
                if not conversion_type:
                    raise ValueError("Missing required field: conversion_type")
    
                # Create request object with validated data
                request = BatchConversionRequest(
                    value=float(value),
                    from_unit=str(from_unit),
                    to_unit=str(to_unit),
                    conversion_type=conversion_type,
                    request_id=request_id,
                )
    
                # Validate conversion type
                if request.conversion_type not in CONVERSION_FUNCTIONS:
                    raise ValueError(
                        f"Unsupported conversion type: {request.conversion_type}"
                    )
    
                # Perform the conversion
                conversion_func = CONVERSION_FUNCTIONS[request.conversion_type]
                converted_value = conversion_func(
                    request.value, request.from_unit, request.to_unit
                )
    
                # Create successful result
                result = BatchConversionResult(
                    request_id=request.request_id,
                    success=True,
                    original_value=request.value,
                    original_unit=request.from_unit,
                    converted_value=converted_value,
                    converted_unit=request.to_unit,
                    conversion_type=request.conversion_type,
                )
    
            except Exception as e:
                # Create error result
                request_id = request_data.get("request_id", f"error_{len(results)}")
                result = BatchConversionResult(
                    request_id=request_id,
                    success=False,
                    error_message=str(e),
                )
    
            results.append(result.to_dict())
    
        return results
  • Type definition (Literal) for valid 'conversion_type' values accepted by the batch tool.
    CONVERSION_TYPE = Literal[
        "angle",
        "area",
        "computer_data",
        "density",
        "energy",
        "force",
        "length",
        "mass",
        "power",
        "pressure",
        "speed",
        "temperature",
        "time",
        "volume",
    ]
  • Input schema for the 'requests' parameter defining the expected structure of batch conversion requests using Pydantic Field for description.
    requests: Annotated[
        list[dict],
        Field(
            description="List of conversion requests. Each request should contain: value (float), from_unit (str), to_unit (str), conversion_type (str), and optionally request_id (str)"
        ),
    ],
  • Dictionary mapping conversion types to their specific implementation functions, used for dynamic dispatching in convert_batch_tool.
    CONVERSION_FUNCTIONS: dict[str, Callable[..., float]] = {
        "angle": convert_angle_tool,
        "area": convert_area_tool,
        "computer_data": convert_computer_data_tool,
        "density": convert_density_tool,
        "energy": convert_energy_tool,
        "force": convert_force_tool,
        "length": convert_length_tool,
        "mass": convert_mass_tool,
        "power": convert_power_tool,
        "pressure": convert_pressure_tool,
        "speed": convert_speed_tool,
        "temperature": convert_temperature_tool,
        "time": convert_time_tool,
        "volume": convert_volume_tool,
    }

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/zazencodes/unit-converter-mcp'

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