Skip to main content
Glama

MCP Optimizer

🚀 Mathematical Optimization MCP Server with PuLP and OR-Tools support

Tests Coverage Python License

📖 Quick Links: 🚀 Quick Start | 🔧 macOS Troubleshooting | 📊 Examples | 🎯 Features

🚀 Quick Start

Most stable method with full functionality

# Run with STDIO transport (for MCP clients)
docker run --rm -i ghcr.io/dmitryanchikov/mcp-optimizer:latest

# Run with SSE transport (for remote clients)
docker run -d -p 8000:8000 -e TRANSPORT_MODE=sse \
  ghcr.io/dmitryanchikov/mcp-optimizer:latest

# Check SSE endpoint
curl -i http://localhost:8000/sse

2. 📦 pip + venv - Cross-platform

Standard approach

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # Linux/macOS
# or .venv\Scripts\activate  # Windows

# Install mcp-optimizer
pip install mcp-optimizer

# For SSE issues, use stable dependency versions:
# pip install "mcp-optimizer[stable]"

# Run (STDIO mode recommended)
mcp-optimizer --transport stdio

3. 🚀 uvx - Linux/Windows (full), macOS (partially)

# Linux/Windows - works out of the box
uvx mcp-optimizer

# macOS - requires Python 3.12
uvx --python python3.12 mcp-optimizer

# STDIO mode recommended
uvx mcp-optimizer --transport stdio

macOS users: If you encounter OR-Tools related errors, see 🔧 macOS uvx Troubleshooting section for automated fix scripts.

🍎 macOS Specifics

OR-Tools support:

  • uvx: PuLP only (limited functionality)

  • pip: full OR-Tools support

  • Docker: full OR-Tools support

For full OR-Tools support via pip:

# Install OR-Tools via Homebrew
brew install or-tools

# Then install mcp-optimizer
pip install "mcp-optimizer[stable]"

Transport Mode Recommendations

Installation Method

Recommended Transport

Why

Docker

SSE

Full stability

pip + venv

STDIO

Avoids dependency issues with newer versions

uvx

STDIO

Maximum compatibility

Integration with LLM Clients

Claude Desktop Integration

Option 1: Using Docker (Recommended)

  1. Install Claude Desktop from claude.ai

  2. Pull the Docker image:

docker pull ghcr.io/dmitryanchikov/mcp-optimizer:latest
  1. Add to your claude_desktop_config.json:

{
  "mcpServers": {
    "mcp-optimizer": {
      "command": "docker",
      "args": [
        "run", "--rm", "-i",
        "ghcr.io/dmitryanchikov/mcp-optimizer:latest",
        "python", "main.py"
      ]
    }
  }
}
  1. Restart Claude Desktop and look for the 🔨 tools icon

Option 2: Using pip + venv

# Create virtual environment and install
python -m venv .venv
source .venv/bin/activate  # Linux/macOS
pip install mcp-optimizer

Then add to your Claude Desktop config:

{
  "mcpServers": {
    "mcp-optimizer": {
      "command": "mcp-optimizer"
    }
  }
}

Option 3: Using uvx Add to your claude_desktop_config.json:

{
  "mcpServers": {
    "mcp-optimizer": {
      "command": "uvx",
      "args": ["mcp-optimizer"]
    }
  }
}

Note: On macOS, uvx provides limited functionality (PuLP solver only) or see 🔧 macOS uvx Troubleshooting

Advanced Docker Setup (for remote MCP clients)

# Run SSE server on port 8000 (uses environment variable)
docker run -d -p 8000:8000 -e TRANSPORT_MODE=sse \
  ghcr.io/dmitryanchikov/mcp-optimizer:latest

# Or with CLI argument and custom port
docker run -d -p 9000:9000 ghcr.io/dmitryanchikov/mcp-optimizer:latest \
  python -m mcp_optimizer.main --transport sse --host 0.0.0.0 --port 9000

# Check server status
docker logs <container-name>

# Verify SSE endpoint (should show event stream)
curl -i http://localhost:8000/sse

SSE Endpoint: http://localhost:8000/sse (Server-Sent Events for MCP communication)

Cursor Integration

  1. Install the MCP extension in Cursor

  2. Add mcp-optimizer to your workspace settings (Docker recommended):

{
  "mcp.servers": {
    "mcp-optimizer": {
      "command": "docker",
      "args": [
        "run", "--rm", "-i",
        "ghcr.io/dmitryanchikov/mcp-optimizer:latest",
        "python", "main.py"
      ]
    }
  }
}

Alternative configurations:

// Using pip installation
{
  "mcp.servers": {
    "mcp-optimizer": {
      "command": "mcp-optimizer"
    }
  }
}

