Skip to main content
Glama

solve_integer_program_tool

Solve optimization problems with integer or binary variables for discrete decision-making like facility location, crew scheduling, and project selection using linear programming.

Instructions

Solve an integer or mixed-integer programming problem using PuLP.

    This tool solves optimization problems where some or all variables must
    take integer values, which is useful for discrete decision problems.

    Use cases:
    - Facility location: Decide where to build warehouses or service centers
    - Project selection: Choose which projects to fund (binary decisions)
    - Crew scheduling: Assign integer numbers of staff to shifts
    - Network design: Design networks with discrete components
    - Cutting stock: Minimize waste when cutting materials
    - Capital budgeting: Select investments when partial investments aren't allowed

    Args:
        objective: Objective function with 'sense' and 'coefficients'
        variables: Variable definitions with types "continuous", "integer", or "binary"
        constraints: List of linear constraints
        solver: Solver to use ("CBC", "GLPK", "GUROBI", "CPLEX")
        time_limit_seconds: Maximum time to spend solving (optional)

    Returns:
        Optimization result with integer/binary variable values

    Example:
        # Binary knapsack: select items to maximize value within weight limit
        solve_integer_program(
            objective={"sense": "maximize", "coefficients": {"item1": 10, "item2": 15}},
            variables={
                "item1": {"type": "binary"},
                "item2": {"type": "binary"}
            },
            constraints=[
                {"expression": {"item1": 5, "item2": 8}, "operator": "<=", "rhs": 10}
            ]
        )
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
objectiveYes
variablesYes
constraintsYes
solverNoCBC
time_limit_secondsNo

