Skip to main content
Glama

schwab-mcp

MCP-сервер, который подключается к брокерскому API Charles Schwab, а также плагин для Claude Code с навыками, позволяющими сократить количество запросов к LLM при вызове инструментов MCP.

Что это делает

MCP-сервер — использует Schwab API через schwabdev и предоставляет 18 инструментов через Streamable HTTP:

Категория

Инструменты

Сессия

list_accounts, set_active_account, get_active_account

Рыночные данные

get_quotes, get_option_chain, get_option_expirations, get_price_history, get_movers, get_market_hours

Счета

get_account, get_transactions, get_transaction, get_preferences

Ордера

list_orders, list_all_orders, get_order, place_order, cancel_order, replace_order, preview_order

Инструменты

search_instruments, get_instrument

Плагин Claude Code — предоставляет шесть навыков (schwab:account, schwab:orders, schwab:quotes, schwab:market, schwab:instruments, schwab:chart-orders), которые заранее задают для Claude правила выбора инструментов, форматы параметров и шаблоны безопасности. Это исключает необходимость лишнего взаимодействия с LLM для определения того, какой инструмент вызвать и как это сделать.

Related MCP server: KiteMCP

Предварительные требования

  • Python 3.11+

  • Учетная запись Schwab Developer с одобренным приложением (вам понадобятся ключ приложения и секрет)

Настройка

# Clone and install
git clone <repo-url> && cd schwab-mcp
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"

# Add credentials
cp .env.example ~/.schwab-mcp/.env
# Edit ~/.schwab-mcp/.env with your Schwab app key and secret

# Authenticate (opens browser for OAuth)
schwab-mcp auth

# Start the server
schwab-mcp serve

По умолчанию сервер прослушивает http://127.0.0.1:8099/mcp. Переопределите это с помощью переменных окружения SCHWAB_MCP_HOST и SCHWAB_MCP_PORT.

Использование с Claude Code

Установите каталог плагина, чтобы Claude Code подхватил подключение MCP и навыки:

claude plugin add ./plugin

Это регистрирует:

  • Подключение к MCP-серверу (через plugin/.mcp.json)

  • Шесть навыков, которые направляют Claude в использовании каждой категории инструментов

  • Хук завершения сессии, который очищает временные файлы

После установки спрашивайте Claude о чем-то вроде:

  • "What are my account positions?"

  • "Get me a quote for AAPL"

  • "Place a limit order to buy 10 shares of MSFT at $400"

  • "Show me today's top movers on the S&P 500"

  • "Chart my filled orders for SPX today"

Пример: Размещение лимитного ордера

You: Buy 100 shares of SPY with limit order at current median bid-ask spread.
     This order should be canceled if it weren't filled before 3/30 12PM ET.

Claude: I need to get SPY's current bid-ask spread first, then build the order.
        Let me fetch the quote.

        [calls get_quotes for SPY]

        Got the quote. Here's the current SPY pricing:
        - Bid: $632.70
        - Ask: $633.00
        - Midpoint: $632.85

        Regarding cancellation by 3/30 12PM ET — Schwab doesn't support
        "cancel at a specific time." I'll use DAY duration (valid through
        market close on 3/30). You'd need to manually cancel at noon if
        unfilled.

        [calls place_order with confirmed=False — dry run]

        | Field      | Value                      |
        |------------|----------------------------|
        | Action     | BUY                        |
        | Symbol     | SPY                        |
        | Quantity   | 100 shares                 |
        | Order Type | LIMIT                      |
        | Price      | $632.85 (bid-ask midpoint) |
        | Duration   | DAY                        |
        | Session    | NORMAL                     |

        Shall I submit this order?

You: yes

Claude: [calls place_order with confirmed=True]

        Order submitted successfully.

Навык направил Claude на следующие действия:

  1. Получить котировку для расчета средней цены

  2. Сначала выполнить пробный запуск ордера (confirmed=False) и показать сводку

  3. Отправить ордер (confirmed=True) только после явного одобрения пользователя

Пример: Построение графика исполненных ордеров

You: Plot my last week's credit spread trades

Claude: [fetches filled orders for Mar 22-28]

        39 credit spread orders on SPXW last week — 30 vertical spreads
        and 9 iron condors across 5 trading days.

        [fetches 15-minute SPX candles for the same range]
        [runs chart_orders.py with candles + orders data]

        Candles: 130, Orders: 62 (12 buy, 11 sell, 39 spread)
        Interactive chart saved to plugin/skills/chart-orders/chart.html

Пример графика ордеров

Навык направил Claude на следующие действия:

  1. Получить исполненные ордера за указанный диапазон дат и определить базовый актив (SPXW/SPX)

  2. Получить 15-минутные свечи (подходящие для многодневного диапазона)

  3. Запустить скрипт построения графика для создания интерактивного графика Plotly с маркерами ордеров, разделителями дней и всплывающими подсказками

Безопасность

Операции изменения состояния (place_order, cancel_order, replace_order) используют двухэтапный шаблон подтверждения. Первый вызов — это пробный запуск, который показывает, что произойдет; вы должны явно подтвердить выполнение.

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

src/schwab_mcp/
  server.py          # CLI entry point (serve / auth commands)
  client.py          # Schwab client init, OAuth tokens, state persistence
  _mcp.py            # FastMCP server instance
  logging_config.py  # Rotating log handler with credential redaction
  tools/             # MCP tool implementations
    session.py       # Account listing and selection
    market_data.py   # Quotes, options, price history, movers
    accounts.py      # Account details, transactions, preferences
    orders.py        # Order CRUD with dry-run safety
    instruments.py   # Symbol/CUSIP lookup

plugin/
  .mcp.json                  # MCP server connection config
  .claude-plugin/plugin.json # Plugin metadata
  hooks/hooks.json           # Session cleanup hook
  skills/                    # Claude Code skill definitions

Состояние и логи

Все состояние среды выполнения находится в ~/.schwab-mcp/:

Файл

Назначение

.env

API-учетные данные

tokens.db

OAuth-токены (автоматически обновляются через schwabdev)

state.json

Выбор активного счета

schwab-mcp.log

Ротируемый лог (5 МБ, 3 резервные копии, учетные данные скрыты)

Большие ответы инструментов (цепочки опционов, длинные списки транзакций) записываются в /tmp/schwab-mcp/ и автоматически удаляются при завершении сессии Claude Code.

Разработка

# Run tests
pytest

# Run with debug logging
LOG_LEVEL=DEBUG schwab-mcp serve

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    F
    maintenance
    A Model Context Protocol server that enables AI assistants like Claude to securely interact with Charles Schwab accounts and market data through the official Schwab API.
    75
    -
  • F
    license
    Not graded
    quality
    D
    maintenance
    A command-based MCP server that enables programmatic stock trading on Zerodha through natural language interfaces like Claude, allowing users to buy and sell stocks via API calls.
    -
  • F
    license
    Not graded
    quality
    D
    maintenance
    MCP server exposing Tradier brokerage tools to Claude, enabling account balance checks, position management, order operations, and market data queries.
    -
  • A
    license
    A
    quality
    F
    maintenance
    MCP server for Interactive Brokers API integration, enabling account management, trading, market data, and short selling analysis through Claude.
    8
    35
    MIT