Skip to main content
Glama
apetta

Vibe Math MCP

by apetta

solve_linear_system

Solve systems of linear equations (Ax = b) using SciPy's optimized solver for square or overdetermined systems.

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

TableJSON 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

Implementation Reference

  • Registration of the solve_linear_system tool using @mcp.tool decorator, including name, description with examples, and 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 linear system solver using NumPy/SciPy (la.solve for exact square systems, la.lstsq for least-squares overdetermined). Handles input validation, error cases (singular, dimension mismatch), formats output with metadata.
    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 schema definition via Annotated types and Field descriptions for input parameters: coefficients (matrix), constants (vector), method (direct/least_squares).
    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:
  • Categorizes solve_linear_system under 'Linear Algebra' tools for use in batch_execute tool discovery and documentation.
    TOOL_CATEGORIES = {
        "Basic": ["calculate", "percentage", "round", "convert_units"],
        "Arrays": ["array_operations", "array_statistics", "array_aggregate", "array_transform"],
        "Statistics": ["statistics", "pivot_table", "correlation"],
        "Financial": ["financial_calcs", "compound_interest", "perpetuity"],
        "Linear Algebra": ["matrix_operations", "solve_linear_system", "matrix_decomposition"],
        "Calculus": ["derivative", "integral", "limits_series"],
    }

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