// Using uvx (limited functionality on macOS)
{
  "mcp.servers": {
    "mcp-optimizer": {
      "command": "uvx",
      "args": ["mcp-optimizer"]
    }
  }
}

Other LLM Clients

For other MCP-compatible clients (Continue, Cody, etc.), use similar configuration patterns. Recommended priority:

  1. Docker (maximum stability across platforms)

  2. pip + venv (standard Python approach)

  3. uvx (quick testing, limited on macOS)

Advanced Installation Options

Local Development

# Clone the repository
git clone https://github.com/dmitryanchikov/mcp-optimizer.git
cd mcp-optimizer

# Install dependencies with uv
uv sync --extra dev

# Run the server
uv run python main.py

Local Package Build and Run

For testing and development, you can build the package locally and run it with uvx:

# Build the package locally
uv build

# Run with uvx from local wheel file
uvx --from ./dist/mcp_optimizer-0.3.9-py3-none-any.whl mcp-optimizer

# Or run with help to see available options
uvx --from ./dist/mcp_optimizer-0.3.9-py3-none-any.whl mcp-optimizer --help

# Test the local package with a simple MCP message
echo '{"jsonrpc": "2.0", "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test", "version": "1.0"}}, "id": 1}' | uvx --from ./dist/mcp_optimizer-0.3.9-py3-none-any.whl mcp-optimizer

Note: The local build creates both wheel (.whl) and source distribution (.tar.gz) files in the dist/ directory. The wheel file is recommended for uvx installation as it's faster and doesn't require compilation.

Docker with Custom Configuration

# Build locally with optimization
git clone https://github.com/dmitryanchikov/mcp-optimizer.git
cd mcp-optimizer
docker build -t mcp-optimizer:optimized .
docker run -p 8000:8000 mcp-optimizer:optimized

# Check optimized image size (398MB vs 1.03GB original - 61% reduction!)
docker images mcp-optimizer:optimized

# Test the optimized image
./scripts/test_docker_optimization.sh

Standalone Server Commands

# Run directly with uvx (no installation needed)
uvx mcp-optimizer

# Or run specific commands
uvx mcp-optimizer --help

# With pip installation
mcp-optimizer

# Or run with Python module (use main.py for stdio mode)
python main.py

Transport Modes

MCP Optimizer supports two MCP transport protocols:

  • STDIO: Standard input/output for direct MCP client integration (Claude Desktop, Cursor, etc.)

  • SSE: Server-Sent Events over HTTP for web-based MCP clients and remote integrations

STDIO Transport (Default - for MCP clients like Claude Desktop)

# Default STDIO mode for MCP protocol
uvx mcp-optimizer
# or
uvx mcp-optimizer --transport stdio
# or
uv run python -m mcp_optimizer.main --transport stdio
# or
python main.py

SSE Transport (for remote MCP clients)

# SSE mode for remote MCP clients (default port 8000)
uvx mcp-optimizer --transport sse
# or
uv run python -m mcp_optimizer.main --transport sse

# Custom host and port
uvx mcp-optimizer --transport sse --host 0.0.0.0 --port 9000
# or
uv run python -m mcp_optimizer.main --transport sse --host 0.0.0.0 --port 9000

# With debug mode
uvx mcp-optimizer --transport sse --debug --log-level DEBUG

Available CLI Options

# Show all available options
uvx mcp-optimizer --help

# Options:
#   --transport {stdio,sse}    MCP transport protocol (default: stdio)
#   --port PORT               Port for SSE transport (default: 8000)
#   --host HOST               Host for SSE transport (default: 127.0.0.1)
#   --debug                   Enable debug mode
#   --reload                  Enable auto-reload for development
#   --log-level {DEBUG,INFO,WARNING,ERROR}  Logging level (default: INFO)
#
# Environment Variables:
#   TRANSPORT_MODE={stdio,sse}  Override transport mode
#   SERVER_HOST=0.0.0.0        Override server host
#   SERVER_PORT=8000           Override server port

Related MCP server: Google OR-Tools server

🔧 Platform Compatibility & Troubleshooting

macOS Compatibility

✅ Full Functionality:

  • Homebrew + pip: brew install or-tools && pip install mcp-optimizer

  • Virtual environments: python -m venv venv && source venv/bin/activate && pip install ortools mcp-optimizer

  • Docker: Full OR-Tools support in containers

⚠️ Limited Functionality:

  • uvx (isolated environments): Only PuLP solver available due to OR-Tools native library paths

  • Fallback behavior: Automatically switches to PuLP when OR-Tools unavailable

Common Issues & Solutions:

  1. OR-Tools "Library not loaded" error:

    # Solution: Install via Homebrew
    brew install or-tools
    # Then use regular pip/venv instead of uvx
  2. uvx shows OR-Tools warnings:

    WARNING: OR-Tools not available: No module named 'ortools'

    This is expected - uvx provides fallback functionality with PuLP solver.

  3. Best practices for macOS:

    • Use Docker for production deployments

    • Use Homebrew + pip for development

    • Use uvx for quick testing (limited functionality)

