Skip to main content
Glama
apetta

Vibe Math MCP

by apetta

array_operations

Perform element-wise mathematical operations on 2D arrays using Polars. Supports array-array and array-scalar calculations including addition, subtraction, multiplication, division, and power operations.

Instructions

Perform element-wise operations on arrays using Polars.

Supports array-array and array-scalar operations.

Examples:

SCALAR MULTIPLICATION: operation="multiply", array1=[[1,2],[3,4]], array2=2 Result: [[2,4],[6,8]]

ARRAY ADDITION: operation="add", array1=[[1,2]], array2=[[3,4]] Result: [[4,6]]

POWER OPERATION: operation="power", array1=[[2,3]], array2=2 Result: [[4,9]]

ARRAY DIVISION: operation="divide", array1=[[10,20],[30,40]], array2=[[2,4],[5,8]] Result: [[5,5],[6,5]]

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
contextNoOptional annotation to label this calculation (e.g., 'Bond A PV', 'Q2 revenue'). Appears in results for easy identification.
output_modeNoOutput format: full (default), compact, minimal, value, or final. See batch_execute tool for details.full
operationYesElement-wise operation to perform
array1YesFirst 2D array (e.g., [[1,2],[3,4]])
array2YesSecond array, scalar, or JSON string

Implementation Reference

  • The main handler function for the 'array_operations' tool. Performs element-wise arithmetic operations on 2D arrays (or array-scalar) using Polars DataFrames for add/subtract/multiply/divide and NumPy for power. Handles JSON string inputs from MCP serialization, division by zero, and formats output with shape info.
    async def array_operations(
        operation: Annotated[
            Literal["add", "subtract", "multiply", "divide", "power"],
            Field(description="Element-wise operation to perform"),
        ],
        array1: Annotated[List[List[float]], Field(description="First 2D array (e.g., [[1,2],[3,4]])")],
        array2: Annotated[
            Union[str, List[List[float]], float],
            Field(description="Second array, scalar, or JSON string"),
        ],
    ) -> str:
        """Element-wise array operations."""
        try:
            # Handle XML serialization: parse stringified JSON
            if isinstance(array2, str):
                try:
                    array2 = cast(List[List[float]], json.loads(array2))
                except (json.JSONDecodeError, ValueError):
                    array2 = cast(float, float(array2))
    
            df1 = list_to_polars(array1)
    
            is_scalar = isinstance(array2, (int, float))
    
            if operation == "add":
                result_df = df1 + array2 if is_scalar else df1 + list_to_polars(array2)
            elif operation == "subtract":
                result_df = df1 - array2 if is_scalar else df1 - list_to_polars(array2)
            elif operation == "multiply":
                result_df = df1 * array2 if is_scalar else df1 * list_to_polars(array2)
            elif operation == "divide":
                if is_scalar and array2 == 0:
                    raise ValueError("Division by zero")
                result_df = df1 / array2 if is_scalar else df1 / list_to_polars(array2)
            elif operation == "power":
                # Use NumPy for reliable power operations (Polars doesn't support ** operator)
                arr1 = df1.to_numpy()
                if is_scalar:
                    result_arr = arr1**array2
                else:
                    arr2 = list_to_polars(array2).to_numpy()
                    result_arr = arr1**arr2
                result_df = list_to_polars(result_arr.tolist())
            else:
                raise ValueError(f"Unknown operation: {operation}")
    
            result = polars_to_list(result_df)
    
            return format_array_result(
                result, {"operation": operation, "shape": f"{len(result)}×{len(result[0])}"}
            )
        except Exception as e:
            raise ValueError(f"Array operation failed: {str(e)}")
  • Registers the 'array_operations' tool with the MCP server using the @mcp.tool decorator. Includes detailed description with examples and tool annotations indicating it's read-only and idempotent.
    @mcp.tool(
        name="array_operations",
        description="""Perform element-wise operations on arrays using Polars.
    
    Supports array-array and array-scalar operations.
    
    Examples:
    
    SCALAR MULTIPLICATION:
        operation="multiply", array1=[[1,2],[3,4]], array2=2
        Result: [[2,4],[6,8]]
    
    ARRAY ADDITION:
        operation="add", array1=[[1,2]], array2=[[3,4]]
        Result: [[4,6]]
    
    POWER OPERATION:
        operation="power", array1=[[2,3]], array2=2
        Result: [[4,9]]
    
    ARRAY DIVISION:
        operation="divide", array1=[[10,20],[30,40]], array2=[[2,4],[5,8]]
        Result: [[5,5],[6,5]]""",
        annotations=ToolAnnotations(
            title="Array Operations",
            readOnlyHint=True,
            idempotentHint=True,
        ),
    )
  • Pydantic-based input schema definition using Annotated types and Field descriptions for operation type, array1 (2D list of floats), and array2 (flexible: str/2D list/scalar).
        operation: Annotated[
            Literal["add", "subtract", "multiply", "divide", "power"],
            Field(description="Element-wise operation to perform"),
        ],
        array1: Annotated[List[List[float]], Field(description="First 2D array (e.g., [[1,2],[3,4]])")],
        array2: Annotated[
            Union[str, List[List[float]], float],
            Field(description="Second array, scalar, or JSON string"),
        ],
    ) -> str:
  • Imports the tools modules in server.py, which triggers the execution of decorators and registers all tools including array_operations with the MCP instance.
    from .tools import array, basic, batch, calculus, financial, linalg, statistics  # noqa: E402
    
    # Explicitly declare as part of module interface (tools registered via decorators)
    __all__ = ["mcp", "basic", "array", "batch", "statistics", "financial", "linalg", "calculus"]
    
    
    def main():
        """Entry point for uvx."""
        mcp.run()
    
    
    if __name__ == "__main__":
        main()

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/apetta/vibe-math-mcp'

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