Skip to main content
Glama
kchinna

TradingAssistantMCP

by kchinna

TradingAssistantMCP

Учебный проект: MCP-сервер (Model Context Protocol), который позволяет агенту (например, Claude) получать данные о акциях и, в перспективе, запускать бэктесты и собственные торговые стратегии.

Установка

Требуется Python 3.11+. Пока не нужны API-ключи (текущие инструменты используют yfinance, для которого не требуется регистрация).

python3 -m venv .venv
.venv/bin/pip install -e .

Это создаёт изолированное окружение в .venv/ и устанавливает в него зависимости проекта. .venv/ находится в .gitignore — любой, кто клонирует этот репозиторий, должен сам выполнить эти две команды, прежде чем что-то заработает.

Related MCP server: yfinance MCP Server

Запуск сервера

Сервер (src/trading_assistant_mcp/server.py) не предназначен для запуска напрямую — его запускает MCP-клиент (агент) через stdio. Два способа проверить его работу:

1. MCP Inspector (ручное тестирование, агент не нужен) — браузерный интерфейс для прямого вызова инструментов:

.venv/bin/mcp dev src/trading_assistant_mcp/server.py

Открывает локальный URL (например, http://127.0.0.1:6274). Нажмите Connect, перейдите на вкладку Tools и вызовите инструмент вручную.

Требуется установленный uv (mcp dev запускает сервер через uv run внутри, независимо от указанного выше venv).

2. Claude Code (настоящий агент) — зарегистрирован как MCP-сервер уровня проекта в .mcp.json. Откройте сессию Claude Code в этом каталоге и просто задайте вопрос, например «какая цена у AAPL?» — Claude сам решит, вызывать ли инструмент.

Примечание о переносимости: в .mcp.json жёстко прописан абсолютный путь к .venv/bin/python этой машины. Если вы клонируете этот репозиторий в другое место, выполните заново:

claude mcp add -s project trading-assistant -- /absolute/path/to/.venv/bin/python /absolute/path/to/src/trading_assistant_mcp/server.py

Что уже есть

  • get_quote(symbol) — текущая цена, дневной диапазон, объём для тикера акции.

Структура проекта

src/trading_assistant_mcp/
├── server.py              # MCP server: wraps data functions as tools
├── data/
│   └── yfinance_client.py # plain Python, no MCP dependency — reusable/testable on its own
└── analysis/               # reserved for indicators (SMA/EMA/RSI/MACD), not yet built

server.py намеренно сделан тонким адаптером: это единственный файл, который импортирует mcp. Логика получения данных и (позже) анализа остаётся в обычных Python-модулях, чтобы её можно было тестировать и переиспользовать независимо от протокольного уровня.

План развития

Сначала анализ текущих данных (свечи, фундаментальные показатели/коэффициенты, технические индикаторы), затем бэктестинг и собственные стратегии на естественном языке (например, «покупай AMD каждый раз, когда она падает на 1%, продавай каждый раз, когда она растёт на 5%»). Полный план — в решениях проекта.

Available Tools

4 tools
get_candlesA

Get historical OHLCV candlestick bars for a stock symbol.

Args: symbol: Stock ticker symbol, e.g. "AAPL" or "MSFT". period: How far back to fetch, e.g. "1mo", "3mo", "6mo". interval: Bar size, e.g. "1h", "1d".

ParametersJSON Schema
NameRequiredDescriptionDefault
periodNo3mo
symbolYes
intervalNo1h

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.7/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the core behavior—returning historical rather than live data in OHLCV bar form—and describes lookback period and bar interval. It does not disclose potential edge behaviors such as timezone handling, corporate action adjustments, or error behavior for invalid symbols.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is compact and front-loaded: one clear purpose sentence followed by a short Args block with definitions and examples. Every line adds useful information and there is no filler.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

With an output schema present, the return structure does not need to be explained in the description. All three parameters are covered with meaningful semantics, and the defaults are visible in the schema. The main missing pieces are explicit sibling routing and behavioral edge cases, but for a simple historical-candles endpoint the description is largely complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the docstring must compensate, and it does. It defines symbol as a stock ticker with examples, period as how far back to fetch, and interval as bar size, also with examples. The schema supplies defaults, which the description does not repeat. It stops short of enumerating all valid period/interval values, but gives enough concrete guidance for correct invocation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states a specific verb and resource: 'Get historical OHLCV candlestick bars for a stock symbol.' This distinguishes it from sibling tools like get_quote and get_fundamentals because it is about historical price bars rather than quotes, fundamentals, or indicators. However, it does not explicitly contrast itself with those siblings.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Usage is implied: this tool is for historical candle data when the agent needs OHLCV bars. The description provides no explicit guidance on when to prefer this tool over get_quote, get_fundamentals, or get_technical_indicators, nor does it mention exclusions or edge cases.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_fundamentalsA

Get valuation/financial ratios for a stock symbol (P/E, market cap, EPS, dividend yield, beta, 52-week range, margins, growth, etc.).

Fields may be null if not available for a given symbol/exchange.

Args: symbol: Stock ticker symbol, e.g. "AAPL" or "MSFT".

ParametersJSON Schema
NameRequiredDescriptionDefault
symbolYes

TDQS

A4.1/5.0
Behavior3/5

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 does disclose an important trait: 'Fields may be null if not available for a given symbol/exchange'. However, it does not describe output structure, error behavior, data freshness, or symbol validation, so the behavioral picture remains partial.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise and front-loaded: it opens with the core purpose, follows with the null-field caveat, and ends with a clear Args section. No sentence is wasted, and the structure is easy to scan.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple one-parameter tool with no output schema, the description is largely complete: it states the tool's purpose, lists representative fields, documents the only parameter, and flags nullability. It could be strengthened by briefly describing the expected return shape or behavior for invalid symbols, but these are minor gaps given the tool's low complexity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema provides only the property name 'symbol', but the description adds meaningful semantics: 'Stock ticker symbol, e.g. "AAPL" or "MSFT"'. This fully compensates for the 0% schema description coverage and gives the agent concrete examples for the single required parameter.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific verb and resource: 'Get valuation/financial ratios for a stock symbol', and lists concrete fields such as P/E, market cap, EPS, and dividend yield. This clearly distinguishes it from sibling tools like get_quote, get_candles, and get_technical_indicators, which are about prices and technical analysis rather than fundamentals.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies when to use the tool (when you need valuation or financial ratios) but provides no explicit guidance on alternatives or exclusions. It does not mention that get_quote should be used for current price or get_candles for historical prices, leaving the routing to inference.

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 range for a stock symbol.

Args: symbol: Stock ticker symbol, e.g. "AAPL" or "MSFT".

ParametersJSON Schema
NameRequiredDescriptionDefault
symbolYes

TDQS

A4.3/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden for behavioral disclosure. It does state what output to expect (current price and day range), but it does not discuss data reliability, delay, error handling, or whether the price is real-time or delayed. This is adequate for a simple read-only tool but leaves some behavioral details uncovered.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is compact, front-loaded with the purpose, and includes a clearly separated 'Args:' section. Every sentence adds value, and there is no redundancy or filler.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple one-parameter tool with no output schema, the description is largely complete: it states the input format and the main expected output. It could be more complete by describing the return structure or noting data source, but it provides enough for an agent to call the tool with confidence.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema provides no description for the 'symbol' parameter (0% coverage), but the description fully compensates by explaining the argument in plain language and giving concrete examples like 'AAPL' or 'MSFT.' This is exactly the kind of parameter semantics that helps an agent invoke the tool correctly.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's action and resource: 'Get the current price and day range for a stock symbol.' This is specific and distinct from the siblings (fundamentals, candles, technical indicators), so an agent can confidently select this tool for quote-like data.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The usage context is clearly implied: use when you need the current price and day range for a stock. However, it does not explicitly mention when not to use it or contrast with the sibling tools, so the guidance is clear but lacks explicit exclusions or alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_technical_indicatorsA

Compute standard technical indicators (SMA-20/50, RSI-14, MACD, Bollinger Bands, ATR-14, volume vs its 20-period average) for a stock symbol.

Fetches its own candle data internally (not via get_candles - that tool's raw output is too large to round-trip through a tool call). Needs at least 50 candles for every indicator to be non-null (fewer still works, but indicators requiring more history than is available return null).

Args: symbol: Stock ticker symbol, e.g. "AAPL" or "MSFT". period: How far back to fetch, e.g. "1mo", "3mo", "6mo". interval: Bar size, e.g. "1h", "1d".

ParametersJSON Schema
NameRequiredDescriptionDefault
periodNo3mo
symbolYes
intervalNo1h

TDQS

A4.4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the burden of behavioral disclosure and does so well: it explains that the tool fetches candle data internally, why it avoids get_candles, and that insufficient history produces null values. It does not detail the exact response shape, but for a compute-only indicator tool the disclosed behavior is meaningful and sufficient.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is compact and front-loaded: the first sentence states the capability, the second adds the key operational caveat, and the Args block gives parameter semantics in a scannable format. There is no filler, repetition, or wasted text.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a 3-parameter read/compute tool with no output schema, the description covers purpose, parameter meaning, internal data sourcing, and null behavior—enough for an agent to invoke it correctly. The only notable omission is the exact return structure, but the listed indicators and caveats provide adequate contextual coverage.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0%, so the description must compensate, and it does: symbol is explained with examples, period is defined as 'how far back to fetch' with examples like '1mo', '3mo', '6mo', and interval is defined as 'bar size' with examples like '1h', '1d'. It could also state accepted formats or defaults, but the provided semantics are enough for correct invocation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

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 standard technical indicators (SMA-20/50, RSI-14, MACD, Bollinger Bands, ATR-14, volume vs its 20-period average) for a stock symbol.' The explicit indicator list makes the tool's scope precise and clearly distinct from siblings like get_quote, get_fundamentals, and get_candles.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives clear context: use this to compute indicators over a period/interval, and it explicitly warns not to prefetch candles via get_candles because that tool's raw output is too large to round-trip through a tool call. It also flags the 50-candle minimum for non-null results, though it does not explicitly discuss when to prefer get_quote or get_fundamentals.

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.

  1. 4 tool updatesv0.1.0
    • First observedget_candles
    • First observedget_fundamentals
    • First observedget_quote
    • First observedget_technical_indicators

TDQS

A4.2/5.0

Scored across 4 tools

Disambiguation5/5

Each tool targets a distinct data domain: real-time quote, fundamentals, historical OHLCV, and computed indicators. Descriptions clearly separate concerns, so an agent should not confuse them.

Naming Consistency5/5

All tools follow a consistent get_<noun> pattern with snake_case naming. The naming convention is uniform and predictable across the entire set.

Tool Count5/5

Four tools is a focused, well-scoped set for a market-data-only server. Each tool covers a meaningful and non-redundant aspect of stock research.

Completeness4/5

The set covers the core read-only stock data needs: real-time price, fundamentals, historical price data, and technical indicators. Minor gaps exist, such as no symbol search/disambiguation or batch quote support, but these are workable around.

Maintenance

ActivityMaintained
ResponsivenessNo issues

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

Related MCP Servers

  • A
    license
    Not graded
    quality
    C
    maintenance
    Enables AI agents to retrieve real-time stock data, manage watchlists, and perform comprehensive technical analysis using Yahoo Finance API. Provides 18+ tools for stock price tracking, trend analysis, volatility assessment, and financial indicators through MCP integration.
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables LLMs to retrieve stock market data and financial information from Yahoo Finance using the yfinance Python library. Supports querying stock prices, historical data, and other financial metrics through natural language.
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    Provides real-time stock quotes, historical data, and stock search via Yahoo Finance, enabling AI assistants to access and analyze financial market data.
    18
    19
    MIT