优化MCP
Claude Code的高级优化工具-9个用于生产的专用求解器
 ](<>)
版本:2.5.0(所有4个增强功能均已完成) 状态:生产准备就绪(9个工具+1个编排技能)
______________________________________________________________________
快速启动(60秒)
想马上试试吗?以下是最快的路径:
1.安装依赖项(10秒)
git clone https://github.com/your-org/optimization-mcp
cd optimization-mcp
pip install -r requirements.txt2.测试它是否有效(10秒)
# test_basic.py
from src.api.allocation import optimize_allocation
result = optimize_allocation(
objective={
"sense": "maximize",
"items": [
{"name": "project_a", "value": 100},
{"name": "project_b", "value": 150}
]
},
resources={"budget": {"total": 10000}},
item_requirements=[
{"name": "project_a", "budget": 6000},
{"name": "project_b", "budget": 5000}
]
)
print(f"Status: {result['status']}")
print(f"Optimal value: {result['objective_value']}")
print(f"Allocation: {result['allocation']}")运行: python test_basic.py
预期输出:
Status: optimal
Optimal value: 250.0
Allocation: {'project_a': 1, 'project_b': 1}3.在克劳德代码中使用(30秒)
添加到 ~/.claude.json:
{
"mcpServers": {
"optimization-mcp": {
"command": "python",
"args": ["/path/to/optimization-mcp/server.py"]
}
}
}重新启动Claude Code,然后尝试:
Claude, use optimization-mcp to allocate a $100K budget across 3 marketing channels4.下一步(10秒)
______________________________________________________________________
概述
优化MCP提供基于约束的优化功能,可与现有的蒙特卡洛MCP无缝集成。找到最佳的资源分配,跨场景的稳健解决方案,并在不确定性下做出数据驱动的决策。
主要特点
- 深度MC集成:每个工具都有自己的蒙特卡洛意识——使用百分位值、预期结果或完整的场景分布
- 生产解决方案:PuLP(LP/MILP)、SciPy(非线性)、CVXPY(二次型)、NetworkX(网络流)
- 高性能:NetworkX为物流/路线问题提供10-100x的加速(1K-10K变量)
- 零摩擦工作流程:优化输出直接输入蒙特卡洛验证工具
- 开源:不需要商业许可证(不需要Gurobi/CPLEX)
- 生产就绪:内部测试,全面的错误处理,有用的诊断
- 全面覆盖:网络流、帕累托边界、随机规划、列生成
帕累托前沿可视化
多目标优化平衡冲突目标(利润与可持续性):
*此可视化演示了帕累托前沿工具如何探索竞争目标之间的权衡,帮助您在多个最优解决方案中做出战略决策。*
______________________________________________________________________
安装
通过插件市场(推荐)
# Add marketplace
claude plugin marketplace add eesb99/optimization-mcp
# Install plugin
claude plugin install optimization-mcp
# Verify installation
/mcp
# Should show: ✔ optimization-mcp (connected, 9 tools)手动安装
# Clone repository
git clone https://github.com/eesb99/optimization-mcp.git ~/.claude/mcp-servers/optimization-mcp
# Run setup
cd ~/.claude/mcp-servers/optimization-mcp
./setup.sh
# Add to ~/.claude.json
{
"mcpServers": {
"optimization-mcp": {
"command": "/Users/[username]/.claude/mcp-servers/optimization-mcp/run.sh"
}
}
}
# Restart Claude Code自动设置:The setup.sh 脚本会自动创建一个虚拟环境并安装所有依赖项。
______________________________________________________________________
重要免责声明
软件保修
本软件根据MIT许可证“按原样”提供,不提供任何明示或暗示的保证。作者对使用本软件造成的任何损害不承担责任。在实施之前,始终验证优化结果。
商业决策通知
优化结果是基于输入数据和假设的数学模型。虽然算法经过严格测试,但现实世界的决策需要:
- 与领域专家一起验证结果
- 关键参数敏感性分析
- 部署前使用历史数据进行测试
- 了解模型限制和假设
财务建议免责声明
投资组合优化工具仅用于教育和分析目的。它不构成财务、投资或专业建议。在做出投资决策之前,咨询合格的财务顾问。过去的性能和模型输出不能保证未来的结果。
准确性和验证
所有优化工具都经过全面的内部测试和验证,但用户应该:
- 独立验证关键应用程序的结果
- 生产使用前对已知问题进行测试
- 验证假设和输入数据质量
- 仔细查看求解器状态和警告
- 考虑多种情景和敏感性分析
推荐:从非关键应用程序开始,彻底验证,然后扩展到生产使用。
______________________________________________________________________
工具
1. optimize_allocation
目的:资源分配受到限制(预算、时间、能力)
用例:
- 跨渠道营销预算
- 各产品的生产能力
- 资源有限的项目选择
- 饮料/食品的成分配方
示例:
result = optimize_allocation(
objective={
"items": [
{"name": "google_ads", "value": 125000}, # Expected ROI
{"name": "linkedin", "value": 87000}
],
"sense": "maximize"
},
resources={
"budget": {"total": 100000}
},
item_requirements=[
{"name": "google_ads", "budget": 25000},
{"name": "linkedin", "budget": 18000}
]
)
# Output:
# {
# "status": "optimal",
# "objective_value": 212000.0,
# "allocation": {"google_ads": 1, "linkedin": 1, ...},
# "resource_usage": {...},
# "shadow_prices": {"budget": 1.25}, # Worth $1.25 per extra $1
# "monte_carlo_compatible": {...} # Ready for MC validation
# }蒙特卡罗积分:
# Use P50 (median) values from Monte Carlo simulation
result = optimize_allocation(
objective={...},
resources={...},
item_requirements=[...],
monte_carlo_integration={
"mode": "percentile",
"percentile": "p50",
"mc_output": mc_simulation_result
}
)参数:
objective:骰子items(列表)和sense(“最大化”/“最小化”)resources:资源限制(例如。,{"budget": {"total": 100000}})item_requirements:每个项目所需资源的字典列表constraints:可选的附加约束monte_carlo_integration:可选MC集成(3种模式:百分位数、预期、场景)solver_options:可选(time_limit,verbose)
退货:
status:“最优”、“不可行”、“无界”或“错误”objective_value:最佳值allocation:所选项目的骰子(1=已选,0=未选)resource_usage:每种资源的利用率统计数据shadow_prices:放宽每个约束的边际值monte_carlo_compatible:输出格式化以进行MC验证
多目标优化
v1.1.0中的新功能:通过加权标量化优化多个竞争目标。
用例:
- 平衡利润和可持续性
- 权衡回报与风险
- 同时优化成本和质量
- 任何多准则决策问题
示例:
result = optimize_allocation(
objective={
"sense": "maximize",
"functions": [
{
"name": "profit",
"items": [
{"name": "product_a", "value": 100},
{"name": "product_b", "value": 150}
],
"weight": 0.7 # 70% weight on profit
},
{
"name": "sustainability",
"items": [
{"name": "product_a", "value": 80},
{"name": "product_b", "value": 60}
],
"weight": 0.3 # 30% weight on sustainability
}
]
},
resources={
"budget": {"total": 50000}
},
item_requirements=[
{"name": "product_a", "budget": 25000},
{"name": "product_b", "budget": 30000}
]
)
# Output includes objective breakdown:
# {
# "status": "optimal",
# "objective_value": 127.0, # 0.7*140 + 0.3*70
# "allocation": {"product_a": 1, "product_b": 0},
# "objective_breakdown": {
# "profit": {
# "value": 100,
# "weight": 0.7,
# "weighted_value": 70.0
# },
# "sustainability": {
# "value": 80,
# "weight": 0.3,
# "weighted_value": 24.0
# }
# }
# }需求:
- 至少需要2个目标函数
- 权重总和必须为1.0(在0.01公差范围内)
- 每个权重必须介于0和1之间
- 每个函数都有自己的
items列表与name和value
向后兼容:单目标格式仍然和以前一样。
增强约束
v2.0.0中的新功能:用于复杂决策逻辑的高级约束类型。
约束类型:
1.有条件的(If Then):
constraints=[
{
"type": "conditional",
"condition_item": "project_a",
"then_item": "project_b",
"description": "if_a_then_b"
}
]
# If project_a is selected, then project_b MUST be selected2.非连接(OR-至少N):
constraints=[
{
"type": "disjunctive",
"items": ["option_a", "option_b", "option_c"],
"min_selected": 2,
"description": "pick_at_least_2"
}
]
# At least 2 of the 3 options must be selected3.相互排他性(确切地说是N):
constraints=[
{
"type": "mutex",
"items": ["strategy_a", "strategy_b", "strategy_c"],
"exactly": 1,
"description": "pick_exactly_one"
}
]
# Exactly 1 strategy must be selected (XOR logic)组合示例:
# Complex business logic: Pick one core product + conditionally required addons
result = optimize_allocation(
objective={...},
resources={...},
item_requirements=[...],
constraints=[
{"type": "mutex", "items": ["core_a", "core_b"], "exactly": 1},
{"type": "conditional", "condition_item": "core_a", "then_item": "addon_1"},
{"type": "disjunctive", "items": ["addon_1", "addon_2"], "min_selected": 1}
]
)用例:
- 产品捆绑规则
- 技术依赖链
- 战略选择
- 监管合规约束
______________________________________________________________________
2. optimize_robust
目的:找到在蒙特卡洛场景中运行良好的稳健解决方案
用例:
- 在85%以上的场景中有效的分配
- 最坏情况优化
- 风险约束决策
示例:
# Step 1: Run Monte Carlo to generate scenarios
mc_result = run_business_scenario(
scenario_name="Product Launch",
revenue_assumptions={...},
cost_structure={...},
num_simulations=10000
)
# Step 2: Find robust allocation
result = optimize_robust(
objective={
"items": [{"name": "project_a"}, {"name": "project_b"}],
"sense": "maximize"
},
resources={"budget": {"total": 100000}},
item_requirements=[...],
monte_carlo_scenarios={
"scenarios": mc_result["scenarios"] # All 10K scenarios
},
robustness_criterion="best_average",
risk_tolerance=0.85 # Works in 85% of scenarios
)
# Output:
# {
# "allocation": {...},
# "robustness_metrics": {
# "expected_outcome": 125000,
# "worst_case_outcome": 95000,
# "scenarios_meeting_threshold": 0.92, # 92% of scenarios succeed
# "outcome_percentiles": {"p10": 98000, "p50": 125000, "p90": 152000}
# },
# "outcome_distribution": [...] # Outcome in each scenario
# }参数:
objective,resources,item_requirements:与optimize_allocation相同monte_carlo_scenarios:骰子scenariosMC输出列表robustness_criterion:“最佳平均值”、“最差情况”或“百分位数”risk_tolerance:浮点数(0-1),例如0.85=在85%的情况下有效constraints,solver_options:可选
退货:
allocation:稳健的分配决策robustness_metrics:跨场景的性能统计outcome_distribution:验证结果列表monte_carlo_compatible:MC工具的输出
______________________________________________________________________
3. optimize_portfolio
v2.0.0中的新功能:使用二次规划进行风险回报权衡的投资组合优化。
目的:考虑相关性和风险,优化投资组合配置
用例:
- 投资组合配置
- 风险回报权衡的资产选择
- 夏普比率最大化
- 高效的边境建设
优化目标:
- 夏普比率:最大化(回报-无风险)/风险
- 最小方差:将投资组合风险降至最低,实现目标回报
- 最大回报:最大化目标风险的回报
示例1:夏普比率优化:
result = optimize_portfolio(
assets=[
{"name": "US_equity", "expected_return": 0.10},
{"name": "intl_equity", "expected_return": 0.09},
{"name": "bonds", "expected_return": 0.04}
],
covariance_matrix=[
[0.0225, 0.0100, 0.0020], # US equity: 15% std, correlations
[0.0100, 0.0256, 0.0015], # Intl equity: 16% std
[0.0020, 0.0015, 0.0036] # Bonds: 6% std
],
optimization_objective="sharpe",
risk_free_rate=0.025,
constraints={
"max_weight": 0.70, # Max 70% in any asset
"min_weight": 0.10 # Min 10% in each
}
)
# Output:
# {
# "status": "optimal",
# "weights": {"US_equity": 0.70, "intl_equity": 0.20, "bonds": 0.10},
# "expected_return": 0.092, # 9.2% expected return
# "portfolio_std": 0.1234, # 12.34% risk (std dev)
# "sharpe_ratio": 0.543, # (9.2% - 2.5%) / 12.34%
# "assets": [
# {
# "name": "US_equity",
# "weight": 0.70,
# "risk_contribution_pct": 165.1 # Contributes 165% of risk (due to correlations)
# },
# ...
# ]
# }示例2:最小方差:
# Find lowest-risk portfolio that achieves 6% return
result = optimize_portfolio(
assets=[...],
covariance_matrix=[...],
constraints={"target_return": 0.06},
optimization_objective="min_variance"
)
# Returns portfolio with minimum variance achieving 6% return示例3:最大回报:
# Find highest-return portfolio within risk budget
result = optimize_portfolio(
assets=[...],
covariance_matrix=[...],
constraints={"target_risk": 0.03}, # Max variance = 3%
optimization_objective="max_return"
)
# Returns portfolio with maximum return within risk limit参数:
assets:列表{"name": str, "expected_return": float}covariance_matrix:资产回报协方差的N×N矩阵optimization_objective:"sharpe","min_variance",或"max_return"risk_free_rate:夏普的无风险利率(默认值:0.02)constraints:可选:
- max_weight:每项资产的最大权重(例如,0.30=30%) - min_weight:每项资产的最小权重(例如,0.05=5%) - target_return:必需 min_variance 目标 - target_risk:必需 max_return 目标 - long_only:防止卖空(默认值:True)
monte_carlo_integration:可选MC集成solver_options:可选求解器设置
退货:
status:优化状态weights:最佳投资组合权重的骰子(总和为1.0)expected_return:投资组合预期回报portfolio_variance:投资组合差异(风险²)portfolio_std:投资组合标准差(风险)sharpe_ratio:(返回-rf)/stdassets:资产层面的详细信息,包括风险贡献monte_carlo_compatible:MC验证输出
求解器:带SCS的CVXPY(处理二次目标和约束)
______________________________________________________________________
4. optimize_schedule
v2.0.0中的新功能:具有依赖关系和资源约束的任务调度。
目的:考虑任务依赖性、资源限制和时间限制,优化项目进度
用例:
- 项目进度安排(RCPSP)
- 车间作业调度
- 任务优先级与截止日期
- 随时间推移的资源分配
优化目标:
- 最小化Makespan:尽快完成项目
- 最大化价值:在时间预算内优先处理高价值任务
示例1:软件项目进度表:
result = optimize_schedule(
tasks=[
{"name": "design", "duration": 5, "value": 100, "dependencies": [], "resources": {"developers": 2}},
{"name": "backend", "duration": 10, "value": 200, "dependencies": ["design"], "resources": {"developers": 3}},
{"name": "frontend", "duration": 8, "value": 150, "dependencies": ["design"], "resources": {"developers": 2}},
{"name": "testing", "duration": 4, "value": 80, "dependencies": ["backend", "frontend"], "resources": {"developers": 2}}
],
resources={"developers": {"total": 5}},
time_horizon=30,
optimization_objective="minimize_makespan"
)
# Output:
# {
# "status": "optimal",
# "makespan": 19, # Project finishes at time 19
# "schedule": {"design": 0, "backend": 5, "frontend": 5, "testing": 15},
# "critical_path": ["design", "backend", "testing"], # Tasks determining makespan
# "resource_usage": {...}, # Developer utilization over time
# "tasks": [
# {"name": "design", "start_time": 0, "end_time": 5, "on_critical_path": true},
# ...
# ]
# }示例2:有截止日期:
result = optimize_schedule(
tasks=[...],
resources={...},
time_horizon=30,
constraints=[
{"type": "deadline", "task": "testing", "time": 20}, # Must finish by time 20
{"type": "parallel_limit", "limit": 3} # Max 3 tasks in parallel
]
)参数:
tasks:任务列表,包括:
- name:任务标识符 - duration:所需时间单位 - value:任务值/优先级(可选,用于最大值) - dependencies:必备任务名称列表(可选) - resources:每个时间单位的资源需求(可选)
resources:每个时间段的可用资源time_horizon:总调度窗口constraints:可选的时间约束:
- 截止日期:任务必须在时间T前完成 - 发布:任务不能在时间T之前开始 - 并行限制:最多可同时执行N个任务
optimization_objective:"minimize_makespan"或"maximize_value"monte_carlo_integration:不确定持续时间的可选MCsolver_options:可选求解器设置
退货:
status:优化状态schedule:骰子映射任务→ 开始时间makespan:项目完成时间(尽量减少工作量)total_value:计划任务值的总和(最大值)resource_usage:资源利用时间表critical_path:任务顺序决定完成时间tasks:带有关键路径标记的任务级详细信息monte_carlo_compatible:MC验证输出
求解器:带CBC的PuLP(任务时间分配的MILP)
______________________________________________________________________
5. optimize_execute
v2.1.0中的新功能:具有自动求解器选择和灵活问题规范的自定义优化。
目的:用于快速原型制作和定制优化问题的高级用户工具
用例:
- 自定义优化配方不符合标准模板
- 新优化问题的快速原型制作
- 当你知道数学形式并想要自动选择求解器时
- 教育/研究应用
主要特点:
- 自动求解器选择:自动检测并选择最佳求解器(PuLP/SciPy/CVXPY)
- 灵活的规格:基于骰子的问题定义
- 所有求解器均可访问:可以覆盖自动检测以强制特定求解器
示例1:简单背包问题:
result = optimize_execute(
problem_definition={
"variables": [
{"name": "item1", "type": "binary"},
{"name": "item2", "type": "binary"},
{"name": "item3", "type": "binary"}
],
"objective": {
"coefficients": {"item1": 60, "item2": 100, "item3": 120},
"sense": "maximize"
},
"constraints": [
# Weight: 10*item1 + 20*item2 + 30*item3 ="|"==", "rhs": number}`
- `auto_detect`:自动选择最佳解算器(默认值:True)
- `solver_preference`:用覆盖 `"pulp"`, `"scipy"`,或 `"cvxpy"`
- `monte_carlo_integration`:可选MC集成
- `solver_options`:可选(`time_limit`, `verbose`)
**退货**:
- `status`:优化状态
- `solver_used`:选择了哪个求解器
- `objective_value`:最佳值
- `solution`:变量值骰子
- `solve_time_seconds`:求解时间
- `problem_info`:问题统计
- `shadow_prices` 或 `dual_values`:灵敏度信息(取决于求解器)
- `monte_carlo_compatible`:MC验证输出
**自动检测逻辑**:
- 具有二进制/整数变量→ PuLP(加拿大广播公司)
- 连续线性→ PuLP(默认)
- 可以用以下方式覆盖 `solver_preference` 参数
**何时使用**:
- ✅ 您遇到自定义问题,无法安装标准模板
- ✅ 您希望使用dict规范快速制作原型
- ✅ 您需要从一个界面访问所有3个求解器
- ✅ 你对数学公式很熟悉
**何时不使用**:
- ❌ 标准分配→ 改用optimize_allocation
- ❌ 投资组合→ 改用optimize_portfolio
- ❌ 调度→ 改用optimize_schedule
**求解器**:自动选择(PuLP/SciPy/CVXPY)或手动超控
#### 为什么optimize_excute是你的“逃生舱”
**灵活性层**:虽然专用工具覆盖了90%的用例, `optimize_execute` 是专门为另外10%设计的。
**当专用工具合适时** (先使用这些):
- 预算分配→ `optimize_allocation`
- 投资组合→ `optimize_portfolio`
- 调度→ `optimize_schedule`
- 网络路由→ `optimize_network_flow`
- 多目标权衡→ `optimize_pareto`
**当您需要定制配方时** (使用optimize_excute):
- 定制背包变体
- 异常约束类型
- 新问题的快速原型制作
- 教育/研究应用
- 是否存在不符合标准模板的问题
**把它当作**:
- **专用工具** =高级API(简单、固执己见,90%的病例)
- **优化执行** =低级API(灵活、一般、10%的病例)
**示例-自定义多维背包**:
Specialized tools don't support this exact variant
Use optimize_execute for full flexibility
result = optimize_execute( problem_definition={ "variables": [ {"name": f"item_{i}", "type": "binary"} for i in range(100) ], "objective": { "coefficients": {f"item_{i}": values[i] for i in range(100)}, "sense": "maximize" }, "constraints": [ # Weight constraint {"coefficients": {f"item_{i}": weights[i] for i in range(100)}, "type": "1000个变量)的框架
- 性能取决于用户提供的定价子问题
- 当前返回带有初始列(占位符定价)
何时使用:非常大的问题,削减库存,人员安排(需要定制定价)
______________________________________________________________________
优化执行
建议限值:
- 变量:取决于自动检测的求解器
- PuLP(LP/MIP):\ 0` (产生流量)
- 水槽:
demand > 0(消耗流量) - 转运:既没有供应也没有需求(传递流量)
______________________________________________________________________
求解器选项
用于:所有工具
格式:
{
"time_limit": number, # Optional: Max solve time (seconds)
"verbose": boolean # Optional: Enable debug output
}示例:
solver_options = {
"time_limit": 30, # Stop after 30 seconds
"verbose": True # Print solver progress
}用法:
result = optimize_allocation(
objective={...},
resources={...},
item_requirements=[...],
solver_options={"time_limit": 60, "verbose": False}
)______________________________________________________________________
规范工作流程
工作流程1:优化→ 验证→ 稳健性检验
找到最优分配,用蒙特卡洛验证,测试假设的稳健性。
User: "Allocate $100K marketing budget with uncertain ROI"
Step 1: Optimize allocation
result = optimize_allocation(
objective={...},
resources={"budget": {"total": 100000}},
item_requirements=[...]
)
Step 2: Validate confidence (uses MC-compatible output)
confidence = validate_reasoning_confidence(
decision_context="Q1 marketing allocation",
assumptions=result["monte_carlo_compatible"]["assumptions"],
success_criteria=result["monte_carlo_compatible"]["recommended_params"]["success_criteria"]
)
# Returns: 87% chance of achieving >90% of optimal value
Step 3: Test robustness
robustness = test_assumption_robustness(
base_answer=f"Allocate {result['allocation']}",
critical_assumptions=result["monte_carlo_compatible"]["assumptions"],
stress_test_ranges={...}
)
# Returns: Breaks if Google Ads ROI 2.0x ROI
- Risk: Breaks if SEO conversion =0.9.0-模型上下文协议
- **浆** >=2.7.0-线性/整数规划
- **SciPy** >=1.16.0-科学计算
- **数值Python** >=2.3.0-数值数组
- **pytest** >=7.0.0-测试框架
______________________________________________________________________
## 许可证
Claude Code MCP生态系统的一部分。负责任地使用。
______________________________________________________________________
## 支持
- **问题**:报告Claude代码设置中的问题
- **文档**:请参阅计划文件 `~/.claude/plans/resilient-frolicking-wreath.md`
- **例子**:检查 `examples/` 完整工作流目录
______________________________________________________________________
**第1周状态**: ✓ 配备2个核心工具的生产就绪
下一篇:第2周-投资组合优化和调度工具