Implementation Reference

  • The MCP tool handler function 'solve_integer_program_tool' decorated with @mcp.tool(). It wraps the solve_integer_program helper function to execute the integer programming optimization.
    @mcp.tool()
    def solve_integer_program_tool(
        objective: dict[str, Any],
        variables: dict[str, dict[str, Any]],
        constraints: list[dict[str, Any]],
        solver: str = "CBC",
        time_limit_seconds: float | None = None,
    ) -> dict[str, Any]:
        """Solve an integer or mixed-integer programming problem using PuLP.
    
        This tool solves optimization problems where some or all variables must
        take integer values, which is useful for discrete decision problems.
    
        Use cases:
        - Facility location: Decide where to build warehouses or service centers
        - Project selection: Choose which projects to fund (binary decisions)
        - Crew scheduling: Assign integer numbers of staff to shifts
        - Network design: Design networks with discrete components
        - Cutting stock: Minimize waste when cutting materials
        - Capital budgeting: Select investments when partial investments aren't allowed
    
        Args:
            objective: Objective function with 'sense' and 'coefficients'
            variables: Variable definitions with types "continuous", "integer", or "binary"
            constraints: List of linear constraints
            solver: Solver to use ("CBC", "GLPK", "GUROBI", "CPLEX")
            time_limit_seconds: Maximum time to spend solving (optional)
    
        Returns:
            Optimization result with integer/binary variable values
    
        Example:
            # Binary knapsack: select items to maximize value within weight limit
            solve_integer_program(
                objective={"sense": "maximize", "coefficients": {"item1": 10, "item2": 15}},
                variables={
                    "item1": {"type": "binary"},
                    "item2": {"type": "binary"}
                },
                constraints=[
                    {"expression": {"item1": 5, "item2": 8}, "operator": "<=", "rhs": 10}
                ]
            )
        """
        result = solve_integer_program(
            objective, variables, constraints, solver, time_limit_seconds
        )
        result_dict: dict[str, Any] = result
        return result_dict
  • Core helper function that parses the raw input dictionaries using Pydantic models (Objective, Variable, Constraint) and solves the integer program using PuLPSolver.
    @with_resource_limits(timeout_seconds=60.0, estimated_memory_mb=100.0)
    def solve_integer_program(
        objective: dict[str, Any],
        variables: dict[str, dict[str, Any]],
        constraints: list[dict[str, Any]],
        solver: str = "CBC",
        time_limit_seconds: float | None = None,
    ) -> dict[str, Any]:
        """Solve an integer programming problem using PuLP."""
        try:
            # Parse and validate input
            obj = Objective(**objective)
            vars_dict = {name: Variable(**var_def) for name, var_def in variables.items()}
            constraints_list = [Constraint(**constraint) for constraint in constraints]
    
            # Create and solve problem with integer variables
            pulp_solver = PuLPSolver(solver)
            result = pulp_solver.solve_linear_program(
                objective=obj,
                variables=vars_dict,
                constraints=constraints_list,
                time_limit=time_limit_seconds,
            )
    
            return result
    
        except Exception as e:
            logger.error(f"Integer programming error: {e}")
            return {
                "status": "error",
                "error_message": f"Failed to solve integer program: {str(e)}",
                "objective_value": None,
                "variables": {},
                "execution_time": 0.0,
                "solver_info": {},
            }
  • Function that defines and registers the solve_integer_program_tool (and solve_linear_program_tool) using the @mcp.tool() decorator on the MCP instance.
    def register_linear_programming_tools(mcp: FastMCP[Any]) -> None:
        """Register linear programming tools with the MCP server."""
    
        @mcp.tool()
        def solve_linear_program_tool(
            objective: dict[str, Any],
            variables: dict[str, dict[str, Any]],
            constraints: list[dict[str, Any]],
            solver: str = "CBC",
            time_limit_seconds: float | None = None,
        ) -> dict[str, Any]:
            """Solve a linear programming problem using PuLP.
    
            This tool solves general linear programming problems where you want to
            optimize a linear objective function subject to linear constraints.
    
            Use cases:
            - Resource allocation: Distribute limited resources optimally
            - Diet planning: Create nutritionally balanced meal plans within budget
            - Manufacturing mix: Determine optimal product mix to maximize profit
            - Investment planning: Allocate capital across different investment options
            - Supply chain optimization: Minimize transportation and storage costs
            - Energy optimization: Optimize power generation and distribution
    
            Args:
                objective: Objective function with 'sense' ("minimize" or "maximize")
                          and 'coefficients' (dict mapping variable names to coefficients)
                variables: Variable definitions mapping variable names to their properties
                          (type: "continuous"/"integer"/"binary", lower: bound, upper: bound)
                constraints: List of constraints, each with 'expression' (coefficients),
                            'operator' ("<=", ">=", "=="), and 'rhs' (right-hand side value)
                solver: Solver to use ("CBC", "GLPK", "GUROBI", "CPLEX")
                time_limit_seconds: Maximum time to spend solving (optional)
    
            Returns:
                Optimization result with status, objective value, variable values, and solver info
    
            Example:
                # Maximize 3x + 2y subject to 2x + y <= 20, x + 3y <= 30, x,y >= 0
                solve_linear_program(
                    objective={"sense": "maximize", "coefficients": {"x": 3, "y": 2}},
                    variables={
                        "x": {"type": "continuous", "lower": 0},
                        "y": {"type": "continuous", "lower": 0}
                    },
                    constraints=[
                        {"expression": {"x": 2, "y": 1}, "operator": "<=", "rhs": 20},
                        {"expression": {"x": 1, "y": 3}, "operator": "<=", "rhs": 30}
                    ]
                )
            """
            result = solve_linear_program(objective, variables, constraints, solver, time_limit_seconds)
            result_dict: dict[str, Any] = result
            return result_dict
    
        @mcp.tool()
        def solve_integer_program_tool(
            objective: dict[str, Any],
            variables: dict[str, dict[str, Any]],
            constraints: list[dict[str, Any]],
            solver: str = "CBC",
            time_limit_seconds: float | None = None,
        ) -> dict[str, Any]:
            """Solve an integer or mixed-integer programming problem using PuLP.
    
            This tool solves optimization problems where some or all variables must
            take integer values, which is useful for discrete decision problems.
    
            Use cases:
            - Facility location: Decide where to build warehouses or service centers
            - Project selection: Choose which projects to fund (binary decisions)
            - Crew scheduling: Assign integer numbers of staff to shifts
            - Network design: Design networks with discrete components
            - Cutting stock: Minimize waste when cutting materials
            - Capital budgeting: Select investments when partial investments aren't allowed
    
            Args:
                objective: Objective function with 'sense' and 'coefficients'
                variables: Variable definitions with types "continuous", "integer", or "binary"
                constraints: List of linear constraints
                solver: Solver to use ("CBC", "GLPK", "GUROBI", "CPLEX")
                time_limit_seconds: Maximum time to spend solving (optional)
    
            Returns:
                Optimization result with integer/binary variable values
    
            Example:
                # Binary knapsack: select items to maximize value within weight limit
                solve_integer_program(
                    objective={"sense": "maximize", "coefficients": {"item1": 10, "item2": 15}},
                    variables={
                        "item1": {"type": "binary"},
                        "item2": {"type": "binary"}
                    },
                    constraints=[
                        {"expression": {"item1": 5, "item2": 8}, "operator": "<=", "rhs": 10}
                    ]
                )
            """
            result = solve_integer_program(
                objective, variables, constraints, solver, time_limit_seconds
            )
            result_dict: dict[str, Any] = result
            return result_dict
    
        logger.info("Registered linear programming tools")
  • Invocation of register_linear_programming_tools(mcp) inside create_mcp_server(), which triggers the tool registration for solve_integer_program_tool.
    register_linear_programming_tools(mcp)
  • Server creation function that orchestrates all tool registrations, including the linear programming tools containing solve_integer_program_tool.
    def create_mcp_server() -> FastMCP[dict[str, str]]:
        """Create and configure the MCP server with optimization tools."""
    
        # Create MCP server
        mcp: FastMCP[dict[str, str]] = FastMCP("MCP Optimizer")
    
        # Register all optimization tools
        register_linear_programming_tools(mcp)
        register_integer_programming_tools(mcp)
        register_assignment_tools(mcp)
        register_knapsack_tools(mcp)
        register_routing_tools(mcp)
        register_scheduling_tools(mcp)
        register_financial_tools(mcp)
        register_production_tools(mcp)
        register_validation_tools(mcp)
    
        # Health check resource
        @mcp.resource("resource://health")
        def health_resource() -> dict[str, Any]:
            """Get server health status and resource information."""
            return get_health()
    
        # Resource monitoring endpoints
        @mcp.resource("resource://resource-stats")
        def resource_stats_resource() -> dict[str, Any]:
            """Get detailed resource usage statistics."""
            return get_resource_stats()
    
        @mcp.resource("resource://resource-reset")
        def resource_reset_resource() -> dict[str, str]:
            """Reset resource monitoring statistics."""
            return reset_resource_statistics()
    
        # Server info resource
        @mcp.resource("resource://server-info")
        def server_info_resource() -> dict[str, Any]:
            """Get comprehensive server information."""
            return get_server_info()
    
        logger.info("MCP Optimizer server created and configured")
        logger.info(
            f"Configuration: max_solve_time={settings.max_solve_time}s, "
            f"max_memory={settings.max_memory_mb}MB, "
            f"max_concurrent={settings.max_concurrent_requests}"
        )
    
        return mcp
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden. It discloses the tool uses PuLP and mentions optional time limits, but doesn't cover important behavioral aspects like computational complexity, memory usage, error handling, or what happens when no solution is found. The description states it 'solves' problems but doesn't clarify if it returns approximate solutions for difficult problems.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections: purpose statement, use cases, parameters, returns, and example. While comprehensive, it could be more front-loaded - the core functionality is clear in the first paragraph, but the detailed parameter explanations and example add necessary value for this complex tool.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a complex tool with 5 parameters, nested objects, no annotations, and no output schema, the description provides good parameter semantics and use cases. However, it lacks information about return format details, error conditions, performance characteristics, and doesn't fully compensate for the missing output schema. The example helps but doesn't replace proper behavioral documentation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage and 5 parameters (3 required), the description provides excellent parameter documentation. It clearly explains each parameter's purpose: objective function with sense and coefficients, variable definitions with specific types, constraints as linear constraints, solver options with four named choices, and optional time limit. The example further clarifies parameter usage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool 'solves optimization problems where some or all variables must take integer values' using PuLP, specifying both the action (solve) and resource (integer/mixed-integer programming problems). It distinguishes itself from siblings like solve_linear_program_tool by explicitly mentioning integer constraints, and from solve_mixed_integer_program by mentioning both integer and mixed-integer cases.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context through six specific use cases (facility location, project selection, etc.) that illustrate when to use this tool for discrete decision problems. However, it doesn't explicitly state when NOT to use it or name specific alternatives among the many sibling tools, though the integer focus implicitly distinguishes it from continuous optimization tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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/dmitryanchikov/mcp-optimizer'

If you have feedback or need assistance with the MCP directory API, please join our Discord server