# Mcportfolio

> McPortfolio: A Model Context Protocol server providing 9 specialized tools for LLM-driven portfolio optimization using natural language, covering mean-variance to machine learning approaches.

- **Type:** MCP server
- **Install:** `agentstack add mcp-ebrandler-mcportfolio`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [ebrandler](https://agentstack.voostack.com/s/ebrandler)
- **Installs:** 0
- **Category:** [AI & ML](https://agentstack.voostack.com/c/ai-and-ml)
- **Latest version:** 0.1.0
- **License:** Apache-2.0
- **Upstream author:** [ebrandler](https://github.com/ebrandler)
- **Source:** https://github.com/ebrandler/mcportfolio

## Install

```sh
agentstack add mcp-ebrandler-mcportfolio
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

```
// Modified by Edward Brandler, based on original files from PyPortfolioOpt and USolver
```

#  McPortfolio - LLM-Driven Portfolio Optimization

This project allows users to work with advanced portfolio optimization using natural language, without writing code. It provides **9 specialized MCP tools** covering everything from classic mean-variance optimization to modern machine learning approaches like Hierarchical Risk Parity.

**Overview of Portfolio Optimizers:**

Portfolio optimizers are algorithms and mathematical tools designed to help investors allocate their capital among different assets in a way that balances risk and return. The most common approaches include:

- **Mean-Variance Optimization (Markowitz):** Finds the portfolio with the lowest risk for a given expected return, or the highest return for a given risk, based on historical means and covariances.
- **Maximum Sharpe Ratio:** Seeks the portfolio with the best risk-adjusted return, maximizing the Sharpe ratio.
- **Minimum Volatility:** Focuses on constructing the portfolio with the lowest possible volatility.
- **Efficient Frontier:** The set of optimal portfolios that offer the highest expected return for a defined level of risk.
- **Black-Litterman Model:** Combines market equilibrium with investor views to produce more stable and realistic portfolios.
- **Hierarchical Risk Parity (HRP):** Uses clustering algorithms to build diversified portfolios that are robust to estimation errors.
- **Mean-CVaR and Mean-Semivariance:** Alternative risk measures that focus on downside risk or tail risk, rather than standard deviation.

These optimizers allow users to tailor their portfolios to their specific risk tolerance, investment goals, and market views.

It gives a universal solver interface for Model-Constraint-Problem (MCP). It makes the [PyPortfolioOpt](https://pyportfolioopt.readthedocs.io/en/latest/) library's features available to Large Language Models (LLMs) through an MCP Server. The main goal is to let .

This project builds on the open-source [USolver](https://github.com/sdiehl/usolver) project, which gives a Model Context Protocol server with tools for different optimization problems. Through USolver, this project works with this powerful solver:

*   [`cvxpy`](https://www.cvxpy.org/) - Used for convex optimization problems in portfolio theory, like maximizing Sharpe ratio or minimizing volatility with linear and quadratic constraints.

## Important Points for LLM-Driven Optimization

The LLM's ability to pick the right solver, parameters, and variables for an optimization problem is a judgment call. It is affected by the non-deterministic nature of LLMs.

**Users should check both the LLM's assumptions and the output.**

### How to Check:
*   **Review the LLM's prompt and generated code/parameters**: Before running, look at the input the LLM is making for the MCP server.
*   **Check server logs**: The MCP server gives detailed logs of operations and parameters used. Review these logs to make sure they match your goals.
*   **Compare with PyPortfolioOpt documentation**: If you know PyPortfolioOpt, check the LLM's chosen parameters and objectives against the library's official docs.
*   **Look at the output metrics**: Check the expected annual return, annual volatility, Sharpe ratio, and other performance metrics to make sure they make sense for your problem.

## Claude Project Instructions

Best practise is to run McPortfolio in a Claude Project. This allows you to set project knowledge, which will improve performance.

There's presently (2025-06-09) no way to force Claude to use a specific tool via MCP Server. So to nudge Claude in the right direction, you can explicitly tell it which tool to use. But even then, you may face issues.

So to help Claude better understand the tools' purposes and how to use them, copy and paste the contents of docs/Claude_Project_Instructions.md to your Claude project's knowledge section. Queries then run from within the project will run more smoothly.

The instructions help Claude to:
- Find when a request fits McPortfolio's features
- Make proper requests using the standard JSON format
- Check outputs against financial best practices
- Give clear explanations of its optimization choices

## An overview of classical portfolio optimization methods

*Reproduced and adapted from [PyPortfolioOpt by robertmartin8](https://github.com/robertmartin8/PyPortfolioOpt?tab=readme-ov-file#an-overview-of-classical-portfolio-optimization-methods)*

Harry Markowitz's 1952 paper is the undeniable classic, which turned portfolio optimization from an art into a science. The key insight is that by combining assets with different expected returns and volatilities, one can decide on a mathematically optimal allocation which minimises the risk for a target return – the set of all such optimal portfolios is referred to as the efficient frontier.

Although much development has been made in the subject, more than half a century later, Markowitz's core ideas are still fundamentally important and see daily use in many portfolio management firms. The main drawback of mean-variance optimization is that the theoretical treatment requires knowledge of the expected returns and the future risk-characteristics (covariance) of the assets. Obviously, if we knew the expected returns of a stock life would be much easier, but the whole game is that stock returns are notoriously hard to forecast. As a substitute, we can derive estimates of the expected return and covariance based on historical data – though we do lose the theoretical guarantees provided by Markowitz, the closer our estimates are to the real values, the better our portfolio will be.

Thus this project provides four major sets of functionality (though of course they are intimately related):

- Estimates of expected returns
- Estimates of risk (i.e covariance of asset returns)
- Objective functions to be optimized
- Optimizers

A key design goal of PyPortfolioOpt is modularity – the user should be able to swap in their components while still making use of the framework that PyPortfolioOpt provides.

## Available MCP Tools

McPortfolio provides a comprehensive suite of portfolio optimization tools through the Model Context Protocol (MCP) server. Each tool is designed for specific optimization scenarios and can be used independently or in combination.

### Core Tools

#### 1. `retrieve_stock_data`
Retrieves historical stock market data for analysis.

**Parameters:**
- `tickers`: List of stock symbols (e.g., ["AAPL", "MSFT", "GOOGL"])
- `period`: Time period for data (e.g., "1y", "2y", "5y")

**Use Case:** Data collection for any portfolio optimization analysis.

#### 2. `solve_portfolio`
General-purpose portfolio optimization with flexible constraints and objectives.

**Parameters:**
- `description`: Problem description
- `tickers`: List of stock symbols
- `constraints`: List of constraint strings (e.g., ["max_weight 0.3", "min_weight 0.05"])
- `objective`: Optimization objective ("minimize_volatility", "maximize_sharpe_ratio", etc.)

**Use Case:** Most common portfolio optimization scenarios with custom constraints.

### Specialized Optimization Methods

#### 3. `solve_efficient_frontier`
Classic Markowitz mean-variance optimization for maximum Sharpe ratio portfolios.

**Parameters:**
- `description`: Problem description
- `tickers`: List of stock symbols
- `min_weight`: Minimum weight per asset (default: 0.0)
- `max_weight`: Maximum weight per asset (default: 1.0)
- `risk_free_rate`: Risk-free rate for Sharpe calculation (default: 0.0)

**Use Case:** Traditional mean-variance optimization, ideal for well-diversified portfolios.

#### 4. `solve_cla`
Critical Line Algorithm for efficient frontier computation.

**Parameters:**
- `description`: Problem description
- `tickers`: List of stock symbols
- `min_weight`: Minimum weight per asset (default: 0.0)
- `max_weight`: Maximum weight per asset (default: 1.0)
- `risk_free_rate`: Risk-free rate for Sharpe calculation (default: 0.0)

**Use Case:** Efficient computation of the entire efficient frontier, useful for risk-return analysis.

#### 5. `solve_hierarchical_portfolio`
Hierarchical Risk Parity (HRP) optimization using machine learning clustering.

**Parameters:**
- `description`: Problem description
- `tickers`: List of stock symbols
- `min_weight`: Minimum weight per asset (default: 0.0)
- `max_weight`: Maximum weight per asset (default: 1.0)
- `risk_free_rate`: Risk-free rate for Sharpe calculation (default: 0.0)

**Use Case:** Modern portfolio construction that addresses estimation errors in traditional optimization.

#### 6. `solve_black_litterman`
Black-Litterman model combining market equilibrium with investor views.

**Parameters:**
- `description`: Problem description
- `tickers`: List of stock symbols
- `views`: List of investor views with expected returns and confidence levels
- `risk_aversion`: Risk aversion parameter (default: 1.0)
- `tau`: Scaling factor for uncertainty (default: 0.05)

**Use Case:** Incorporating market views and expert opinions into portfolio optimization.

### Utility Tools

#### 7. `solve_discrete_allocation`
Converts portfolio weights to actual share quantities for implementation.

**Parameters:**
- `description`: Problem description
- `tickers`: List of stock symbols
- `weights`: Dictionary of target weights (e.g., {"AAPL": 0.4, "MSFT": 0.6})
- `portfolio_value`: Total portfolio value in dollars

**Use Case:** Converting theoretical weights to practical share allocations for trading.

#### 8. `solve_cvxpy_problem`
Advanced custom optimization using CVXPY for complex constraints.

**Parameters:**
- `problem`: CVXPY problem specification with variables, constraints, and objectives

**Use Case:** Custom optimization problems that require advanced mathematical formulations.

#### 9. `simple_cvxpy_solver`
Simplified CVXPY interface for basic optimization problems.

**Parameters:**
- `variables`: List of optimization variables
- `objective_type`: "minimize" or "maximize"
- `objective_expr`: Objective function expression
- `constraints`: List of constraint expressions
- `description`: Problem description

**Use Case:** Simple custom optimization without complex CVXPY knowledge.

## Tool Selection Guide

Choose the right tool based on your optimization needs:

| **Scenario** | **Recommended Tool** | **Why** |
|--------------|---------------------|---------|
| **General portfolio optimization** | `solve_portfolio` | Most flexible, supports various constraints and objectives |
| **Classic mean-variance optimization** | `solve_efficient_frontier` | Standard Markowitz approach, well-tested |
| **Risk parity / diversification focus** | `solve_hierarchical_portfolio` | Modern approach, robust to estimation errors |
| **Efficient frontier analysis** | `solve_cla` | Efficient computation of entire frontier |
| **Incorporating market views** | `solve_black_litterman` | Combines equilibrium with expert opinions |
| **Converting weights to shares** | `solve_discrete_allocation` | Practical implementation of theoretical weights |
| **Custom mathematical constraints** | `solve_cvxpy_problem` | Maximum flexibility for complex problems |
| **Simple custom optimization** | `simple_cvxpy_solver` | Easy interface for basic custom problems |

### When to Use Each Method

**Traditional Approaches:**
- **Efficient Frontier**: When you want to understand risk-return tradeoffs
- **CLA**: When you need the complete efficient frontier efficiently
- **General Portfolio**: When you have specific constraints or objectives

**Modern Approaches:**
- **HRP**: When you have many assets and want robust diversification
- **Black-Litterman**: When you have market views or want to incorporate expert opinions

**Practical Implementation:**
- **Discrete Allocation**: Always use after optimization to convert to actual shares

## Portfolio Optimization Examples

The server provides two main endpoints for portfolio optimization. Here are comprehensive examples for different scenarios:

### 1. Basic Portfolio Optimization

```python
# Example 1: Simple minimum volatility portfolio
{
    "description": "Build a minimum volatility portfolio",
    "tickers": ["AAPL", "MSFT", "NVDA", "GOOGL", "META"],
    "constraints": ["max_weight 0.3"],  # No single stock exceeds 30%
    "objective": "minimize_volatility"
}

# Example 2: Maximum Sharpe ratio portfolio
{
    "description": "Build a maximum Sharpe ratio portfolio",
    "tickers": ["AAPL", "MSFT", "NVDA", "GOOGL", "META"],
    "constraints": ["max_weight 0.3"],
    "objective": "maximize_sharpe_ratio"
}
```

### 2. Sector-Constrained Portfolio

```python
# Example: Diversified portfolio across major sectors
{
    "description": "Build a diversified portfolio across major sectors",
    "tickers": [
        # Technology
        "AAPL", "MSFT", "NVDA", "GOOGL", "META",
        # Financials
        "JPM", "V", "BAC", "GS", "AXP",
        # Healthcare
        "JNJ", "UNH", "PFE", "MRK", "ABBV",
        # Consumer
        "MCD", "PG", "KO", "WMT", "SBUX",
        # Energy
        "XOM", "CVX"
    ],
    "constraints": [
        "max_weight 0.15",     # No single stock exceeds 15%
        "sector_tech 0.35",    # Technology sector max 35%
        "sector_fin 0.35",     # Financial sector max 35%
        "sector_health 0.35",  # Healthcare sector max 35%
        "sector_cons 0.35",    # Consumer sector max 35%
        "sector_energy 0.35"   # Energy sector max 35%
    ],
    "objective": "minimize_volatility"
}
```

### 3. Risk-Constrained Portfolio

```python
# Example: Portfolio with risk constraints
{
    "description": "Build a portfolio with risk constraints",
    "tickers": ["AAPL", "MSFT", "NVDA", "GOOGL", "META", "JPM", "V", "JNJ", "UNH"],
    "constraints": [
        "max_weight 0.2",      # No single stock exceeds 20%
        "min_weight 0.05",     # Each stock must have at least 5%
        "max_volatility 0.15"  # Maximum portfolio volatility of 15%
    ],
    "objective": "maximize_sharpe_ratio"
}
```

### 4. Factor-Constrained Portfolio

```python
# Example: Portfolio with factor constraints
{
    "description": "Build a portfolio with factor constraints",
    "tickers": ["AAPL", "MSFT", "NVDA", "GOOGL", "META", "JPM", "V", "JNJ", "UNH"],
    "constraints": [
        "max_weight 0.2",           # No single stock exceeds 20%
        "min_weight 0.05",          # Each stock must have at least 5%
        "max_beta 1.2",             # Maximum portfolio beta of 1.2
        "min_momentum 0.1",         # Minimum momentum factor exposure
        "max_value 0.3"             # Maximum value factor exposure
    ],
    "objective": "maximize_sharpe_ratio"
}
```

### 5. Custom Risk Measures

```python
# Example: Portfolio with custom risk measures
{
    "description": "Build a portfolio with custom risk measures",
    "tickers": ["AAPL", "MSFT", "NVDA", "GOOGL", "META", "JPM", "V", "JNJ", "UNH"],
    "constraints": [
        "max_weight 0.2",           # No single stock exceeds 20%
        "max_cvar 0.1",             # Maximum Conditional Value at Risk of 10%
        "max_cdar 0.15",            # Maximum Conditional Drawdown at Risk of 15%
        "max_semivariance 0.12"     # Maximum semivariance of 12%
    ],
    "objective": "minimize_volatility"
}
```

### 6. Hierarchical Risk Parity (HRP) Portfolio

```python
# Example: HRP portfolio for risk parity
{
    "description": "Build HRP portfolio for risk parity across sectors",
    "tickers": [
        "AAPL", "MSFT", "GOOGL",  # Tech
        "JPM", "V", "BAC",        # Finance
        "JNJ", "UNH", "PFE",      # Healthcare
        "PG", "KO", "WMT"         # Consumer
    ],
    "min_weight": 0.02,
    "max_weight": 0.25,
    "risk_free_rate": 0.02
}
```

### 7. Critical Line Algorithm (CLA) Portfolio

```python
# Example: CLA optimization for efficient frontier analysis
{
    "description": "Optimize tech portfolio using CLA",
    "ticke

…

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [ebrandler](https://github.com/ebrandler)
- **Source:** [ebrandler/mcportfolio](https://github.com/ebrandler/mcportfolio)
- **License:** Apache-2.0

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** yes
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-ebrandler-mcportfolio
- Seller: https://agentstack.voostack.com/s/ebrandler
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
