Skip to main content
Glama
by apetta

array_operations

Perform element-wise mathematical operations on 2D arrays using Polars, including addition, subtraction, multiplication, division, and power operations between arrays or arrays and scalars.

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

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

Input Schema (JSON Schema)

{ "properties": { "array1": { "description": "First 2D array (e.g., [[1,2],[3,4]])", "items": { "items": { "type": "number" }, "type": "array" }, "type": "array" }, "array2": { "anyOf": [ { "type": "string" }, { "items": { "items": { "type": "number" }, "type": "array" }, "type": "array" }, { "type": "number" } ], "description": "Second array, scalar, or JSON string" }, "context": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null, "description": "Optional annotation to label this calculation (e.g., 'Bond A PV', 'Q2 revenue'). Appears in results for easy identification." }, "operation": { "description": "Element-wise operation to perform", "enum": [ "add", "subtract", "multiply", "divide", "power" ], "type": "string" }, "output_mode": { "default": "full", "description": "Output format: full (default), compact, minimal, value, or final. See batch_execute tool for details.", "enum": [ "full", "compact", "minimal", "value", "final" ], "type": "string" } }, "required": [ "operation", "array1", "array2" ], "type": "object" }

Implementation Reference

  • Main handler function performing element-wise add/subtract/multiply/divide/power on 2D arrays, supporting scalar broadcasting and array-array operations using Polars DataFrames (NumPy for power). Handles JSON-stringified inputs from MCP XML serialization.
    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)}")
  • Pydantic schema for tool inputs: operation (enum), array1 (List[List[float]]), array2 (union for scalar/array/string). Includes descriptive Field metadata.
    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:
  • MCP tool registration decorator defining name, description, and annotations (read-only, 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, ), )
  • Import statement that loads the tools modules, executing decorators to register array_operations among other tools with the MCP server instance.
    from .tools import array, basic, batch, calculus, financial, linalg, statistics # noqa: E402

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