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
| Name | Required | Description | Default |
|---|---|---|---|
| context | No | Optional annotation to label this calculation (e.g., 'Bond A PV', 'Q2 revenue'). Appears in results for easy identification. | |
| output_mode | No | Output format: full (default), compact, minimal, value, or final. See batch_execute tool for details. | full |
| operation | Yes | Element-wise operation to perform | |
| array1 | Yes | First 2D array (e.g., [[1,2],[3,4]]) | |
| array2 | Yes | Second array, scalar, or JSON string |
Input Schema (JSON Schema)
Implementation Reference
- src/vibe_math_mcp/tools/array.py:42-95 (handler)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:
- src/vibe_math_mcp/tools/array.py:13-41 (registration)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, ), )
- src/vibe_math_mcp/server.py:693-693 (registration)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