← Back to Tutorials
MCP Demo• 15 minutes

MCP Agent Demo: Solving Complex Optimization

See how AI agents use the Model Context Protocol to solve optimization problems they would otherwise struggle with.

The Challenge

Consider a complex portfolio optimization problem with multiple constraints:

Portfolio optimization problem
# Portfolio Optimization Challenge

You manage a $10M investment portfolio with 5 assets:
- Tech stocks (AAPL, MSFT, GOOGL)
- Bonds (AGG, BND)
- Real estate (VNQ)

Requirements:
1. Target return: 8% annually
2. Maximum risk (CVaR): 12%
3. No single position > 30%
4. Minimum position: 5%
5. Weights must sum to 100%

Historical data:
- Expected returns: [0.12, 0.08, 0.15, 0.04, 0.06]
- Covariance matrix: [complex 5x5 matrix]
- Risk-free rate: 2%

Why this is hard: This requires specialized knowledge of financial optimization, CVaR calculation, constraint handling, and choosing the right algorithm. An agent without domain expertise would struggle.

Agent Without MCP: The Struggle

An agent trying to solve this manually would face several challenges:

Agent struggling without MCP
# Agent trying to solve manually (struggling)

User: "Optimize my portfolio with the constraints above"

Agent (thinking): "I need to write optimization code. Let me try scipy..."

```python
from scipy.optimize import minimize
import numpy as np

# This is getting complex...
def portfolio_objective(weights):
    # Wait, how do I handle CVaR constraints?
    # I need to calculate CVaR but I'm not sure how...
    portfolio_return = np.dot(weights, expected_returns)
    portfolio_variance = np.dot(weights.T, np.dot(covariance, weights))
    return -portfolio_return / np.sqrt(portfolio_variance)  # Sharpe ratio?

# Constraints are tricky...
constraints = [
    {'type': 'eq', 'fun': lambda w: np.sum(w) - 1.0},
    # How do I enforce CVaR < 12%?
    # How do I handle min/max position limits?
]

# This might not work correctly...
result = minimize(portfolio_objective, x0, bounds=bounds, constraints=constraints)
```

Agent: "I'm having trouble with the CVaR constraint. 
The scipy optimizer doesn't directly support CVaR, and I'm 
not confident my implementation is correct. Also, I'm not 
sure which optimization algorithm to use for this problem..."
Uncertain about CVaR calculation methodology
Doesn't know which optimization algorithm to use
May implement constraints incorrectly
No way to validate if solution is correct

Agent With MCP: The Solution

The same agent, equipped with MCP tools, can solve this efficiently:

Agent succeeding with MCP
# Agent using MCP tools (successful)

User: "Optimize my portfolio with the constraints above"

Agent (via MCP): 
<tool_call>
{
  "tool": "analyze_optimization_problem",
  "arguments": {
    "objective_function": "portfolio_optimization_with_cvar",
    "bounds": [[0.05, 0.30], [0.05, 0.30], [0.05, 0.30], [0.05, 0.30], [0.05, 0.30]],
    "constraints": [
      "sum(weights) == 1.0",
      "target_return >= 0.08",
      "cvar <= 0.12",
      "min_position >= 0.05",
      "max_position <= 0.30"
    ],
    "domain": "financial"
  }
}
</tool_call>

<tool_result>
{
  "problem_type": "constrained_portfolio_optimization",
  "complexity": "high",
  "recommended_strategy": "cma_es_with_constraints",
  "estimated_evaluations": 2000,
  "constraint_handling": "penalty_method",
  "domain_specific_insights": {
    "risk_measure": "CVaR",
    "suitable_algorithms": ["CMA-ES", "Differential Evolution"],
    "common_pitfalls": ["CVaR calculation errors", "constraint violation"]
  }
}
</tool_result>

Agent: "The analysis suggests using CMA-ES with constraint handling. 
Let me optimize using the recommended approach."

