schwab-mcp
Click on "Deploy 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., "@schwab-mcp show my Schwab account balances and a quote for AAPL"
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.
schwab-mcp
A production-ready, open-source Model Context Protocol (MCP) server for Charles Schwab Market Data v1 & Trader v1 APIs.
English | 简体中文
Direct async REST integration with Charles Schwab's official APIs (zero unofficial third-party Schwab SDK dependencies), supporting stocks, ETFs, and single/multi-leg options, built-in multi-layer risk guardrails, and two silky-smooth authentication modes designed for modern AI agents (Cursor, Codex, Claude Desktop, Claude Code, Antigravity, Windsurf, and any MCP client).
Why schwab-mcp?
Capability | Details |
Mode 1: Remote Hosted (Cloudflare-style OAuth 2.1) | Deploy once on a public HTTPS domain. Connect from Cursor / Codex / Claude with just a URL — native MCP OAuth 2.1 ( |
Mode 2: Local Any-Agent ( | Pass your Schwab App Key & Secret via |
Latest MCP Protocol ( | Stateless |
Defense-in-Depth Risk Guardrails |
|
Related MCP server: ReadyTrader-Stocks
Architecture
flowchart LR
subgraph Clients["AI Agents (Cursor / Codex / Claude / Antigravity)"]
C1["Mode 1: Remote Client (URL only)"]
C2["Mode 2: Local Client (uvx schwab-mcp)"]
end
subgraph Server["schwab-mcp (MCP SDK v2)"]
OAuth["MCP OAuth 2.1 Server\nDCR • PKCE • RFC 8707\n/schwab/callback"]
LocalAuth["In-Chat Auth Tools\nstart_auth • complete_auth\nLocal HTTPS Callback"]
Tools["30 MCP Tools + Resources + Prompts\nMarket Data • Accounts • Guarded Orders"]
Risk["RiskGuard + JSONL Audit\nDry-Run • Read-Only • USD Cap"]
end
subgraph Schwab["Charles Schwab Official APIs"]
SOAuth["OAuth 2.0\n/v1/oauth/*"]
MD["Market Data v1\n/marketdata/v1/*"]
TR["Trader API v1\n/trader/v1/*"]
end
C1 -->|Streamable HTTP + OAuth 2.1| OAuth
OAuth <-->|Upstream OAuth Proxy| SOAuth
OAuth --> Tools
C2 -->|stdio| LocalAuth
LocalAuth <-->|Loopback HTTPS or Paste| SOAuth
C2 --> Tools
Tools --> Risk
Risk --> TR
Tools --> MDPrerequisites
Register an application on the Charles Schwab Developer Portal.
Enable both Accounts and Trading Production and Market Data Production products.
Wait until your app status is
Ready for Use(not justApproved).Register your Callback URL in the portal:
Mode 2 (Local stdio):
https://127.0.0.1:8182Mode 1 (Remote OAuth 2.1):
https://schwab-mcp.your-domain.com/schwab/callback
Note on Schwab OAuth: Charles Schwab enforces OAuth 2.0 Authorization Code flow with a 30-minute access token (auto-refreshed transparently) and a hard 7-day refresh token lifetime. Re-authentication takes one click every 7 days.
Quick Start: Mode 2 — Pure Local Any-Agent (uvx schwab-mcp)
No cloning, no .env files, no terminal setup required. Add schwab-mcp to any MCP client with your Schwab Developer App credentials:
Cursor / Claude Desktop / Claude Code / Antigravity / Windsurf
{
"mcpServers": {
"schwab": {
"command": "uvx",
"args": ["schwab-mcp"],
"env": {
"SCHWAB_APP_KEY": "your_schwab_app_key",
"SCHWAB_APP_SECRET": "your_schwab_app_secret",
"SCHWAB_CALLBACK_URL": "https://127.0.0.1:8182"
}
}
}
}Or pass credentials directly via CLI arguments (for agents without env config):
uvx schwab-mcp \
--app-key "your_schwab_app_key" \
--app-secret "your_schwab_app_secret" \
--callback-url "https://127.0.0.1:8182"Smooth First-Time Authentication (Directly Inside Chat)
Simply ask your agent: "Check my Schwab positions and NVDA quote."
If not authenticated yet, the agent automatically calls
start_auth:Starts a temporary local HTTPS callback listener on
https://127.0.0.1:8182Opens the Charles Schwab login page in your default browser
Sign in and click Approve.
Automatic capture: Your token is saved immediately to
~/.config/schwab-mcp/token.json(0600permissions), shared across all local agents (Cursor, Codex, Claude, Antigravity).Fallback (headless / skip cert prompt): Copy the full redirected URL (
https://127.0.0.1:8182/?code=...) from the browser address bar and paste it in chat; the agent callscomplete_auth.
Pro tip (zero browser warnings on localhost): Run
mkcert 127.0.0.1 localhostonce and setSCHWAB_TLS_CERT_PATH&SCHWAB_TLS_KEY_PATH. See docs/authentication.md.
Quick Start: Mode 1 — Remote Hosted (Cloudflare-style One-Click OAuth 2.1)
Deploy schwab-mcp once on your VPS behind HTTPS (Caddy, Nginx, or Cloudflare Tunnel), then connect from Cursor, Codex, Claude, or any remote MCP client using only a URL — no API keys on client devices, no copy-pasting callback URLs, and zero certificate warnings.
1. Start the Server (Docker Compose + Auto-HTTPS Caddy)
cp .env.example .env
# Edit .env:
# SCHWAB_APP_KEY=...
# SCHWAB_APP_SECRET=...
# MCP_PUBLIC_URL=https://schwab-mcp.your-domain.com
# MCP_PUBLIC_DOMAIN=schwab-mcp.your-domain.com
docker compose up -dOr run directly without Docker:
uvx schwab-mcp serve \
--host 0.0.0.0 \
--port 8765 \
--public-url https://schwab-mcp.your-domain.comSCHWAB_CALLBACK_URL automatically defaults to https://schwab-mcp.your-domain.com/schwab/callback (register this exact URL in Schwab Developer Portal).
2. Connect from Any MCP Client (URL Only!)
{
"mcpServers": {
"schwab": {
"url": "https://schwab-mcp.your-domain.com/mcp"
}
}
}When you connect, Cursor / Codex / Claude automatically detects MCP OAuth 2.1, shows a Connect / Authorize button, redirects you to Charles Schwab login, exchanges tokens server-side, and connects you immediately. See docs/deployment.md for Caddy, Nginx, and Cloudflare Tunnel recipes.
Available Tools, Resources & Prompts
MCP Tools (30 Tools with ToolAnnotations)
Category | Tools |
Authentication (3) |
|
Market Data v1 (7) |
|
Accounts & Orders (7) |
|
Risk & Helpers (2) |
|
Guarded Execution (11) |
|
MCP Resources
schwab://auth/status— Live OAuth 2.0 token health & TTLschwab://risk/config— Active risk guardrailsschwab://accounts— Linked accounts overview
MCP Prompts
safe_order_checklist— Pre-flight verification workflow before live tradesanalyze_position— Position PnL, concentration, and exit protection reviewoption_chain_review— Expiration, IV, liquidity, and Greeks analysis
CLI Reference
# Mode 2: Start local stdio MCP server (default)
schwab-mcp
# Mode 1: Start remote Streamable HTTP server with MCP OAuth 2.1
schwab-mcp serve --public-url https://schwab-mcp.example.com --host 0.0.0.0 --port 8765
# Local CLI authentication helpers
schwab-mcp auth login # Opens browser + captures callback automatically (or --no-auto-callback)
schwab-mcp auth status # Inspect token TTL & warnings
schwab-mcp auth refresh # Manually refresh 30-min access token
schwab-mcp auth logout # Delete local token
# Diagnostics (credentials, callback URL, TLS cert, token health, risk config)
schwab-mcp doctorRisk Guardrails & Live Trading Safety
By default, SCHWAB_DRY_RUN=true is enforced globally so no real money order can ever be submitted accidentally:
Global Dry-Run Guard (
SCHWAB_DRY_RUN=true): Intercepts all order submissions and runs Schwab's officialpreviewOrderendpoint instead. Cannot be overridden by any AI tool parameter.Global Read-Only Guard (
SCHWAB_READ_ONLY=true): Blocks all live order placements, replacements, and cancellations.Notional Cap (
SCHWAB_MAX_ORDER_USD, default$5,000): Estimates notional value (including live quote lookups for market/trailing orders and smart sizing for OCO/Bracket strategies) and rejects oversized orders.Symbol Allowlist / Blocklist: Restrict trading with
SCHWAB_ALLOWED_SYMBOLSandSCHWAB_BLOCKED_SYMBOLS(applies to both equity and underlying symbols of options).Explicit Live Confirmation + Audit Trail: Even with
SCHWAB_DRY_RUN=false, live actions requireconfirm_live=True, and every attempt is logged totrade_audit.jsonl(0600).
See docs/security.md for full details.
Development
git clone https://github.com/HGZ-20/schwab-mcp.git
cd schwab-mcp
uv sync --all-extras
uv run pytest -vDisclaimer
This project is an independent, community-maintained open-source MCP server and is not affiliated with, endorsed by, or officially supported by Charles Schwab & Co., Inc. Trading equities and options involves substantial financial risk. Always test thoroughly in SCHWAB_DRY_RUN=true mode before enabling live execution.
License
Available Tools
30 toolsbuild_option_symbolBuild OCC Option SymbolARead-onlyIdempotent
Build a 21-character OCC option symbol required by Charles Schwab.
Args: underlying: Underlying ticker (e.g. 'AAPL', 'SPY'). expiration: Expiration date in 'YYYY-MM-DD' or 'YYMMDD' format. contract_type: 'CALL' (or 'C') or 'PUT' (or 'P'). strike: Option strike price (e.g. 200.0 or 182.5).
Inputs: strike (required), expiration (required), underlying (required), contract_type (required). Returns: object
cancel_orderCancel Open OrderBDestructive
Cancel an existing open order by order_id (respects SCHWAB_READ_ONLY and SCHWAB_DRY_RUN).
Inputs: order_id (required), account, confirm_live. Returns: object
complete_authComplete Schwab AuthenticationA
Complete Charles Schwab OAuth 2.0 login by exchanging a callback URL or authorization code.
Args: callback_url: The full redirected URL from your browser address bar (e.g. 'https://127.0.0.1:8182/?code=...&session=...') or the raw authorization code.
Inputs: callback_url (required). Returns: object
get_account_detailsGet Account DetailsARead-onlyIdempotent
Fetch balances, buying power, margin status, and positions for a specific Schwab account.
Args: account: Account number, last 4 digits, or encrypted hashValue (optional if only 1 account or default set). include_positions: Include open positions. raw: Return full unmodified Schwab JSON payload.
Inputs: raw, account, include_positions. Returns: object
get_auth_statusGet Schwab Auth StatusARead-onlyIdempotent
Check Charles Schwab OAuth 2.0 token health and remaining TTL (30m access & 7d refresh).
Inputs: no named parameters. Returns: object
get_market_hoursGet Market HoursARead-onlyIdempotent
Check exchange trading hours and holiday status for specified markets.
Args: markets: Comma-separated list from 'equity', 'option', 'bond', 'future', 'forex'. date: Optional YYYY-MM-DD date (defaults to today).
Inputs: date, markets. Returns: object
get_market_moversGet Market MoversBRead-onlyIdempotent
Fetch top market movers for an index or market segment.
Args: index: '$DJI', '$COMPX', '$SPX', 'NYSE', 'NASDAQ', 'OTCBB', 'INDEX_ALL', 'EQUITY_ALL', 'OPTION_ALL', 'OPTION_PUT', or 'OPTION_CALL'. sort: 'VOLUME', 'TRADES', 'PERCENT_CHANGE_UP', or 'PERCENT_CHANGE_DOWN'. frequency: Lookback minutes: 0, 1, 5, 10, 30, or 60.
Inputs: sort, index, frequency. Returns: object
get_option_chainGet Option ChainARead-onlyIdempotent
Fetch real-time option chain (calls/puts, strikes, bid/ask, IV, OI, Greeks).
Args: symbol: Underlying ticker (e.g. 'NVDA', 'SPY'). contract_type: 'ALL', 'CALL', or 'PUT'. strike_count: Strikes above and below ATM (default 8). range_filter: 'ALL', 'ITM', 'NTM', 'OTM', 'SAK', 'SBK', 'SNK'. from_date: Filter expirations from YYYY-MM-DD. to_date: Filter expirations up to YYYY-MM-DD. strike: Optional single strike price filter. strategy: 'SINGLE', 'ANALYTICAL', 'COVERED', 'VERTICAL', 'CALENDAR', 'STRANGLE', 'STRADDLE', etc. include_underlying_quote: Include underlying spot quote. compact: Return clean contract summaries (default True) or full raw Schwab JSON.
Inputs: symbol (required), strike, compact, to_date, +6 more. Returns: object
get_option_expirationsGet Option ExpirationsARead-onlyIdempotent
List available option expiration dates, DTE, and expiration types for an underlying symbol.
Inputs: symbol (required). Returns: object
get_orderGet Order DetailsBRead-onlyIdempotent
Fetch full details and execution status of a single order by order_id.
Inputs: order_id (required), account. Returns: object
get_ordersGet OrdersARead-onlyIdempotent
Query orders for a specific account or across all accounts (pass account='ALL').
Args: account: Account number, last 4 digits, hashValue, 'ALL', or None for default account. days_back: Lookback window in days when from_time is omitted (default 7, Schwab max 60). from_time: Optional ISO-8601 start timestamp (e.g. '2026-11-15T00:00:00Z'). to_time: Optional ISO-8601 end timestamp. status: Optional filter: 'WORKING', 'FILLED', 'CANCELED', 'EXPIRED', 'PENDING_ACTIVATION', 'REJECTED', etc. max_results: Maximum orders to return (default 50).
Inputs: status, account, to_time, days_back, +2 more. Returns: object
get_positionsGet Open PositionsARead-onlyIdempotent
Fetch all open equity and option positions for an account with PnL and market values.
Inputs: account. Returns: object
get_price_historyGet Historical Price BarsARead-onlyIdempotent
Fetch historical OHLCV candlestick price bars for a stock, ETF, or index.
Args: symbol: Ticker symbol (e.g. 'AAPL', 'SPY'). period_type: 'day', 'month', 'year', or 'ytd'. period: Number of periods (day: 1,2,3,4,5,10; month: 1,2,3,6; year: 1,2,3,5,10,15,20; ytd: 1). Omit (set None) if specifying start_date/end_date. frequency_type: 'minute' (for day), 'daily', 'weekly', or 'monthly'. frequency: Candle interval (minute: 1,5,10,15,30; daily/weekly/monthly: 1). start_date: Optional start date ('YYYY-MM-DD', ISO-8601 UTC, or epoch ms). end_date: Optional end date ('YYYY-MM-DD', ISO-8601 UTC, or epoch ms). need_extended_hours: Include pre-market and after-hours candles. need_previous_close: Include previous close metadata. limit: Maximum number of most-recent candles returned (default 120).
Inputs: symbol (required), limit, period, end_date, +6 more. Returns: object
get_quotesGet Real-Time QuotesARead-onlyIdempotent
Fetch real-time market quotes for one or multiple stocks, ETFs, indexes, or OCC options.
Args: symbols: List of symbols (e.g. ['AAPL', 'NVDA', '$SPX']) or comma-separated string. fields: Schwab quote fields (default 'quote,reference,extended'). indicative: Include indicative quotes for eligible symbols. compact: Return concise AI-friendly quote fields (default True) or full Schwab payload.
Inputs: symbols (required), fields, compact, indicative. Returns: object
get_risk_configGet Risk Guardrails ConfigARead-onlyIdempotent
Inspect active trading risk guardrails (dry_run, read_only, max_order_usd, symbol rules).
Inputs: no named parameters. Returns: object
get_transactionsGet Account TransactionsBRead-onlyIdempotent
Fetch account transaction history (trades, dividends, option assignments, cash transfers).
Args: account: Account number, last 4 digits, or hashValue. days_back: Lookback window in days when start_date is omitted (default 30). start_date: Optional start date ('YYYY-MM-DD' or ISO-8601). end_date: Optional end date ('YYYY-MM-DD' or ISO-8601). types: Schwab transaction type: 'TRADE', 'RECEIVE_AND_DELIVER', 'DIVIDEND_OR_INTEREST', 'ACH_RECEIPT', 'ACH_DISBURSEMENT', 'CASH_RECEIPT', 'CASH_DISBURSEMENT', 'ELECTRONIC_FUND', 'WIRE_OUT', 'WIRE_IN', 'JOURNAL', 'MEMORANDUM', 'MARGIN_CALL', 'MONEY_MARKET', 'SMA_ADJUSTMENT'. symbol: Optional ticker symbol filter.
Inputs: types, symbol, account, end_date, +2 more. Returns: object
get_user_preferencesGet User PreferencesARead-onlyIdempotent
Fetch Schwab user preferences (account nicknames and streamer connection metadata).
Inputs: no named parameters. Returns: object
list_accountsList Schwab AccountsARead-onlyIdempotent
List all linked Schwab accounts with encrypted hashes, balances, buying power, and positions.
Inputs: include_positions. Returns: object
place_bracket_orderPlace Bracket OrderCDestructive
Place (or dry-run preview) a Bracket order (entry triggers OCO Take-Profit + Stop-Loss).
Inputs: symbol (required), quantity (required), take_profit_price (required), account, +15 more. Returns: object
place_equity_orderPlace Equity / ETF OrderADestructive
Place (or dry-run preview) a stock/ETF order with built-in risk checks.
Args: symbol: Equity or ETF ticker (e.g. 'AAPL', 'SPY'). instruction: 'BUY', 'SELL', 'SELL_SHORT', or 'BUY_TO_COVER'. quantity: Number of shares (> 0). order_type: 'MARKET', 'LIMIT', 'STOP', 'STOP_LIMIT', 'MARKET_ON_CLOSE', or 'LIMIT_ON_CLOSE'. price: Limit price (required for LIMIT, STOP_LIMIT, and LIMIT_ON_CLOSE). stop_price: Stop trigger price (required for STOP and STOP_LIMIT). duration: 'DAY', 'GOOD_TILL_CANCEL', 'FILL_OR_KILL', or 'IMMEDIATE_OR_CANCEL'. session: 'NORMAL', 'AM' (pre-market), 'PM' (after-hours), or 'SEAMLESS' (extended hours require LIMIT+DAY). account: Optional account number, last 4 digits, or hashValue. dry_run: Force dry-run/preview mode (note: global SCHWAB_DRY_RUN=true cannot be overridden). confirm_live: Must be True to submit a real order when SCHWAB_DRY_RUN=false.
Inputs: symbol (required), quantity (required), instruction (required), price, +7 more. Returns: object
place_oco_orderPlace OCO Exit OrderBDestructive
Place (or dry-run preview) an OCO (One-Cancels-Other) order for Take-Profit + Stop-Loss.
Inputs: symbol, account, dry_run, duration, +11 more. Returns: object
place_option_orderPlace Single-Leg Option OrderBDestructive
Place (or dry-run preview) a single-leg option order with built-in risk checks.
Provide EITHER option_symbol (21-char OCC symbol from get_option_chain) OR
all four of (underlying, expiration, contract_type, strike).
Inputs: quantity (required), instruction (required), price, strike, +10 more. Returns: object
place_option_spread_orderPlace Multi-Leg Option Spread OrderBDestructive
Place (or dry-run preview) a multi-leg option spread or covered strategy order (2-4 legs).
Inputs: legs (required), price, account, dry_run, +4 more. Returns: object
place_raw_orderPlace Custom Raw OrderCDestructive
Place (or dry-run preview) any custom Schwab Trader API v1 order JSON payload.
Inputs: order_payload (required), account, dry_run, confirm_live. Returns: object
place_trailing_stop_orderPlace Trailing Stop OrderBDestructive
Place (or dry-run preview) a TRAILING_STOP or TRAILING_STOP_LIMIT order for equity or option.
Inputs: quantity (required), instruction (required), stop_price_offset (required), strike, +16 more. Returns: object
place_trigger_orderPlace 1st-Triggers-2nd OrderCDestructive
Place (or dry-run preview) a 1st-Triggers-2nd (TRIGGER) conditional order.
Inputs: primary_order (required), triggered_orders (required), account, dry_run, +1 more. Returns: object
preview_raw_orderPreview Custom Raw OrderBRead-onlyIdempotent
Call Schwab's official previewOrder endpoint directly without submitting a live order.
Inputs: order_payload (required), account. Returns: object
replace_orderReplace Open OrderCDestructive
Replace/modify an existing open order with a new Schwab order payload.
Inputs: order_id (required), new_order_payload (required), account, dry_run, +1 more. Returns: object
search_instrumentsSearch Instruments & FundamentalsBRead-onlyIdempotent
Search instruments by ticker/description or retrieve fundamental company metrics.
Args: symbol: Ticker or search keyword (e.g. 'AAPL', 'TSLA'). projection: 'fundamental', 'symbol-search', 'symbol-regex', 'desc-search', 'desc-regex', or 'search'.
Inputs: symbol (required), projection. Returns: object
start_authStart Schwab AuthenticationAIdempotent
Start Charles Schwab OAuth 2.0 login directly from your AI agent (Mode 2 local flow).
Supports MCP 2026-07-28 URL-mode elicitation (prompting the client UI natively for
out-of-band OAuth so credentials never touch the LLM context), plus automatic local
HTTPS loopback callback capture and manual URL-paste fallback via complete_auth.
Args: open_browser: Automatically open the Schwab login URL in your desktop browser when client URL-mode elicitation is unavailable (default True). auto_capture: Start a temporary local HTTPS listener to capture the callback automatically (default True). wait_seconds: Optional seconds to wait for browser completion before returning (0-120, default 0).
Inputs: auto_capture, open_browser, wait_seconds. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 30 tools
Most tools target a clearly distinct resource+action (quotes vs. price history vs. option chain vs. transactions), and the nine place_* order tools each map to a well-defined order type. Minor overlap exists between preview_raw_order and place_raw_order (which itself supports dry-run preview), and between the generic raw order tool and the typed equity/option order tools, which could cause occasional misselection.
Nearly every tool follows a strict snake_case verb_noun pattern (get_quotes, place_equity_order, cancel_order, build_option_symbol), with a predictable cluster of place_*/get_*/list_* variants. The auth trio (start_auth, complete_auth, get_auth_status) uses a consistent noun-first sub-convention that stays readable.
At 30 tools the surface is heavy, and the bulk comes from nine order-placement variants plus three auth tools. Each does earn a place given the breadth of the Schwab trading domain, but the set is larger than the typical well-scoped range and borders on overload for an agent choosing among order types.
Core lifecycle is well covered: account/position reads, market data, option chains, order preview/place/replace/cancel, transactions, risk config, and OAuth management. Gaps are modest — no watchlist management and no streaming/real-time subscription tools, which agents must work around with quote polling.
Maintenance
Related MCP Connectors
Connect brokerage accounts to AI assistants: holdings, orders, asset lookup, and approved trading.
Unified financial infrastructure connecting AI agents directly to trade live/demo brokerage accounts, Web3 non-custodial wallets, real-time market data across equities, ETFs, crypto, forex, options, DeFi swaps, and prediction markets, institutional research feeds, and algorithmic strategy backtesters.
AI agents backtest, paper trade and live trade via your broker. Free to connect; OAuth.
Connect AI agents to bank accounts, transactions, balances, and investments.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to securely interact with Charles Schwab accounts through OAuth authentication, providing access to account balances, real-time market quotes, options chains, transaction history, order management, and comprehensive market data.1MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to execute stock trading operations with built-in risk controls and human approval workflows. Supports paper trading simulation, real brokerage integration (Alpaca, Tradier), backtesting, sentiment analysis, and portfolio management while maintaining strict separation between AI intelligence and trade execution.MIT
- FlicenseNot gradedqualityDmaintenanceEnables LLMs to retrieve real-time stock and options market data through the E\*TRADE API using natural language. It features secure OAuth 1.0 authentication, persistent token management, and comprehensive support for stock quotes, options chains, and Greeks.2-
- FlicenseNot gradedqualityDmaintenanceEnables AI models to manage Robinhood portfolios, execute trades, and run automated trading bots with stop-loss/take-profit monitoring.1-