Linux/Windows Compatibility

✅ Full Functionality:

  • uvx: Works out of the box with OR-Tools

  • pip: Standard installation

  • Docker: Recommended for production

Solver Availability by Platform

Platform

uvx

pip

Docker

macOS

PuLP only

✅ Full

✅ Full

Linux

✅ Full

✅ Full

✅ Full

Windows

✅ Full

✅ Full

✅ Full

Solver Features:

  • OR-Tools: Advanced algorithms (CP-SAT, routing, scheduling)

  • PuLP: Basic linear programming, reliable fallback

🔧 macOS uvx Troubleshooting

Problem: OR-Tools Library Issues with uvx

Common Error Messages:

Library not loaded: /Users/corentinl/work/stable/temp_python3.13/lib/libscip.9.2.dylib
ImportError: No module named 'ortools'
WARNING: OR-Tools not available

Root Cause: OR-Tools binary wheels contain hardcoded library paths that fail in uvx isolated environments. This is a macOS-specific issue due to how uvx isolates dependencies.

📊 Functionality Impact by Installation Method

✅ Available with uvx + fallback (PuLP solver only):

  • Linear Programming - Basic optimization, simplex method

  • Financial Optimization - Portfolio optimization, risk management

  • Production Planning - Resource allocation, inventory management

❌ Lost with uvx (requires OR-Tools):

  • Assignment Problems - Hungarian algorithm, transportation problems

  • Integer Programming - Mixed-integer, binary programming (SCIP/CBC)

  • Knapsack Problems - Discrete optimization, multiple variants

  • Vehicle Routing - TSP, CVRP, time windows (constraint programming)

  • Job Scheduling - CP-SAT solver, resource planning

🛠️ Solutions (in order of preference)

# Smart adaptive script - no hardcoded versions!
# Automatically detects your system libraries and Python versions
./scripts/fix_macos_uvx.sh

# Then uvx works with full functionality
uvx mcp-optimizer --transport stdio

2. Manual Fix

# Install system dependencies
brew install or-tools scip

# Create symlink for hardcoded path
sudo mkdir -p /Users/corentinl/work/stable/temp_python3.13/lib/
sudo ln -sf /opt/homebrew/lib/libscip.9.2.dylib /Users/corentinl/work/stable/temp_python3.13/lib/libscip.9.2.dylib

# Test fix
uvx mcp-optimizer --help

3. Use pip (Always Works)

# Install dependencies first
brew install or-tools

# Install package
pip install mcp-optimizer
mcp-optimizer

4. Use Docker (Production Ready)

docker run -p 8000:8000 mcp-optimizer

🎯 Features

Supported Optimization Problem Types:

  • Linear Programming - Maximize/minimize linear objective functions

  • Assignment Problems - Optimal resource allocation using Hungarian algorithm

  • Transportation Problems - Logistics and supply chain optimization

  • Knapsack Problems - Optimal item selection (0-1, bounded, unbounded)

  • Routing Problems - TSP and VRP with time windows

  • Scheduling Problems - Job and shift scheduling

  • Integer Programming - Discrete optimization problems

  • Financial Optimization - Portfolio optimization and risk management

  • Production Planning - Multi-period production planning

Testing

Automated Test Scripts

Quick Testing:

# Test local package build and functionality
./scripts/test_local_package.sh

# Test Docker container build and functionality  
./scripts/test_docker_container.sh

# Run comprehensive test suite (both package and Docker)
./scripts/test_all.sh

# Run only specific tests
./scripts/test_all.sh --skip-docker    # Skip Docker tests
./scripts/test_all.sh --skip-package   # Skip package tests

Manual Testing:

# Run simple functionality tests
uv run python tests/test_integration/comprehensive_test.py

# Run comprehensive integration tests
uv run python tests/test_integration/comprehensive_test.py

# Run all unit tests
uv run pytest tests/ -v

# Run with coverage
uv run pytest tests/ --cov=src/mcp_optimizer --cov-report=html

Test Scripts Features:

  • ✅ Local Package Testing: Build, STDIO/SSE modes, CLI functionality

  • ✅ Docker Container Testing: Image build, environment variables, health checks

  • ✅ Comprehensive Suite: Parallel execution with detailed reporting

  • ✅ Automatic Cleanup: Processes and containers cleaned up after tests

  • ✅ Cross-Platform: Works on macOS, Linux (requires Docker for container tests)

Requirements:

  • For local tests: uv, curl, lsof, gtimeout/timeout

  • For Docker tests: docker + local requirements

  • macOS: brew install coreutils (for gtimeout)

