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)

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

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,
    }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes key behaviors: it's a batch operation (multiple conversions at once), returns structured responses with success/failure status and error messages, and handles optional request_id for tracking. However, it doesn't mention potential limitations like rate limits, maximum batch size, or authentication needs.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with the core purpose in the first sentence, followed by a bulleted list of request components and a clear statement about the return format. Every sentence earns its place by providing essential information without redundancy, making it highly efficient and well-structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (batch processing with multiple parameters), no annotations, and the presence of an output schema (which handles return values), the description is complete enough. It covers purpose, usage, parameters, and behavioral outcomes, leaving no critical gaps for an AI agent to understand and invoke the tool correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds significant meaning beyond the input schema's 100% coverage. While the schema generically describes 'requests' as an array of objects, the description details each request's components (value, from_unit, to_unit, conversion_type, request_id), explains their purposes, and clarifies that request_id is optional. This compensates for the schema's lack of nested property descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific verb ('Perform multiple unit conversions') and resource ('in a single batch request'), distinguishing it from sibling tools that handle single conversions of specific types. It explicitly mentions batch processing, which sets it apart from individual conversion tools like convert_temperature or convert_length.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool: for 'multiple unit conversions in a single batch request.' It implicitly suggests alternatives (the sibling tools) for single conversions, though it doesn't name them directly. The context is clear and leaves no ambiguity about its batch-oriented purpose.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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