Skip to main content
Glama
by apetta

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

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
operationYesMatrix operation
matrix1YesFirst matrix (e.g., [[1,2],[3,4]])
matrix2NoSecond matrix for multiplication

Input Schema (JSON Schema)

{ "properties": { "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." }, "matrix1": { "description": "First matrix (e.g., [[1,2],[3,4]])", "items": { "items": { "type": "number" }, "type": "array" }, "type": "array" }, "matrix2": { "anyOf": [ { "type": "string" }, { "items": { "items": { "type": "number" }, "type": "array" }, "type": "array" }, { "type": "null" } ], "default": null, "description": "Second matrix for multiplication" }, "operation": { "description": "Matrix operation", "enum": [ "multiply", "inverse", "transpose", "determinant", "trace" ], "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": [ "matrix1", "operation" ], "type": "object" }

Implementation Reference

  • 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)}")
  • 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:

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