CI/CD Integration:

# GitHub Actions example
- name: Test Package
  run: ./scripts/test_local_package.sh
- name: Test Docker
  run: ./scripts/test_docker_container.sh

📊 Usage Examples

Linear Programming

from mcp_optimizer.tools.linear_programming import solve_linear_program

# Maximize 3x + 2y subject to:
# x + y <= 4
# 2x + y <= 6
# x, y >= 0

objective = {"sense": "maximize", "coefficients": {"x": 3, "y": 2}}
variables = {
    "x": {"type": "continuous", "lower": 0},
    "y": {"type": "continuous", "lower": 0}
}
constraints = [
    {"expression": {"x": 1, "y": 1}, "operator": "<=", "rhs": 4},
    {"expression": {"x": 2, "y": 1}, "operator": "<=", "rhs": 6}
]

result = solve_linear_program(objective, variables, constraints)
# Result: x=2.0, y=2.0, objective=10.0

Assignment Problem

from mcp_optimizer.tools.assignment import solve_assignment_problem

workers = ["Alice", "Bob", "Charlie"]
tasks = ["Task1", "Task2", "Task3"]
costs = [
    [4, 1, 3],  # Alice's costs for each task
    [2, 0, 5],  # Bob's costs for each task
    [3, 2, 2]   # Charlie's costs for each task
]

result = solve_assignment_problem(workers, tasks, costs)
# Result: Total cost = 5.0 with optimal assignments

Knapsack Problem

from mcp_optimizer.tools.knapsack import solve_knapsack_problem

items = [
    {"name": "Item1", "weight": 10, "value": 60},
    {"name": "Item2", "weight": 20, "value": 100},
    {"name": "Item3", "weight": 30, "value": 120}
]

result = solve_knapsack_problem(items, capacity=50)
# Result: Total value = 220.0 with optimal item selection

Portfolio Optimization

from mcp_optimizer.tools.financial import optimize_portfolio

assets = [
    {"name": "Stock A", "expected_return": 0.12, "risk": 0.18},
    {"name": "Stock B", "expected_return": 0.10, "risk": 0.15},
    {"name": "Bond C", "expected_return": 0.06, "risk": 0.08}
]

result = optimize_portfolio(
    assets=assets,
    objective="minimize_risk",
    budget=10000,
    risk_tolerance=0.15
)
# Result: Optimal portfolio allocation with minimized risk

🏗️ Architecture

mcp-optimizer/
├── LICENSE                     # MIT License
├── README.md                   # Project documentation
├── CHANGELOG.md               # Release notes
├── CONTRIBUTING.md            # Contribution guidelines
├── pyproject.toml             # Python project configuration
├── uv.lock                    # Dependency lock file
├── main.py                    # Entry point
├── Dockerfile                 # Main Docker configuration
├── docker-compose.yml         # Multi-service setup
├── .dockerignore             # Docker ignore rules
├── .gitignore                # Git ignore rules
├── .python-version           # Python version specification
├── src/mcp_optimizer/        # Main source code
│   ├── __init__.py
│   ├── __main__.py           # Module entry point
│   ├── main.py               # Application entry point
│   ├── mcp_server.py         # MCP server implementation
│   ├── config.py             # Configuration management
│   ├── tools/                # 9 categories of optimization tools
│   │   ├── linear_programming.py
│   │   ├── assignment.py
│   │   ├── knapsack.py
│   │   ├── routing.py
│   │   ├── scheduling.py
│   │   ├── financial.py
│   │   └── production.py
│   ├── solvers/              # PuLP and OR-Tools integration
│   │   ├── pulp_solver.py
│   │   └── ortools_solver.py
│   ├── schemas/              # Pydantic validation schemas
│   └── utils/                # Utility functions
├── tests/                    # Comprehensive test suite
│   ├── test_tools/           # Tool-specific tests
│   ├── test_solvers/         # Solver tests
│   └── test_integration/     # Integration tests
├── scripts/                  # Automation scripts
├── examples/                 # Usage examples and prompts
│   ├── en/                   # English examples
│   └── ru/                   # Russian examples
├── k8s/                      # Kubernetes deployment manifests
└── monitoring/               # Grafana/Prometheus setup
    └── grafana/
        └── datasources/

🧪 Test Results

✅ Comprehensive Test Suite

🧪 Starting Comprehensive MCP Optimizer Tests
==================================================
✅ Server Health PASSED
✅ Linear Programming PASSED
✅ Assignment Problems PASSED  
✅ Knapsack Problems PASSED
✅ Routing Problems PASSED
✅ Scheduling Problems PASSED
✅ Financial Optimization PASSED
✅ Production Planning PASSED
✅ Performance Test PASSED

