schwab-mcp
schwab-mcp
MCP-сервер, который подключается к брокерскому API Charles Schwab, а также плагин для Claude Code с навыками, позволяющими сократить количество запросов к LLM при вызове инструментов MCP.
Что это делает
MCP-сервер — использует Schwab API через schwabdev и предоставляет 18 инструментов через Streamable HTTP:
Категория | Инструменты |
Сессия |
|
Рыночные данные |
|
Счета |
|
Ордера |
|
Инструменты |
|
Плагин 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 на следующие действия:
Получить котировку для расчета средней цены
Сначала выполнить пробный запуск ордера (
confirmed=False) и показать сводкуОтправить ордер (
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 на следующие действия:
Получить исполненные ордера за указанный диапазон дат и определить базовый актив (SPXW/SPX)
Получить 15-минутные свечи (подходящие для многодневного диапазона)
Запустить скрипт построения графика для создания интерактивного графика 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/:
Файл | Назначение |
| API-учетные данные |
| OAuth-токены (автоматически обновляются через schwabdev) |
| Выбор активного счета |
| Ротируемый лог (5 МБ, 3 резервные копии, учетные данные скрыты) |
Большие ответы инструментов (цепочки опционов, длинные списки транзакций) записываются в /tmp/schwab-mcp/ и автоматически удаляются при завершении сессии Claude Code.
Разработка
# Run tests
pytest
# Run with debug logging
LOG_LEVEL=DEBUG schwab-mcp serveTool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Trading MCP server for AI agents, with live market data, account reads and controlled execution.
MCP server unifying ERPs, CRMs, APIs and knowledge base for Claude, ChatGPT and Gemini.
Multi-tenant FastMCP server for Charles Schwab brokerage data, monetized via DPYC Tollbooth
Connect Claude, ChatGPT, Codex, Claude Code or another MCP client to your real multi-broker investment portfolio. Fortunest tracks stocks, ETFs and crypto across brokers and exchanges; its MCP server lets your agent read holdings, returns, allocation, risk, trades and tax lots, calculated by Fortunest rather than guessed by the model. Reads run on their own; every change waits for your approval in the Fortunest app, and no tool places an order or moves money. Sign-in is OAuth 2.1 and needs Fortunest Pro (14-day trial, no card). A free demo that needs no account is listed as Fortunest demo.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA 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.86MIT
- FlicenseNot gradedqualityDmaintenanceA 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.-
- FlicenseNot gradedqualityDmaintenanceMCP server exposing Tradier brokerage tools to Claude, enabling account balance checks, position management, order operations, and market data queries.-
- AlicenseAqualityFmaintenanceMCP server for Interactive Brokers API integration, enabling account management, trading, market data, and short selling analysis through Claude.835MIT