Skip to main content
Glama
README.md
# An MCP Server for the vnstock3 library

A Model Context Protocol (MCP) server that provides Vietnamese financial market data through Claude Desktop. Fetch historical prices for stocks, forex, cryptocurrencies, and international indices using the vnstock3 library.

## Features

- **Vietnamese Stocks**: Historical OHLCV data for Vietnamese stock market
- **Forex Rates**: Exchange rate data for currency pairs
- **Cryptocurrencies**: Historical crypto price data
- **International Indices**: Global market index data
- **Containerized**: Runs as an isolated Docker container via MCP Gateway
- **Seamless Integration**: Works directly with Claude Desktop

## Quick Deploy

[![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/gahoccode/vnprices-mcp)

## Available Tools

### Price History Tools

#### 1. `get_stock_history`
Fetch historical stock price data for Vietnamese stocks (e.g., VCI, VNM, HPG).

#### 2. `get_forex_history`
Fetch historical forex exchange rate data (e.g., USDVND, EURVND).

#### 3. `get_crypto_history`
Fetch historical cryptocurrency price data (e.g., BTC, ETH).

#### 4. `get_index_history`
Fetch historical index data for Vietnamese market indices (VNINDEX, HNXINDEX, UPCOMINDEX).

### Portfolio Optimization Tools

#### 5. `calculate_returns`
Calculate expected returns for a portfolio of Vietnamese stocks using mean historical or exponential moving average methods.

#### 6. `optimize_portfolio`
Perform Mean-Variance Optimization to find the maximum Sharpe ratio portfolio for Vietnamese stocks.

#### 7. `full_portfolio_optimization`
Perform comprehensive portfolio optimization with multiple strategies (max Sharpe, min volatility, max utility) for Vietnamese stocks.

### Financial Statement Tools

**Note:** Currently supports annual periods only. Quarterly data support planned for future releases.

#### 8. `get_income_statement`
Fetch annual income statement (profit & loss) for Vietnamese stocks.

#### 9. `get_balance_sheet`
Fetch annual balance sheet for Vietnamese stocks.

#### 10. `get_cash_flow`
Fetch annual cash flow statement for Vietnamese stocks.

#### 11. `get_financial_ratios`
Fetch annual financial ratios (P/B, ROE, etc.) for Vietnamese stocks.

### Dividend Data Tool

#### 12. `get_dividend_history`
Fetch complete dividend history for Vietnamese stocks.

### Company Information Tools

#### 13. `get_company_info`
Fetch comprehensive company information for Vietnamese stocks including overview, shareholders, officers, subsidiaries, events, news, reports, financial ratios summary, and trading statistics.

### Commodity & Exchange Rate Tools

#### 14. `get_sjc_gold_price`
Fetch SJC gold prices (current or historical from 2016-01-02).

#### 15. `get_btmc_gold_price`
Fetch BTMC (Bảo Tín Minh Châu) gold prices (current only).

#### 16. `get_vcb_exchange_rate`
Fetch VCB (Vietcombank) exchange rates for a specific date.

### Fund Management Tools

#### 17. `get_fund_listing`
Get list of all available mutual funds with filtering by fund type (BALANCED, BOND, STOCK).

#### 18. `search_funds`
Search for mutual funds by symbol or partial name.

#### 19. `get_fund_nav_report`
Get historical NAV report for a specific mutual fund.

#### 20. `get_fund_top_holdings`
Get top 10 holdings for a specific mutual fund.

#### 21. `get_fund_industry_allocation`
Get industry allocation breakdown for a specific mutual fund.

#### 22. `get_fund_asset_allocation`
Get asset allocation breakdown for a specific mutual fund.


## Prerequisites

- **Docker Desktop** (or Docker Engine) - [Download Docker Desktop](https://docs.docker.com/get-started/get-docker/)
- **Claude Desktop** application
- **macOS, Windows, or Linux**

**vnstock3 Documentation:**
- [vnstock3 Documentation](https://vnstocks.com/docs/vnstock/thong-ke-gia-lich-su)
- [vnstock Historical Prices Guide](https://github.com/gahoccode/docs/blob/main/vnstock/historical_prices.md)
- [vnstock VCI Quote Source](https://github.com/thinh-vu/vnstock/blob/main/vnstock/explorer/vci/quote.py)
- [vnstock MSN Quote Source](https://github.com/thinh-vu/vnstock/blob/main/vnstock/explorer/msn/quote.py)

## Tutorial

Besides the docs, I highly recommend watching this tutorial and following NetworkChuck's instructions. This guy is awesome!

- [Docker MCP Tutorial by NetworkChuck](https://www.youtube.com/watch?v=GuTcle5edjk&t=1349s)
- [NetworkChuck's Docker MCP Example](https://github.com/theNetworkChuck/docker-mcp-tutorial)

## Project Structure
```
vnprices-mcp/
├── server.py           # MCP server implementation
├── Dockerfile          # Container definition
├── requirements.txt    # Python dependencies
└── README.md          # This file
```

## Configuration

### Step 1: Clone the Repository

First, clone this repository:

```bash
git clone https://github.com/gahoccode/vnprices-mcp.git
cd vnprices-mcp
```

### Step 2: Copy Configuration Files

Copy the vnstock catalog and configuration files to the MCP directory:

```bash
# Create the catalogs directory if it doesn't exist
mkdir -p ~/.docker/mcp/catalogs

# Copy the catalog file
cp vnstock-catalog.yaml ~/.docker/mcp/catalogs/custom.yaml

# Copy the config file
cp config.yaml ~/.docker/mcp/config.yaml

# Copy the registry file
cp registry.yaml ~/.docker/mcp/registry.yaml
```

### Step 3: Claude Desktop Setup

Edit `~/Library/Application Support/Claude/claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "mcp-gateway": {
      "command": "docker",
      "args": [
        "run",
        "-i",
        "--rm",
        "-v", "/var/run/docker.sock:/var/run/docker.sock",
        "-v", "/Users/YOUR_USERNAME/.docker/mcp:/mcp",
        "docker/mcp-gateway",
        "--catalog=/mcp/catalogs/docker-mcp.yaml",
        "--catalog=/mcp/catalogs/custom.yaml",
        "--config=/mcp/config.yaml",
        "--registry=/mcp/registry.yaml",
        "--transport=stdio"
      ]
    }
  }
}
```

**Important:** Replace `YOUR_USERNAME` with your actual macOS username.

After configuration:
1. Quit Claude Desktop completely (Cmd+Q on macOS)
2. Restart Claude Desktop
3. Wait for it to fully load

## Usage Examples

For detailed usage examples and sample queries, see [examples/questions.md](./examples/questions.md).

Quick examples:
- **Stock Data**: `Get VCI stock prices from January 1, 2024 to December 31, 2024`
- **Portfolio Optimization**: `Find the optimal portfolio weights for VCI, VNM, HPG to maximize Sharpe ratio`
- **Financial Statements**: `Get the annual income statement for VCI stock`
- **Company Info**: `Show me major shareholders of VCI stock`

## Rebuild & Test

### After Code Changes

If you modify `server.py` or other files:
```bash
# 1. Navigate to project directory
cd vnprices-mcp

# 2. Rebuild Docker image
docker build -t vnprices-mcp:latest .
docker build -t mcp-gateway .

# 2. Stop and remove old gateway container
docker stop mcp-gateway && docker rm mcp-gateway

# 3. Verify new image
docker images | grep vnprices-mcp

# 4. Check image ID changed
docker images vnprices-mcp

# 5. Run gateway
docker run -d \
  --name mcp-gateway \
  -v $(pwd)/catalogs:/mcp/catalogs \
  -v $(pwd)/registry.yaml:/mcp/registry.yaml \
  -v $(pwd)/config.yaml:/mcp/config.yaml \
  -p 3000:3000 \
  mcp-gateway

# 6. Restart Claude Desktop completely
# Quit (Cmd+Q) and restart
```

### View Live Logs

While Claude Desktop is running:
```bash
# Find the gateway container
docker ps | grep mcp-gateway

# View logs (replace <container-id> with actual ID)
docker logs -f <container-id>

# Or in one command
docker logs -f $(docker ps -q -f ancestor=docker/mcp-gateway)
```

### Clean Up Old Containers
```bash
# Remove stopped containers
docker container prune

# Remove unused images
docker image prune

# Full cleanup (careful!)
docker system prune -a
```

### Force Rebuild Everything

If things aren't working:
```bash
# 1. Stop Claude Desktop

# 2. Remove old containers
docker rm -f $(docker ps -aq -f ancestor=vnprices-mcp:latest)
docker rm -f $(docker ps -aq -f ancestor=docker/mcp-gateway)

# 3. Remove old image
docker rmi vnprices-mcp:latest

# 4. Rebuild from scratch
docker build --no-cache -t vnprices-mcp:latest .

# 5. Verify files exist
ls -la ~/.docker/mcp/
cat ~/.docker/mcp/config.yaml
cat ~/.docker/mcp/catalogs/custom.yaml

# 6. Test gateway manually (see above)

# 7. Restart Claude Desktop
```

## Development

### Project Structure
```
vnprices-mcp/
├── server.py              # MCP server implementation
│   ├── handle_list_tools()    # Register available tools
│   └── handle_call_tool()     # Execute tool calls
├── Dockerfile             # Container configuration
├── requirements.txt       # Python dependencies
└── README.md             # Documentation
```

### Adding New Tools

1. **Add tool definition** in `handle_list_tools()`:
```python
types.Tool(
    name="your_new_tool",
    description="What it does",
    inputSchema={
        "type": "object",
        "properties": {
            "param": {"type": "string"}
        },
        "required": ["param"]
    }
)
```

2. **Add handler logic** in `handle_call_tool()`:
```python
elif name == "your_new_tool":
    # Your implementation
    result = {"data": "response"}
    return [types.TextContent(type="text", text=json.dumps(result))]
```

3. **Rebuild:**
```bash
docker build -t vnprices-mcp:latest .
```

4. **Update catalog** in `~/.docker/mcp/catalogs/custom.yaml`:
```yaml
tools:
  - name: your_new_tool
```

## Technical Details

- **MCP Protocol Version**: 2025-06-18
- **Python Version**: 3.11
- **MCP SDK**: 1.2.0+
- **VNStock**: 3.2.0+
- **PyPortfolioOpt**: 1.5.6+ (portfolio optimization)
- **Transport**: stdio (Standard Input/Output)
- **Container Size**: ~1.7GB (v1.0.0+: increased from ~1.2GB due to portfolio optimization libraries)
- **Total Tools**: 22 (4 price history + 3 portfolio optimization + 4 financial statements + 1 dividend + 1 company info + 3 commodity/exchange + 6 fund management)

## References

- [vnstock3 Documentation](https://vnstocks.com/docs/vnstock/thong-ke-gia-lich-su)
- [vnstock Historical Prices Guide](https://github.com/gahoccode/docs/blob/main/vnstock/historical_prices.md)
- [vnstock Financial Statements Guide](https://github.com/gahoccode/docs/blob/main/vnstock/financial_statements.md)
- [vnstock Financial Statements Data Types](https://github.com/gahoccode/docs/blob/main/vnstock/financial_statements_dtypes.md)
- [vnstock Dividends Guide](https://github.com/gahoccode/docs/blob/main/vnstock/dividends.md)
- [vnstock Commodity Prices Guide](https://github.com/gahoccode/docs/blob/main/vnstock/commodity_prices.md)
- [vnstock Gold Price Source](https://github.com/thinh-vu/vnstock/blob/main/vnstock/explorer/misc/gold_price.py)
- [vnstock Exchange Rate Source](https://github.com/thinh-vu/vnstock/blob/main/vnstock/explorer/misc/exchange_rate.py)
- [Model Context Protocol](https://modelcontextprotocol.io)
- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
- [Docker MCP Gateway](https://github.com/docker/mcp-gateway)

## License

MIT License - Feel free to use and modify.

## Contributing

Contributions welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Test thoroughly
4. Submit a pull request

## Support

For issues or questions:
- VNStock: [vnstock GitHub](https://github.com/thinh-vu/vnstock)
- MCP: [Model Context Protocol Docs](https://modelcontextprotocol.io)
- Docker: [Docker MCP Gateway](https://github.com/docker/mcp-gateway)

---

**Built with ❤️ for the Vietnamese developer community**