📊 Test Results: 9 passed, 0 failed
🎉 All tests passed! MCP Optimizer is ready for production!

✅ Unit Tests

  • 66 tests passed, 9 skipped

  • Execution time: 0.45 seconds

  • All core components functional

📈 Performance Metrics

  • Linear Programming: ~0.01s

  • Assignment Problems: ~0.01s

  • Knapsack Problems: ~0.01s

  • Complex test suite: 0.02s for 3 optimization problems

  • Overall performance: 🚀 Excellent!

🔧 Technical Details

Core Solvers

  • OR-Tools: For assignment, transportation, knapsack problems

  • PuLP: For linear/integer programming

  • FastMCP: For MCP server integration

Supported Solvers

  • CBC, GLPK, GUROBI, CPLEX (via PuLP)

  • SCIP, CP-SAT (via OR-Tools)

Key Features

  • ✅ Full MCP protocol integration

  • ✅ Comprehensive input validation

  • ✅ Robust error handling

  • ✅ High-performance optimization

  • ✅ Production-ready architecture

  • ✅ Extensive test coverage

  • ✅ Docker and Kubernetes support

📋 Requirements

  • Python 3.11+

  • uv (for dependency management)

  • OR-Tools (automatically installed)

  • PuLP (automatically installed)

🚀 Production Deployment

Docker

# Build image
docker build -t mcp-optimizer .

# Run container
docker run -p 8000:8000 mcp-optimizer

Kubernetes

# Deploy to Kubernetes
kubectl apply -f k8s/

Monitoring

# Start monitoring stack
docker-compose up -d

🎯 Project Status

✅ PRODUCTION READY 🚀

  • All core optimization tools implemented and tested

  • MCP server fully functional

  • Comprehensive test coverage (66 unit tests + 9 integration tests)

  • OR-Tools integration confirmed working

  • Performance optimized (< 30s for complex test suites)

  • Ready for production deployment

📖 Usage Examples

The examples/ directory contains practical examples and prompts for using MCP Optimizer with Large Language Models (LLMs):

Available Examples

  • 📊 Linear Programming (RU | EN)

    • Production optimization, diet planning, transportation, blending problems

  • 👥 Assignment Problems (RU | EN)

    • Employee-project assignment, machine-order allocation, task distribution

  • 💰 Portfolio Optimization (RU | EN)

    • Investment portfolios, retirement planning, risk management

How to Use Examples

  1. For LLM Integration: Copy the prompt text and provide it to your LLM with MCP Optimizer access

  2. For Direct API Usage: Use the provided API structures directly with MCP Optimizer functions

  3. For Learning: Understand different optimization problem types and formulations

Each example includes:

  • Problem descriptions and real-world scenarios

  • Ready-to-use prompts for LLMs

  • Technical API structures

  • Common activation phrases

  • Practical applications

🔄 Recent Updates

Latest Release Features:

  1. Function Exports - Added exportable functions to all tool modules:

    • solve_linear_program() in linear_programming.py

    • solve_assignment_problem() in assignment.py

    • solve_knapsack_problem() in knapsack.py

    • optimize_portfolio() in financial.py

    • optimize_production() in production.py

  2. Enhanced Testing - Updated comprehensive test suite with correct function signatures

  3. OR-Tools Integration - Confirmed full functionality of all OR-Tools components

🚀 Fully Automated Release Process

New Simplified Git Flow (3 steps!)

The project uses a fully automated release process:

1. Create Release Branch

# For minor release (auto-increment)
uv run python scripts/release.py --type minor

# For specific version
uv run python scripts/release.py 0.2.0

# For hotfix
uv run python scripts/release.py --hotfix --type patch

# Preview changes
uv run python scripts/release.py --type minor --dry-run

2. Create PR to main

# Create PR: release/v0.3.0 → main
gh pr create --base main --head release/v0.3.0 --title "Release v0.3.0"

3. Merge PR - DONE! 🎉

After PR merge, automatically happens:

  • ✅ Create tag v0.3.0

  • ✅ Publish to PyPI

  • ✅ Publish Docker images

  • ✅ Create GitHub Release

  • ✅ Merge main back to develop

  • ✅ Cleanup release branch

NO NEED to run manual_finalize_release.py manually anymore!

🔒 Secure Detection: Uses hybrid approach combining GitHub branch protection with automated release detection. See Release Process for details.

Automated Release Pipeline

