Skip to main content
Glama
by apetta

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

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
coefficientsYesCoefficient matrix A in Ax=b system (2D list, e.g., [[2,3],[1,1]])
constantsYesConstants vector b in Ax=b system (1D list, e.g., [8,3])
methodNoSolution method: direct=exact (square systems), least_squares=overdetermined systemsdirect

Input Schema (JSON Schema)

{ "properties": { "coefficients": { "description": "Coefficient matrix A in Ax=b system (2D list, e.g., [[2,3],[1,1]])", "items": { "items": { "type": "number" }, "type": "array" }, "type": "array" }, "constants": { "description": "Constants vector b in Ax=b system (1D list, e.g., [8,3])", "items": { "type": "number" }, "type": "array" }, "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." }, "method": { "default": "direct", "description": "Solution method: direct=exact (square systems), least_squares=overdetermined systems", "enum": [ "direct", "least_squares" ], "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": [ "coefficients", "constants" ], "type": "object" }

Implementation Reference

  • 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",

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