mcp-financial-data-server
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mcp-financial-data-server What's the Sharpe ratio and max drawdown for an equal-weight portfolio of AAPL, MSFT, and GOOG?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MCP Server de Dados Financeiros
Um servidor MCP que expõe ferramentas para consultar cotações e calcular métricas de risco/retorno de carteiras (retorno acumulado, volatilidade anualizada, Sharpe, máximo drawdown). Plugável direto no Claude Desktop, Claude Code ou qualquer outro cliente MCP.


Arquitetura
Um servidor MCP é só um processo Python que fala o protocolo MCP (via stdio ou HTTP) e expõe um punhado de tools — funções com schema de input bem definido — que qualquer cliente MCP pode chamar. O servidor não tem interface própria; o cliente (Claude, por exemplo) decide quando invocar cada tool com base na docstring e no schema.
src/mcp_financial/
├── server.py # entrypoint MCP: registra as tools (MCPServer)
├── models.py # validação de input com Pydantic
├── data.py # wrapper do yfinance: cache + tratamento de erro
├── metrics.py # cálculos financeiros puros (testáveis sem rede)
├── cache.py # cache TTL em memória (evita rate limit do yfinance)
├── logging_config.py # logging estruturado (JSON) em stderr
└── errors.py # exceções de domínioSeparação deliberada: metrics.py não importa yfinance nem faz I/O — é só matemática sobre pandas.Series/DataFrame, o que permite testar Sharpe e drawdown com valores calculados à mão, sem depender da rede ou de mocks frágeis. data.py isola tudo que pode falhar (ticker inválido, provedor fora do ar, rate limit) atrás de exceções próprias (TickerNotFoundError, DataProviderError), para que server.py só precise de um try/except genérico por tool.
Related MCP server: FinanceKit MCP
Ferramentas
Tool | Descrição |
| Preço atual, fechamento anterior e variação do dia. |
| Retorno acumulado, retorno anualizado, volatilidade anualizada, Sharpe e máximo drawdown de uma carteira ponderada. |
| Matriz de correlação dos retornos diários entre dois ou mais ativos. |
| Médias móveis (20/50), máxima/mínima do período e retorno acumulado. |
Todas retornam um dict {"error": "invalid_input" | "data_unavailable" | "internal_error", "details": ...} em vez de lançar exceção, para que o modelo cliente consiga reagir ao erro em vez de a chamada travar.
Rodando localmente
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"Testar as ferramentas via MCP Inspector:
npx @modelcontextprotocol/inspector mcp-financial-data-serverOu rodar o servidor puro (fala stdio, então não produz output "normal" no terminal):
mcp-financial-data-serverConfigurando no Claude Desktop
Adicione ao claude_desktop_config.json:
{
"mcpServers": {
"financial-data": {
"command": "mcp-financial-data-server"
}
}
}Ou apontando para o Python do virtualenv, se preferir não instalar globalmente:
{
"mcpServers": {
"financial-data": {
"command": "/caminho/para/.venv/bin/mcp-financial-data-server"
}
}
}Docker
docker build -t mcp-financial-data-server .Como o protocolo MCP fala stdio, o cliente precisa invocar o container com -i:
{
"mcpServers": {
"financial-data": {
"command": "docker",
"args": ["run", "-i", "--rm", "mcp-financial-data-server"]
}
}
}Testes
pytest --cov=mcp_financial --cov-report=term-missingOs testes de metrics.py usam valores calculados à mão (não a mesma fórmula do código sob teste) para os cálculos financeiros — ver comentários em tests/test_metrics.py.
Boas práticas aplicadas
Validação de input: todo tool valida com um modelo Pydantic antes de tocar em dado externo (ticker normalizado, período restrito a um enum, pesos de carteira validados para somar 1.0).
Tratamento de erro: ticker inválido e provedor fora do ar viram exceções de domínio (
errors.py), nunca uma exceção crua do yfinance vazando pro cliente MCP.Cache: TTL curto (15s para cotação, 5min para histórico) evita bater o rate limit do yfinance em chamadas repetidas na mesma sessão.
Logging estruturado: JSON em stderr (stdout é reservado pro protocolo MCP).
CI: GitHub Actions roda lint (
ruff) epytesta cada push/PR em duas versões de Python.
Limitações conhecidas
yfinance depende de endpoints não-oficiais do Yahoo Finance; instabilidade upstream é esperada e tratada como
DataProviderError, não como bug do servidor.Métricas de carteira assumem rebalanceamento diário implícito (pesos fixos aplicados ao retorno diário de cada ativo), não um buy-and-hold com deriva de pesos.
Available Tools
4 toolscompare_assetsA
Compute the correlation matrix of daily returns between two or more assets.
Args: tickers: Two or more ticker symbols to correlate, e.g. ['AAPL', 'MSFT', 'GOOGL']. period: Lookback window: one of '1mo','3mo','6mo','1y','2y','5y','10y','ytd','max'.
Returns a ticker-by-ticker correlation matrix of daily returns (-1 to 1).
Inputs: tickers (required), period.
get_historical_summaryA
Get a summarized price history for one ticker: moving averages, high/low, and return.
Args: ticker: Ticker symbol, e.g. 'AAPL' or 'VALE3.SA'. period: Lookback window: one of '1mo','3mo','6mo','1y','2y','5y','10y','ytd','max'.
Returns the 20/50-day simple moving averages, period high/low close, and cumulative return over the window. Moving averages are null when there isn't enough history for that window.
Inputs: ticker (required), period.
get_portfolio_metricsA
Compute risk/return metrics for a weighted portfolio of stocks.
Args: tickers: Ticker symbols in the portfolio, e.g. ['AAPL', 'MSFT']. weights: Portfolio weight per ticker, same order, must sum to 1.0. period: Lookback window: one of '1mo','3mo','6mo','1y','2y','5y','10y','ytd','max'. risk_free_rate: Annualized risk-free rate for the Sharpe ratio (e.g. 0.1075 for 10.75%).
Returns cumulative return, annualized return, annualized volatility, Sharpe ratio, and max drawdown for the combined portfolio.
Inputs: tickers (required), weights (required), period, risk_free_rate.
get_quoteA
Get the current price and day change for a stock ticker.
Args: ticker: Ticker symbol, e.g. 'AAPL', 'MSFT', or 'PETR4.SA' for B3-listed stocks.
Returns the latest price, previous close, absolute and percentage change, and currency. Returns an {"error": ...} payload if the ticker is invalid or the data provider is unreachable.
Inputs: ticker (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 4 tools
The four tools have generally clear boundaries: price snapshot, portfolio analytics, correlation, and historical summary. There is mild overlap between get_quote and get_historical_summary since both are single-ticker price tools, but the current vs. windowed-summary distinction is understandable.
Names are consistently lowercase snake_case with a verb_noun pattern: get_quote, get_portfolio_metrics, compare_assets, get_historical_summary. The single compare_ prefix is still predictable and follows the same grammatical style.
Four tools is a modest but reasonable set for a focused market-data server. The count is not excessive, though the broad server name suggests slightly more coverage could be warranted.
The core quote and analytics workflows are covered, but there is no raw historical price series endpoint, no search/discovery tool, and no batch quote capability. These are notable gaps for a 'financial data' server, though users can still accomplish basic investing analyses.
Maintenance
Related MCP Connectors
Portfolio-aware finance tools: drift, risk, earnings, benchmarks, news, tax harvesting
Live stock quotes, a stock screener, crypto prices and FX rates as agent tools.
Performance, risk, comparisons, backtests and screening for US stocks and ETFs, with charts.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceEnables comprehensive stock market analysis with portfolio management, technical indicators, dividend tracking, sector analysis, risk metrics, and price alerts. Provides real-time stock data, trend analysis, and investment insights through natural language interactions.1-
- AlicenseAqualityDmaintenanceProvides AI agents with real-time financial market intelligence including stock quotes, crypto data, technical analysis, and portfolio insights. Enables natural language queries for current prices, technical indicators, asset comparisons, and portfolio analysis.179MIT
- FlicenseNot gradedqualityDmaintenanceEnables financial analysis by fetching real market data from Yahoo Finance, computing moving averages, returns, and volatility, and generating price charts.-
- FlicenseNot gradedqualityDmaintenanceEnables AI assistants to perform live stock and portfolio research using Yahoo Finance data, including quotes, fundamentals, price history, news, portfolio analysis, and ticker comparisons.-