The CI/CD pipeline automatically handles:

  • ✅ Release Candidates: Built from release/* branches

  • ✅ Production Releases: Triggered by version tags on main

  • ✅ PyPI Publishing: Automatic on tag creation

  • ✅ Docker Images: Multi-architecture builds

  • ✅ GitHub Releases: With artifacts and release notes

CI/CD Pipeline

The GitHub Actions workflow automatically:

  • ✅ Runs tests on Python 3.11 and 3.12

  • ✅ Performs security scanning

  • ✅ Builds and pushes Docker images

  • ✅ Publishes to PyPI on tag creation

  • ✅ Creates GitHub releases

Requirements for PyPI Publication

  • Set PYPI_API_TOKEN secret in GitHub repository

  • Ensure all tests pass

  • Follow semantic versioning

🛠️ Development Tools

Debug Tools

Use the debug script to inspect MCP server structure:

# Run debug tools to check server structure
uv run python scripts/debug_tools.py

# This will show:
# - Available MCP tools
# - Tool types and attributes
# - Server configuration

Comprehensive Testing

Run the full integration test suite:

# Run comprehensive tests
uv run python tests/test_integration/comprehensive_test.py

# This tests:
# - All optimization tools (9 categories)
# - Server health and functionality
# - Performance benchmarks
# - End-to-end workflows

Docker Build Instructions

Image Details

  • Base: Python 3.12 Slim (Debian-based)

  • Size: ~649MB (optimized with multi-stage builds)

  • Architecture: Multi-platform support (x86_64, ARM64)

  • Security: Non-root user, minimal dependencies

  • Performance: Optimized Python bytecode, cleaned build artifacts

Local Build Commands

# Standard build
docker build -t mcp-optimizer:latest .

# Build with development dependencies
docker build --build-arg ENV=development -t mcp-optimizer:dev .

# Build with cache mount for faster rebuilds
docker build --mount=type=cache,target=/build/.uv -t mcp-optimizer .

# Check image size
docker images mcp-optimizer

# Run container
docker run -p 8000:8000 mcp-optimizer:latest

# For development with volume mounting
docker run -p 8000:8000 -v $(pwd):/app mcp-optimizer:latest

# Test container functionality
docker run --rm mcp-optimizer:latest python -c "from mcp_optimizer.mcp_server import create_mcp_server; print('✅ MCP Optimizer works!')"

🤝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Git Flow Policy

This project follows a standard Git Flow workflow:

  • Feature branches → develop branch

  • Release branches → main branch

  • Hotfix branches → main and develop branches

📚 Documentation:

Development Setup

# Clone and setup
git clone https://github.com/dmitryanchikov/mcp-optimizer.git
cd mcp-optimizer

# Create feature branch from develop
git checkout develop
git checkout -b feature/your-feature-name

# Install dependencies
uv sync --extra dev

# Run tests
uv run pytest tests/ -v

# Run linting
uv run ruff check src/
uv run mypy src/

# Create PR to develop branch (not main!)

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • OR-Tools - Google's optimization tools

  • PuLP - Linear programming in Python

  • FastMCP - Fast MCP server implementation

📞 Support


Made with ❤️ for the optimization community

📊 Docker Image Size Analysis

The MCP Optimizer Docker image has been optimized to balance functionality and size:

Component

Size

% of Total

Description

Python packages (/venv)

237.0 MB

42.8%

Virtual environment with dependencies

System libraries (/usr)

173.2 MB

31.3%

Base Debian system + Python

Other

137.4 MB

24.8%

Base image, filesystem

Configuration (/var, /etc)

6.2 MB

1.1%

System settings

Application code (/code)

0.2 MB

0.04%

MCP Optimizer source code

Key Dependencies by Size

  • OR-Tools: 75.0 MB (27.8% of venv) - Critical optimization solver (requires pandas + numpy)

  • pandas: 45.0 MB (16.7% of venv) - Required by OR-Tools for data operations

  • NumPy: 24.0 MB (8.9% of venv) - Required by OR-Tools for numerical computing

  • PuLP: 34.9 MB (12.9% of venv) - Linear programming solver

  • FastMCP: 15.2 MB (5.6% of venv) - MCP server framework

  • Pydantic: 12.8 MB (4.7% of venv) - Data validation

Dependencies Analysis

  • Core packages cannot be reduced further: OR-Tools (our main optimization engine) requires both pandas and numpy as mandatory dependencies

  • Optional examples moved: Additional packages for examples (streamlit, plotly) moved to [examples] extra

  • Minimal core impact: Moving examples to optional dependencies only affects development/demo usage

Image Optimization

  • Current optimized size: ~420MB

  • Core functionality: Includes all necessary dependencies for production optimization

  • Example support: Install with [examples] extra for additional demo functionality

  • OR-Tools constraint: Cannot remove pandas/numpy due to hard dependency requirements

Available Tools

13 tools
optimize_portfolio_toolA

Optimize portfolio allocation to maximize return or minimize risk.

    Args:
        assets: List of asset dictionaries with expected return, risk, and sector
        objective: Optimization objective ("maximize_return", "minimize_risk", "maximize_sharpe", "risk_parity")
        budget: Total budget to allocate (default: 1.0)
        risk_tolerance: Maximum acceptable portfolio risk (optional)
        sector_constraints: Maximum allocation per sector (optional)
        min_allocation: Minimum allocation per asset (default: 0.0)
        max_allocation: Maximum allocation per asset (default: 1.0)
        solver_name: Solver to use ("CBC", "GLPK", "GUROBI", "CPLEX")
        time_limit_seconds: Maximum solving time in seconds (default: 30.0)

    Returns:
        Optimization result with optimal portfolio allocation
    

Inputs: assets (required), objective, budget, risk_tolerance, +5 more.

optimize_production_plan_toolA

Optimize multi-period production planning to maximize profit or minimize costs.

    Args:
        products: List of product dictionaries with costs and resource requirements
        resources: List of resource dictionaries with capacity constraints
        periods: Number of planning periods
        demand: List of demand requirements per product per period
        objective: Optimization objective ("maximize_profit", "minimize_cost", "minimize_time")
        inventory_costs: Optional inventory holding costs per product
        setup_costs: Optional setup costs per product
        solver_name: Solver to use ("CBC", "GLPK", "GUROBI", "CPLEX")
        time_limit_seconds: Maximum solving time in seconds (default: 30.0)

    Returns:
        Optimization result with optimal production plan
    

Inputs: products (required), resources (required), periods (required), demand (required), +5 more.

solve_assignment_problem_toolA
    Solve assignment problem using OR-Tools Hungarian algorithm.

    Args:
        workers: List of worker names
        tasks: List of task names
        costs: 2D cost matrix where costs[i][j] is cost of assigning worker i to task j
        maximize: Whether to maximize instead of minimize (default: False)
        max_tasks_per_worker: Maximum tasks per worker (optional)
        min_tasks_per_worker: Minimum tasks per worker (optional)

    Returns:
        Dictionary with solution status, assignments, total cost, and execution time
    

Inputs: workers (required), tasks (required), costs (required), maximize, +2 more.

solve_employee_shift_schedulingB

Solve Employee Shift Scheduling to assign employees to shifts optimally.

    Args:
        employees: List of employee names
        shifts: List of shift dictionaries with time and requirements
        days: Number of days to schedule
        employee_constraints: Optional constraints and preferences per employee
        time_limit_seconds: Maximum solving time in seconds (default: 30.0)

    Returns:
        Optimization result with employee schedules and coverage statistics
    

Inputs: employees (required), shifts (required), days (required), employee_constraints, +1 more.

solve_integer_program_toolA

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}
            ]
        )
    

Inputs: objective (required), variables (required), constraints (required), solver, +1 more.

solve_job_shop_schedulingB

Solve Job Shop Scheduling Problem to optimize machine utilization and completion times.

    Args:
        jobs: List of job dictionaries with tasks and constraints
        machines: List of available machine names
        horizon: Maximum time horizon for scheduling
        objective: Optimization objective ("makespan" or "total_completion_time")
        time_limit_seconds: Maximum solving time in seconds (default: 30.0)

    Returns:
        Optimization result with job schedule and machine assignments
    

Inputs: jobs (required), machines (required), horizon (required), objective, +1 more.

solve_knapsack_problem_toolA

Solve knapsack optimization problems using OR-Tools.

    This tool solves knapsack problems where items need to be selected
    to maximize value while staying within capacity constraints.

    Use cases:
    - Cargo loading: Optimize loading of trucks, ships, or planes by weight and volume
    - Portfolio selection: Choose optimal set of investments within budget constraints
    - Resource allocation: Select projects or activities with limited budget or resources
    - Advertising planning: Choose optimal mix of advertising channels within budget
    - Menu planning: Select dishes for a restaurant menu considering costs and popularity
    - Inventory optimization: Decide which products to stock in limited warehouse space

    Args:
        items: List of items, each with 'name', 'value', 'weight', and optionally 'volume', 'quantity'
        capacity: Weight capacity constraint
        volume_capacity: Volume capacity constraint (optional)
        knapsack_type: Type of knapsack problem ('0-1', 'bounded', 'unbounded')
        max_items_per_type: Maximum items per type for bounded knapsack

    Returns:
        Knapsack result with total value and selected items

    Example:
        # Select items to maximize value within weight limit
        solve_knapsack_problem(
            items=[
                {"name": "Item1", "value": 10, "weight": 5, "volume": 2},
                {"name": "Item2", "value": 15, "weight": 8, "volume": 3},
                {"name": "Item3", "value": 8, "weight": 3, "volume": 1}
            ],
            capacity=10,
            volume_capacity=5
        )
    

Inputs: items (required), capacity (required), volume_capacity, knapsack_type, +1 more.

solve_linear_program_toolA

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}
            ]
        )
    

Inputs: objective (required), variables (required), constraints (required), solver, +1 more.

solve_mixed_integer_programB

Solve Mixed-Integer Programming (MIP) problems with integer, binary, and continuous variables.

    Args:
        variables: List of variable definitions with bounds and types
        constraints: List of constraint definitions with coefficients and bounds
        objective: Objective function definition with coefficients and direction
        solver_name: Solver to use ("SCIP", "CBC", "GUROBI", "CPLEX")
        time_limit_seconds: Maximum solving time in seconds (default: 30.0)

    Returns:
        Optimization result with optimal variable values and objective
    

Inputs: variables (required), constraints (required), objective (required), solver_name, +1 more.

solve_transportation_problem_toolB
    Solve transportation problem using OR-Tools.

    Args:
        suppliers: List of supplier dictionaries with 'name' and 'supply' keys
        consumers: List of consumer dictionaries with 'name' and 'demand' keys
        costs: 2D cost matrix where costs[i][j] is cost of shipping from supplier i to consumer j

    Returns:
        Dictionary with solution status, flows, total cost, and execution time
    

Inputs: suppliers (required), consumers (required), costs (required).

solve_traveling_salesman_problemB

Solve Traveling Salesman Problem (TSP) to find the shortest route visiting all locations.

    Args:
        locations: List of location dictionaries with name and coordinates
        distance_matrix: Optional pre-calculated distance matrix
        start_location: Index of starting location (default: 0)
        return_to_start: Whether to return to starting location (default: True)
        time_limit_seconds: Maximum solving time in seconds (default: 30.0)

    Returns:
        Optimization result with route and total distance
    

Inputs: locations (required), distance_matrix, start_location, return_to_start, +1 more.

solve_vehicle_routing_problemB

Solve Vehicle Routing Problem (VRP) to optimize routes for multiple vehicles.

    Args:
        locations: List of location dictionaries with name, coordinates, and demand
        vehicles: List of vehicle dictionaries with capacity constraints
        distance_matrix: Optional pre-calculated distance matrix
        time_matrix: Optional pre-calculated time matrix
        depot: Index of depot location (default: 0)
        time_limit_seconds: Maximum solving time in seconds (default: 30.0)

    Returns:
        Optimization result with routes for all vehicles
    

Inputs: locations (required), vehicles (required), distance_matrix, time_matrix, +2 more.

validate_optimization_inputC

Validate input data for optimization problems.

    Args:
        problem_type: Type of optimization problem
        input_data: Input data to validate

    Returns:
        Validation result with errors, warnings, and suggestions
    

Inputs: problem_type (required), input_data (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.4/5.0

    Scored across 13 tools

    Disambiguation3/5

    The three general solvers (linear, integer, mixed integer) overlap significantly since linear programming can also handle integer and binary variables, and mixed integer is essentially a superset of integer. The specialized problem solvers (assignment, transportation, knapsack, etc.) are distinct but could be modeled via the general tools, creating potential confusion. Descriptions help but boundaries are fuzzy.

    Naming Consistency3/5

    Most tools follow a 'solve_*_problem_tool' pattern, but several lack the '_tool' suffix (e.g., solve_mixed_integer_program, solve_traveling_salesman_problem) and one is 'validate_optimization_input' without 'solve' prefix. This inconsistency, while readable, violates a predictable verb_noun pattern.

    Tool Count5/5

    13 tools is well within the ideal 3-15 range. Each tool serves a specific optimization domain, and the count feels appropriate for a server dedicated to mathematical optimization without being overwhelming or sparse.

    Completeness4/5

    The server covers a wide range of classic optimization problems: LP, IP, MIP, assignment, transportation, knapsack, TSP, VRP, job shop, shift scheduling, portfolio, and production planning. Minor gaps exist, such as a generic constraint satisfaction tool or nonlinear optimization, but for the stated purpose the coverage is quite comprehensive.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      A Model Context Protocol (MCP) server that exposes MiniZinc constraint solving capabilities to Large Language Models.
      6
      187
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      MCP-ORTools integrates Google's OR-Tools constraint programming solver with Large Language Models through the MCP, enabling AI models to: Submit and validate constraint models Set model parameters Solve constraint satisfaction and optimization problems Retrieve and analyze solution
      22
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables solving Constraint Satisfaction Problems (CSP) like N-Queens, graph coloring, and Sudoku, as well as Linear Programming optimization problems through both MCP tools and HTTP API endpoints.
      2
      MIT
    • A
      license
      Not graded
      quality
      Not graded
      maintenance
      An MCP server that enables Large Language Models to interactively create, edit, and solve constraint models using backends like MiniZinc, Z3, PySAT, and Clingo. It bridges natural language with symbolic reasoning for solving complex logical, SAT, SMT, and optimization problems.
      MIT