matrix_operations
Perform matrix operations including multiplication, inverse, transpose, determinant, and trace calculations using NumPy BLAS for linear algebra tasks.
Instructions
Core matrix operations using NumPy BLAS.
Examples:
MATRIX MULTIPLICATION: operation="multiply", matrix1=[[1,2],[3,4]], matrix2=[[5,6],[7,8]] Result: [[19,22],[43,50]]
MATRIX INVERSE: operation="inverse", matrix1=[[1,2],[3,4]] Result: [[-2,1],[1.5,-0.5]]
TRANSPOSE: operation="transpose", matrix1=[[1,2],[3,4]] Result: [[1,3],[2,4]]
DETERMINANT: operation="determinant", matrix1=[[1,2],[3,4]] Result: -2.0
TRACE: operation="trace", matrix1=[[1,2],[3,4]] Result: 5.0 (1+4)
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 | Matrix operation | |
| matrix1 | Yes | First matrix (e.g., [[1,2],[3,4]]) | |
| matrix2 | No | Second matrix for multiplication |
Input Schema (JSON Schema)
Implementation Reference
- src/vibe_math_mcp/tools/linalg.py:46-107 (handler)The async handler function that executes the matrix_operations tool. Handles operations: multiply (requires matrix2), inverse, transpose, determinant, trace. Uses NumPy for computations and SciPy.linalg for advanced ops like inv/det. Converts lists to/from NumPy arrays, formats results as JSON strings with metadata.async def matrix_operations( operation: Annotated[Literal["multiply", "inverse", "transpose", "determinant", "trace"], Field(description="Matrix operation")], matrix1: Annotated[List[List[float]], Field(description="First matrix (e.g., [[1,2],[3,4]])")], matrix2: Annotated[Union[str, List[List[float]], None], Field(description="Second matrix for multiplication")] = None, ) -> str: """Core matrix operations.""" try: # Parse stringified JSON from XML serialization if isinstance(matrix2, str): matrix2 = cast(List[List[float]], json.loads(matrix2)) mat1 = list_to_numpy(matrix1) if operation == "multiply": if matrix2 is None: raise ValueError("Matrix multiplication requires matrix2") mat2 = list_to_numpy(matrix2) if mat1.shape[1] != mat2.shape[0]: raise ValueError( f"Incompatible shapes for multiplication: {mat1.shape} and {mat2.shape}. " f"First matrix columns must equal second matrix rows." ) result = np.dot(mat1, mat2) return format_array_result(numpy_to_list(result), {"operation": operation}) elif operation == "inverse": if mat1.shape[0] != mat1.shape[1]: raise ValueError(f"Matrix must be square for inversion. Got shape: {mat1.shape}") try: result = la.inv(mat1) return format_array_result(numpy_to_list(result), {"operation": operation}) except np.linalg.LinAlgError: raise ValueError("Matrix is singular and cannot be inverted") elif operation == "transpose": result = mat1.T return format_array_result(numpy_to_list(result), {"operation": operation}) elif operation == "determinant": if mat1.shape[0] != mat1.shape[1]: raise ValueError(f"Matrix must be square for determinant. Got shape: {mat1.shape}") result = float(la.det(mat1)) return format_result( result, {"operation": operation, "shape": f"{mat1.shape[0]}×{mat1.shape[1]}"} ) elif operation == "trace": if mat1.shape[0] != mat1.shape[1]: raise ValueError(f"Matrix must be square for trace. Got shape: {mat1.shape}") result = float(np.trace(mat1)) return format_result( result, {"operation": operation, "shape": f"{mat1.shape[0]}×{mat1.shape[1]}"} ) else: raise ValueError(f"Unknown operation: {operation}") except Exception as e: if isinstance(e, ValueError): raise raise ValueError(f"Matrix operation failed: {str(e)}")
- src/vibe_math_mcp/tools/linalg.py:15-45 (registration)MCP tool registration via @mcp.tool decorator, defining name, comprehensive description with examples, input schema hints via function signature, and annotations indicating read-only and idempotent nature.@mcp.tool( name="matrix_operations", description="""Core matrix operations using NumPy BLAS. Examples: MATRIX MULTIPLICATION: operation="multiply", matrix1=[[1,2],[3,4]], matrix2=[[5,6],[7,8]] Result: [[19,22],[43,50]] MATRIX INVERSE: operation="inverse", matrix1=[[1,2],[3,4]] Result: [[-2,1],[1.5,-0.5]] TRANSPOSE: operation="transpose", matrix1=[[1,2],[3,4]] Result: [[1,3],[2,4]] DETERMINANT: operation="determinant", matrix1=[[1,2],[3,4]] Result: -2.0 TRACE: operation="trace", matrix1=[[1,2],[3,4]] Result: 5.0 (1+4)""", annotations=ToolAnnotations( title="Matrix Operations", readOnlyHint=True, idempotentHint=True, ), )
- Pydantic schema definitions for tool inputs using Annotated types: operation (enum), matrix1 (list of lists of float), optional matrix2 (for multiply). Output str (JSON).async def matrix_operations( operation: Annotated[Literal["multiply", "inverse", "transpose", "determinant", "trace"], Field(description="Matrix operation")], matrix1: Annotated[List[List[float]], Field(description="First matrix (e.g., [[1,2],[3,4]])")], matrix2: Annotated[Union[str, List[List[float]], None], Field(description="Second matrix for multiplication")] = None, ) -> str: