mcp-financial-data-server
Click on "Install 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-serverWhat'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).
| Name | Required | Description | Default |
|---|---|---|---|
| period | No | 1y | |
| tickers | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden of behavioral disclosure. It clearly states the output (a ticker-by-ticker correlation matrix of daily returns, range -1 to 1) and constrains inputs. It does not describe data sources or error handling, but for a read-only computation tool the core behavior is transparent.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is concise and well-structured with a one-sentence purpose, an 'Args' block, and a 'Returns' line. Every section earns its place and no redundant fluff is present.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's simplicity (2 parameters, no output schema, no annotations), the description is complete. An agent can determine required arguments, optional argument values, and the expected result format without any additional context.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate. It fully documents both parameters: tickers requires 'two or more ticker symbols' with a concrete example, and period lists all allowed values ('1mo','3mo','6mo','1y','2y','5y','10y','ytd','max'). This exceeds what the raw schema provides.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description opens with a specific verb and resource: 'Compute the correlation matrix of daily returns between two or more assets.' This clearly defines the tool's function and distinguishes it from siblings like get_quote or get_portfolio_metrics, which serve different purposes. The return value is also specified.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The purpose statement makes the context obvious: use this tool when you need a correlation matrix across multiple tickers. It does not explicitly name alternatives or exclusions, but the sibling tools are distinct enough that no further routing guidance is needed.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| period | No | 6mo | |
| ticker | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden, and it does well by disclosing the null behavior for moving averages when history is insufficient. It also clearly states what is returned. It stops short of describing error scenarios or data conventions, but for a read-only summary tool this is reasonably transparent.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is compact, front-loaded with the main purpose, and clearly separated into Args and Returns. Every sentence contributes useful information with no filler.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a tool with no annotations and no output schema, the description covers the essential inputs, the output contents, and an important edge case. It is slightly incomplete in not addressing error behavior or the exact structure/format of the returned values, but an agent has enough to call it correctly in the common case.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Since schema description coverage is 0%, the description compensates by defining both parameters: ticker with concrete examples and period with an explicit list of allowed values. It does not mention the default period or units for return, but enough meaning is added for correct invocation.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description opens with a specific verb and resource: "Get a summarized price history for one ticker," followed by the concrete outputs (moving averages, high/low, return). The "for one ticker" scope also helps distinguish it from siblings like compare_assets.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The intended use is implied by the description: use this when you need a historical price summary for a single ticker. However, it never explicitly names alternatives or explains when to prefer get_quote or compare_assets, so the guidance is only implicit.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| period | No | 1y | |
| tickers | Yes | ||
| weights | Yes | ||
| risk_free_rate | No |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure. It is transparent about what the tool computes and returns, listing cumulative return, annualized return, annualized volatility, Sharpe ratio, and max drawdown. It does not discuss edge cases, data sources, or validation behavior, but the compute-and-return nature is well conveyed.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is compact, structured into Args and Returns sections, and every sentence carries necessary information. There is no filler or repetition of the input schema, and the purpose statement is front-loaded.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the absence of an output schema and annotations, the description covers the key inputs and outputs well. It could be more complete by specifying the exact return format/keys or whether outputs are decimal or percentage, but it provides enough detail for an agent to understand the tool's scope and behavior.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 0%, so the description must fully compensate. It does: tickers are given with an example, weights are explained with the 'same order' and 'must sum to 1.0' constraint, period is enumerated with all valid values, and risk_free_rate is explained with an annualized example. This is significantly more useful than the bare schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description opens with a specific verb and resource: 'Compute risk/return metrics for a weighted portfolio of stocks.' This clearly distinguishes the tool from siblings like get_quote, compare_assets, and get_historical_summary by focusing on portfolio-level aggregated metrics rather than single quotes, comparisons, or historical summaries.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The first sentence gives clear context: this is for computing portfolio risk/return metrics from tickers and weights. It does not explicitly name alternative tools or state when not to use it, but the portfolio-focused wording provides enough context for an agent to select it appropriately against the listed siblings.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| ticker | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the behavioral burden. It clearly states the return fields (latest price, previous close, absolute/percentage change, currency) and the error payload for invalid or unreachable data. This is solid, though it does not address latency or data freshness.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is front-loaded with a one-sentence summary and uses compact Args/Returns sections. Every sentence adds useful information with no tautology or filler.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple one-parameter quote tool with no output schema, the description is complete: it documents the parameter, the return contract, and failure behavior. Nothing an agent needs to invoke or interpret the call correctly is missing.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema has no description coverage for the ticker parameter, so the description must compensate. It provides concrete ticker formats ('AAPL', 'MSFT', 'PETR4.SA') and notes B3-listed stocks, adding real value beyond the schema's bare 'Ticker' title.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description opens with a specific verb and resource: 'Get the current price and day change for a stock ticker.' This clearly distinguishes it from sibling tools like get_portfolio_metrics or get_historical_summary, which operate at portfolio or historical levels.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description establishes that this is for single-ticker current quotes, but it does not explicitly say when-not-to-use it or point to alternatives like compare_assets or get_historical_summary. The ticker examples imply usage but do not provide exclusion criteria.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.
4 tool updates
v0.1.0- First observed
compare_assets - First observed
get_historical_summary - First observed
get_portfolio_metrics - First observed
get_quote
TDQS
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
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Backtest strategies and analyze portfolios on any ticker: CAGR, drawdown, Sharpe, from real data.
Portfolio-aware finance tools: drift, risk, earnings, benchmarks, news, tax harvesting
Live market data, financial analysis, and portfolio research tools across 10,000+ tickers.
Stocks, crypto, FX, and portfolio math in one tool — no per-source API juggling.
Related MCP Servers
- FlicenseNot gradedqualityFmaintenanceEnables 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.-
- AlicenseAqualityCmaintenanceProvides 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.176MIT
- FlicenseNot gradedqualityDmaintenanceProvides real-time stock data, historical analysis, and stock comparisons using the Yahoo Finance API.-
- FlicenseNot gradedqualityDmaintenanceEnables financial analysis by fetching real market data from Yahoo Finance, computing moving averages, returns, and volatility, and generating price charts.-
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/Biahellens/mcp-financial-data-server'
If you have feedback or need assistance with the MCP directory API, please join our Discord server