<tool_call>
{
  "tool": "optimize_function",
  "arguments": {
    "objective_function": "def portfolio_objective(weights):
    # Calculate portfolio metrics
    portfolio_return = np.dot(weights, expected_returns)
    portfolio_variance = np.dot(weights.T, np.dot(covariance, weights))
    
    # Calculate CVaR (Conditional Value at Risk)
    portfolio_returns_sim = simulate_portfolio_returns(weights, 10000)
    cvar = calculate_cvar(portfolio_returns_sim, confidence=0.95)
    
    # Objective: maximize risk-adjusted return
    sharpe = (portfolio_return - risk_free_rate) / np.sqrt(portfolio_variance)
    
    # Penalty for constraint violations
    penalty = 0
    if np.abs(np.sum(weights) - 1.0) > 0.01:
        penalty += 1000
    if portfolio_return < 0.08:
        penalty += 100 * (0.08 - portfolio_return)
    if cvar > 0.12:
        penalty += 100 * (cvar - 0.12)
    
    return -sharpe + penalty",
    "bounds": [[0.05, 0.30], [0.05, 0.30], [0.05, 0.30], [0.05, 0.30], [0.05, 0.30]],
    "max_evaluations": 2000,
    "domain": "financial",
    "constraints": [
      "sum(weights) == 1.0",
      "target_return >= 0.08",
      "cvar <= 0.12"
    ]
  }
}
</tool_call>

<tool_result>
{
  "success": true,
  "best_parameters": [0.28, 0.22, 0.30, 0.10, 0.10],
  "best_fitness": 1.42,
  "evaluations": 1847,
  "convergence_iterations": 156,
  "explanation": {
    "natural_language": "Optimized portfolio allocation: 28% Tech Stock A, 22% Tech Stock B, 30% Tech Stock C (max), 10% Bonds A, 10% Bonds B. Achieves 8.3% expected return with 11.8% CVaR, satisfying all constraints. The optimizer favored Tech Stock C due to superior risk-adjusted return (Sharpe 1.42).",
    "strategy_used": "CMA-ES with adaptive constraint handling",
    "constraint_satisfaction": "all_constraints_satisfied",
    "risk_metrics": {
      "expected_return": 0.083,
      "cvar": 0.118,
      "sharpe_ratio": 1.42,
      "max_drawdown": 0.15
    }
  }
}
</tool_result>

Agent: "✅ Portfolio optimized successfully!

**Recommended Allocation:**
- Tech Stock A: 28%
- Tech Stock B: 22%  
- Tech Stock C: 30% (maximum allowed)
- Bonds A: 10%
- Bonds B: 10%

**Results:**
- Expected return: 8.3% (exceeds 8% target)
- CVaR: 11.8% (below 12% limit)
- Sharpe ratio: 1.42
- All constraints satisfied

The optimizer used CMA-ES with specialized constraint handling for financial problems, which is more reliable than generic optimization methods for portfolio problems."
Uses analyze_optimization_problem for expert guidance
Leverages domain-specific optimization strategies
Gets natural language explanations for results
Confident in solution correctness

Side-by-Side Comparison

AspectWithout MCPWith MCP
Problem AnalysisAgent guesses approach, may choose wrong algorithmAgent uses analyze_optimization_problem tool for expert recommendations
Constraint HandlingManual implementation, error-prone, especially for CVaRDomain-specific constraint handling built into tools
Algorithm SelectionTrial and error, may use suboptimal methodIntelligent strategy selection based on problem characteristics
Result InterpretationRaw numbers, agent must interpret manuallyNatural language explanations included in results
ReliabilityHigh risk of errors in complex financial calculationsBattle-tested optimization engine with domain expertise
Time to SolutionHours of debugging and iterationMinutes - direct tool calls with expert guidance

How to Integrate MCP

Here's how to connect your agent to the Sematryx MCP server:

MCP integration code
# Setting up MCP connection in your agent

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

# Connect to Sematryx MCP server
server_params = StdioServerParameters(
    command="python",
    args=["-m", "sematryx.platform_services.integrations.mcp.server"],
    env=None
)

async with stdio_client(server_params) as (read, write):
    async with ClientSession(read, write) as session:
        # Initialize the session
        await session.initialize()
        
        # List available tools
        tools = await session.list_tools()
        print("Available tools:", [t.name for t in tools.tools])
        
        # Call optimization tool
        result = await session.call_tool(
            "optimize_function",
            arguments={
                "objective_function": objective_code,
                "bounds": bounds,
                "domain": "financial",
                "max_evaluations": 2000
            }
        )
        
        print("Optimization result:", result.content)

Available MCP Tools

optimize_function

Optimize mathematical functions with intelligent strategy selection

analyze_optimization_problem

Get expert analysis and recommendations for your problem

get_optimization_strategies

List available optimization strategies and their characteristics

Key Takeaways

MCP enables domain expertise: Agents can access specialized optimization knowledge without implementing it themselves.
Reduces errors: Using battle-tested optimization engines eliminates bugs from manual implementation.
Faster solutions: Agents can solve complex problems in minutes instead of hours of debugging.
Better explanations: Natural language results help agents communicate solutions to users effectively.

Next Steps