Skip to main content
Glama

bcs-mcp

Твой портфель БКС Мир инвестиций — в диалоге с AI.

MCP-сервер, который подключает Claude (Claude Code, Claude Desktop — и любой другой MCP-клиент) к BCS Trade API. Смотри портфель, котировки, стакан, свечи, анализируй позиции и планируй ребалансировку — обычными фразами, на русском.

Это не торговый робот и не «сигналы». Решения всегда принимаешь ты — сервер лишь даёт модели безопасный доступ к данным твоего брокерского счёта.

Собран по образу и подобию t-invest-mcp (аналогичный сервер для Т-Инвестиций) — та же модель безопасности и файловых выгрузок.

Демо: портфель БКС на естественном языке — вопросы и покупка с подтверждением

Почему это безопасно

  • Read-only по умолчанию. Торговые операции даже не регистрируются, пока ты их явно не включишь. Достаточно токена «только для чтения».

  • Сделки — только с твоего подтверждения. Если включишь торговлю, перед каждой заявкой сервер показывает диалог «Купить N шт. X?» — без явного «да» заявка не уйдёт.

  • У БКС нет песочницы — поэтому торговый режим включай осознанно: каждая заявка реальная.

  • Токен живёт в переменной окружения и никогда не попадает в код, логи и ответы сервера. Быстрый старт ниже кладёт его в конфиг клиента — для постоянного использования держи токен в системном keychain, рецепт: docs/secure-token.md.

Related MCP server: DOS Growth MCP Server

Быстрый старт (5 минут)

Нужен Node.js ≥ 22 и брокерский счёт в БКС.

  1. Токен. Войди в веб-версию БКС Мир инвестиций → «Профиль» → «Управление счетами» → нажми на брокерский счёт → «Токены API» → «Выпустить токен», тип «Только для чтения». Токен показывается один раз; живёт 90 дней. Токен привязан ровно к одному счёту.

  2. Подключение к Claude Code — одной командой, установка не нужна (пакет bcs-mcp подтянется из npm):

    claude mcp add bcs \
      -e BCS_REFRESH_TOKEN=<ваш-токен> \
      -- npx -y bcs-mcp

    Для Claude Desktop тот же блок добавляется в Settings → Developer → Edit Config. Этот JSON подходит и любому другому MCP-клиенту (Cursor, VS Code, Windsurf и др.) — меняется только место, куда его вписать:

    {
      "mcpServers": {
        "bcs": {
          "command": "npx",
          "args": ["-y", "bcs-mcp"],
          "env": { "BCS_REFRESH_TOKEN": "<ваш-токен>" }
        }
      }
    }
    git clone https://github.com/human-turn/bcs-mcp && cd bcs-mcp
    npm install && npm run build
    # далее в командах выше вместо "npx -y bcs-mcp" → "node /path/to/bcs-mcp/dist/index.js"

    В такой минимальной конфигурации сервер строго read-only: смотреть и анализировать можно всё, торговать — нельзя (торговые операции даже не регистрируются). Торговля и файловые выгрузки включаются переменными в env — см. Переменные окружения, каждая выключена по умолчанию.

  3. Проверка: спроси «покажи мой портфель БКС».

Готовое из коробки: slash-команды

В Claude Code появляются как /bcs:<имя>:

Демо: квартальный ритуал одной командой

Команда

Что делает

portfolio_review

Полный обзор: структура, концентрация, риски

rebalance_check

Дрейф от целевых долей + план сделок в лотах (без исполнения)

invest_cash <сумма>

Пришла зарплата: куда докупить, чтобы приблизиться к целям

bond_picker <сумма> <горизонт>

Скрининг каталога облигаций: рейтинг, купон, доходность, лесенка

fire_progress

Прогресс к целям (FIRE) из portfolio-target.json: прогноз, требуемый взнос

position_deep_dive <тикер>

Разбор бумаги: карточка, динамика, моя позиция

trades_review [дней]

Мои сделки за период: обороты, средние цены, комиссии

