matrix_operations
Perform matrix operations including multiplication, inverse, transpose, determinant, and trace calculations using NumPy BLAS for mathematical workflows.
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 |
Implementation Reference
- src/vibe_math_mcp/tools/linalg.py:15-107 (handler)The primary handler: @mcp.tool-decorated async function implementing core matrix operations (multiply, inverse, transpose, determinant, trace) with NumPy/SciPy. Includes input schema via Annotated types.@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, ), ) 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/server.py:693-693 (registration)Import statement in server.py that loads the linalg module, registering the matrix_operations tool via its @mcp.tool decorator.from .tools import array, basic, batch, calculus, financial, linalg, statistics # noqa: E402
- Input schema defined via Pydantic Annotated types and Field descriptions in the handler function signature.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:
- matrix_operations listed in TOOL_CATEGORIES for batch_execute tool discovery and documentation."Linear Algebra": ["matrix_operations", "solve_linear_system", "matrix_decomposition"],