solve_linear_system
Solve systems of linear equations (Ax = b) using SciPy's optimized solver for square or overdetermined systems. Input coefficient matrix and constants vector to compute exact or least-squares solutions.
Instructions
Solve systems of linear equations (Ax = b) using SciPy's optimised solver.
Examples:
SQUARE SYSTEM (2 equations, 2 unknowns): coefficients=[[2,3],[1,1]], constants=[8,3], method="direct" Solves: 2x+3y=8, x+y=3 Result: [x=1, y=2]
OVERDETERMINED SYSTEM (3 equations, 2 unknowns): coefficients=[[1,2],[3,4],[5,6]], constants=[5,6,7], method="least_squares" Finds best-fit x minimizing ||Ax-b|| Result: [x≈-6, y≈5.5]
3x3 SYSTEM: coefficients=[[2,1,-1],[1,3,2],[-1,2,1]], constants=[8,13,5], method="direct" Result: [x=3, y=2, z=1]
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 |
| coefficients | Yes | Coefficient matrix A in Ax=b system (2D list, e.g., [[2,3],[1,1]]) | |
| constants | Yes | Constants vector b in Ax=b system (1D list, e.g., [8,3]) | |
| method | No | Solution method: direct=exact (square systems), least_squares=overdetermined systems | direct |
Input Schema (JSON Schema)
Implementation Reference
- src/vibe_math_mcp/tools/linalg.py:109-133 (registration)Registers the solve_linear_system tool using the @mcp.tool decorator, including detailed description with usage examples and tool annotations.@mcp.tool( name="solve_linear_system", description="""Solve systems of linear equations (Ax = b) using SciPy's optimised solver. Examples: SQUARE SYSTEM (2 equations, 2 unknowns): coefficients=[[2,3],[1,1]], constants=[8,3], method="direct" Solves: 2x+3y=8, x+y=3 Result: [x=1, y=2] OVERDETERMINED SYSTEM (3 equations, 2 unknowns): coefficients=[[1,2],[3,4],[5,6]], constants=[5,6,7], method="least_squares" Finds best-fit x minimizing ||Ax-b|| Result: [x≈-6, y≈5.5] 3x3 SYSTEM: coefficients=[[2,1,-1],[1,3,2],[-1,2,1]], constants=[8,13,5], method="direct" Result: [x=3, y=2, z=1]""", annotations=ToolAnnotations( title="Linear System Solver", readOnlyHint=True, idempotentHint=True, ), )
- The core handler function implementing the logic to solve linear systems Ax=b, supporting direct solve for square matrices and least-squares for overdetermined systems using SciPy.linalg, with comprehensive input validation and formatted JSON output.async def solve_linear_system( coefficients: Annotated[List[List[float]], Field(description="Coefficient matrix A in Ax=b system (2D list, e.g., [[2,3],[1,1]])")], constants: Annotated[List[float], Field(description="Constants vector b in Ax=b system (1D list, e.g., [8,3])")], method: Annotated[Literal["direct", "least_squares"], Field(description="Solution method: direct=exact (square systems), least_squares=overdetermined systems")] = "direct", ) -> str: """Solve linear systems Ax=b using SciPy. Direct method for square systems, least squares for overdetermined. More stable than matrix inversion.""" try: A = list_to_numpy(coefficients) b = np.array(constants, dtype=float) if A.shape[0] != len(b): raise ValueError( f"Incompatible dimensions: coefficient matrix has {A.shape[0]} rows " f"but constants vector has {len(b)} elements" ) if method == "direct": if A.shape[0] != A.shape[1]: raise ValueError( f"Direct method requires square matrix. Got {A.shape}. " f"Use method='least_squares' for overdetermined systems." ) try: x = la.solve(A, b) except np.linalg.LinAlgError: raise ValueError("System is singular or poorly conditioned") elif method == "least_squares": x, residuals, rank, _ = la.lstsq(A, b) # type: ignore[misc] metadata = { "method": method, "rank": int(rank), "residuals": residuals.tolist() if len(residuals) > 0 else None, } return format_result(x.tolist(), metadata) else: raise ValueError(f"Unknown method: {method}") return format_result(x.tolist(), {"method": method}) except Exception as e: if isinstance(e, ValueError): raise raise ValueError(f"Linear system solution failed: {str(e)}")
- Pydantic input schema definitions using Annotated types and Field descriptions for the tool parameters: coefficients (matrix A), constants (vector b), and method (direct or least_squares).coefficients: Annotated[List[List[float]], Field(description="Coefficient matrix A in Ax=b system (2D list, e.g., [[2,3],[1,1]])")], constants: Annotated[List[float], Field(description="Constants vector b in Ax=b system (1D list, e.g., [8,3])")], method: Annotated[Literal["direct", "least_squares"], Field(description="Solution method: direct=exact (square systems), least_squares=overdetermined systems")] = "direct",