weekly [сумма]

Недельный ритуал: дайджест + план докупок

quarterly

Обзор портфеля + проверка ребалансировки

feedback [тема]

Репорт о проблеме для разработчиков (без токена и личных данных)

Все команды анализируют и предлагают — ни одна не совершает сделок сама. Целевые доли для ребалансировки задаются файлом portfolio-target.json в корне проекта (эталон — MCP-ресурс bcs://portfolio-target/example, формат совместим с t-invest-mcp).

Дивиденды и купоны BCS Trade API не отдаёт — рядом можно подключить публичный moex-mcp (MOEX ISS): команды это учитывают.

Переменные окружения

Переменная

Значение

Описание

BCS_REFRESH_TOKEN

обязательна

Refresh-токен из ЛК БКС (90 дней, привязан к счёту)

BCS_ALLOW_TRADING

true/false

Регистрирует place/edit/cancel_order. Нужен токен «для торговли и чтения». РЕАЛЬНЫЕ деньги!

BCS_CONFIRM

off

Отключает elicitation-подтверждение сделок (по умолчанию включено; выключать не рекомендуется — песочницы нет)

BCS_OUTPUT_DIR

путь

Корень для файловых выгрузок outputPath (по умолчанию — cwd сервера)

Tools

Read-only (всегда):

Tool

Описание

get_portfolio

Портфель: позиции с P&L, долями, стоимостью в RUB/USD/EUR; итоги по классам (срез term, по умолчанию T0)

get_limits

Денежные и депо-лимиты: свободные средства по валютам (free = quantity − locked; снимок на начало дня)

get_quotes

Котировки (батч): bid/offer, last, open/high/low, изменение за день

get_order_book

Стакан L2 (глубина 20)

get_recent_trades

Лента обезличенных сделок: новейшие limit (расширяемое окно), период from/to; полный период в файл — через outputPath

get_candles

Свечи OHLCV (M1…MN); с outputPath — весь период чанками

find_instrument

Карточки по тикерам/ISIN: лот, classCode, купоны, дивдоходность, рейтинги (одна карточка на бумагу; allBoards — все площадки)

get_instruments_by_type

Каталог инструментов типа (акции/облигации/ETF/фьючерсы…), пагинация

get_trading_schedule

Сессии инструмента на сегодня (МСК, отсортированы)

get_trading_status

Открыт/закрыт инструмент сейчас + кросс-чек с расписанием (warning при расхождении)

get_discounts

Маржинальные дисконты (long/short)

get_orders

Список заявок (данные с 26.01.2026)

get_order_status

Статус заявки по UUID или биржевому номеру

get_trades

Мои исполненные сделки (данные с 26.01.2026)

get_server_info

Диагностика сервера (для фидбэка)

Торговые (BCS_ALLOW_TRADING=true): place_order, edit_order, cancel_order. Важно: количество в заявках — в штуках, не в лотах (лот — lotSize из find_instrument).

Выгрузка в файл

Каждый read-tool принимает outputPath (путь относительно BCS_OUTPUT_DIR) и outputFormat (json/csv). Сервер пишет результат на диск, в диалог возвращает summary. Для get_candles и get_instruments_by_type это включает выкачивание полного периода/каталога чанками. Запись возможна строго внутри корня выгрузок.

Ограничения BCS Trade API

  • Нет истории денежных операций (полученные дивиденды, комиссии, пополнения) — только биржевые сделки. XIRR и налоговые отчёты поэтому невозможны.

  • Нет песочницы.

  • Один токен = один счёт (несколько счетов — несколько инстансов сервера).

  • Списки заявок/сделок — только с 26.01.2026.

Disclaimer

Не является индивидуальной инвестиционной рекомендацией. Все торговые решения вы принимаете самостоятельно. place_order оперирует реальными деньгами — используйте BCS_ALLOW_TRADING=true осознанно и держите подтверждение сделок включённым.

License

Apache 2.0

Available Tools

15 tools
find_instrumentFind InstrumentsA
Read-onlyIdempotent

Instrument cards by tickers (batch) or ISINs: name, type, boards (classCode/exchange — classCode is needed by candles/orders), lot size, ISIN, issuer; for bonds — face value, maturity, coupon rate/frequency, accrued interest; for stocks — dividend yield, sector, EPS growth, credit rating, BCS score. Start here to resolve a ticker before other calls. By default one merged card per instrument is returned (primary board; other listings in otherBoards; off-exchange rows flagged offExchange) — pass allBoards=true for the raw per-board cards.

Inputs: isins, tickers, allBoards, outputPath, +1 more.

get_candlesGet CandlesA
Read-onlyIdempotent

OHLCV candles. timeFrame: M1/M5/M15/M30/H1/H4/D/W/MN. The API caps one request at 1000 bars; inline calls return the most recent ~1000 TRADING bars of the range (truncated flag set when the range was not fully covered). Pass outputPath to fetch the FULL period via chunked requests (streamed to disk, deduplicated, with progress). Bond prices are quoted in % of face value, not currency.

Inputs: ticker (required), to, from, classCode, +3 more.

get_discountsGet Instrument DiscountsA
Read-onlyIdempotent

Margin discount rates per instrument from the marginal-indicators service. The API exposes discountLong only (no short rates), and values are raw BCS coefficients — observed as 1 for every instrument, so verify against the web cabinet before relying on them. Optional tickers filter is applied client-side.

Inputs: tickers, outputPath, outputFormat.

get_instruments_by_typeGet Instruments By TypeA
Read-onlyIdempotent

Tradable instruments of a type, paginated (page/size, max 100 per page). Pass outputPath to fetch ALL pages into a file; without it a single page is returned inline. baseAssetTicker is required for type=OPTIONS.

Inputs: type (required), page, size, outputPath, +2 more.

get_limitsGet LimitsA
Read-onlyIdempotent

Account limits: money limits per currency with computed free (= quantity − locked, summarized in freeByCurrency), securities (depo) limits, futures holdings and limits. Note: the API returns a start-of-day snapshot (see loadDate) in a single T365 slice — not intraday. Zero rows are hidden unless includeZero=true.

Inputs: outputPath, includeZero, outputFormat.

get_order_bookGet Order BookA
Read-onlyIdempotent

Order book (L2 depth of market) for one instrument: bids/asks with prices and quantities, total volumes. Bond prices are quoted in % of face value, not currency. Outside the trading session the API may report 404 "no data".

Inputs: ticker (required), classCode, outputPath, outputFormat.

get_ordersSearch OrdersA
Read-onlyIdempotent

Your orders on the account (data since 2026-01-26): ticker, side, type, quantity/filled, price, orderStatus (cancelled/filled/active), timestamps. Paginated (page/size), optional date and ticker filters; with outputPath ALL pages are dumped to a file. Orders rejected before reaching the exchange do NOT appear here — check them via get_order_status by client UUID.

Inputs: to, from, page, size, +3 more.

get_order_statusGet Order StatusA
Read-onlyIdempotent

Status of one order by ID. orderIdType 1 = client UUID (from place_order), 2 = exchange order number in the form YYMMDD-CLASSCODE-NUMBER with a 6-digit date (e.g. 260501-TQBR-79628540663).

Inputs: orderId (required), outputPath, orderIdType, outputFormat.

get_portfolioGet PortfolioA
Read-onlyIdempotent

Portfolio of the account bound to the token: every position (securities, money, metals) with quantity, average/current price, value in RUB/USD/EUR, unrealized and daily P&L, portfolio share, accrued interest for bonds. Includes totals by instrument type. The API reports each position once per settlement term (T0/T1/T2/T365) — by default a single slice is returned and totals cover only it; term=all returns the raw duplicates (totals then count every position several times). csv output writes the positions array.

Inputs: term, outputPath, outputFormat.

get_quotesGet QuotesA
Read-onlyIdempotent

Real-time quotes for up to 100 instruments: bid/offer, last price, day open/close/high/low, change. classCode is resolved via find_instrument when omitted. Bond prices are quoted in % of face value, not currency. Note: your own positions already carry currentPrice in get_portfolio.

Inputs: tickers (required), classCodes, outputPath, outputFormat.

get_recent_tradesGet Recent TradesA
Read-onlyIdempotent

Anonymized recent trades feed for one instrument: time, side, price, quantity, volume. Returns the newest limit trades, fetched hour-by-hour backwards from to (the BCS backend caps one request at a 1-hour period and ~4 MB response). Optional from/to select an explicit window. IMPORTANT: the API serves trades of the CURRENT UTC DAY only (from 00:00 UTC = 03:00 MSK) — earlier window starts are clamped, yesterday is unavailable. Records carry no trade id: identical rows within the same second are genuine distinct trades, not duplicates. Pass outputPath to dump a period (default: the whole current UTC day) to a file via hour-by-hour windows. Bond prices are quoted in % of face value, not currency.

Inputs: ticker (required), to, from, limit, +3 more.

get_server_infoGet Server InfoA
Read-onlyIdempotent

Server diagnostics for support/feedback reports: version, runtime, mode flags (trading/confirmation), output root. No broker API calls, never includes tokens.

Inputs: no named parameters.

get_tradesSearch TradesA
Read-onlyIdempotent

Your executed trades on the account (data since 2026-01-26): ticker, side, quantity, price, volume, trade time (tradeDateTime, MSK). Paginated (page/size), optional date and ticker filters; with outputPath ALL pages are dumped to a file. Note: trades only — cash operations (dividends received, fees, deposits) are not available in BCS Trade API.

Inputs: to, from, page, size, +3 more.

get_trading_scheduleGet Trading ScheduleA
Read-onlyIdempotent

Trading sessions of an instrument for the current day: session types with start/end times in MSK (+03:00), sorted. Intervals with tradingSessionStatus=OPEN are the periods when trading is on.

Inputs: ticker (required), classCode, outputPath, outputFormat.

get_trading_statusGet Trading StatusA
Read-onlyIdempotent

Current trading session status per instrument: session type, OPEN/CLOSE, time of the next status change. Each row is cross-checked against today's schedule; on mismatch a warning + scheduleSaysNow field is added (the upstream status endpoint has been observed reporting CLOSE during an open evening session).

Inputs: tickers (required), classCodes, outputPath, outputFormat.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4/5.0

    Scored across 15 tools

    Disambiguation5/5

    Each tool targets a distinct aspect of trading: instrument lookup, candles, order book, quotes, trades, orders, portfolio, etc. Descriptions clearly differentiate them, with no overlapping purposes.

    Naming Consistency4/5

    All but one tool use the 'get_' prefix followed by a noun, which is consistent. 'find_instrument' breaks this pattern, and 'get_instruments_by_type' uses a non-standard suffix, but overall the pattern is clear.

    Tool Count5/5

    15 tools is well-scoped for a trading API server, covering a wide range of necessary functionality without being excessive.

    Completeness2/5

    The server lacks fundamental trading actions: there is no tool to place or cancel orders. While it provides read access to orders and trades, users cannot act, which is a significant gap for a trading server.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides AI models with secure access to Interactive Brokers trading data and functionality, enabling account management, market data retrieval, and trading operations through natural language interactions.
      18
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Connects a brokerage account to AI assistants, enabling portfolio queries, order management, and market data access through natural language.
      MIT
    • F
      license
      Not graded
      quality
      C
      maintenance
      Enables AI assistants to research a T-Invest brokerage account, screen instruments, analyze portfolio yield and risk, build rebalance plans, and optionally preview or submit gated limit orders.
      1
      -
    • A
      license
      A
      quality
      C
      maintenance
      Enables AI assistants to access Saxo Bank portfolio data, account balances, positions, orders, transactions, and market data such as instruments, quotes, and charts. It is read-only by default, with trading tools available only when explicitly enabled.
      10
      MIT