ibkr-mcp
The ibkr-mcp server exposes an Interactive Brokers account (or an offline simulator) as a set of LLM-callable tools for account monitoring, market data, and risk-controlled order entry.
Check server status (
get_status): View the active backend (mock or live IB), connection state, trading enablement, account ID, and current risk limits.View account summary (
get_account_summary): Retrieve net liquidation value, cash balance, buying power, and P&L.View open positions (
get_positions): List all holdings with quantity, average cost, market value, and unrealized P&L.Get market quotes (
get_quote): Fetch a real-time bid/ask/last/mid price snapshot for any stock symbol.View open orders (
get_open_orders): See all working (unfilled) orders currently resting at the venue.View trade blotter (
get_trades): Review all executions and fills for the current session.Preview an order (
preview_order): Step 1 of the trading flow — validate a proposed BUY/SELL order (market or limit) against pre-trade risk limits without submitting it. Returns an estimated notional, risk decision (approved/rejected with reasons), and a single-useconfirmation_tokenif approved.Place an order (
place_order): Step 2 of the trading flow — submit a previously previewed order using itsconfirmation_token. The order is re-validated against risk limits at execution time before submission.Cancel an order (
cancel_order): Cancel a working order by its order ID.Robust risk management: All orders are subject to configurable pre-trade checks, including per-order quantity/notional caps, position notional caps, short-selling restrictions, optional symbol whitelists, and daily order count limits.
Flexible backend: Runs with an offline market simulator by default (zero setup required) or connects to a live IBKR paper/live account.
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., "@ibkr-mcp preview a buy order for 10 shares of 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.
ibkr-mcp — an LLM-driven trading agent for Interactive Brokers
A Model Context Protocol server that exposes an Interactive Brokers account — account data, market data, and order entry — as a set of tools an LLM agent (Claude Desktop, Claude Code, any MCP client) can call. It pairs that with a pre-trade risk engine and a two-step confirm-before-trade flow so an autonomous model can't fat-finger a live account.
The whole thing runs offline out of the box against a built-in market
simulator, so it's reviewable with zero setup — no TWS, no IB Gateway, no
network, not even the mcp package for the demo and tests.
python examples/demo_cli.py # full preview -> place -> blocked-order flow, offline
python tests/test_risk.py # 7 risk-engine tests
python tests/test_session.py # 6 session/safety-flow tests=== 5. Preview BUY 50 NVDA (risk check) ===
{
"symbol": "NVDA", "action": "BUY", "quantity": 50, "order_type": "MKT",
"reference_price": 167.95, "estimated_notional": 8397.5,
"risk": { "approved": true, "reasons": [] },
"trading_enabled": true,
"confirmation_token": "d2bfa616602b",
"token_expires_in_seconds": 120,
"next_step": "Call place_order('d2bfa616602b') to submit."
}
=== 6. Place order via confirmation token ===
{
"order_id": "1000", "symbol": "NVDA", "action": "BUY", "quantity": 50,
"status": "FILLED", "filled_quantity": 50, "avg_fill_price": 167.36,
"message": "Filled."
}
=== 9. Preview BUY 400 TSLA -- expect REJECT (over notional cap) ===
{
"symbol": "TSLA", "action": "BUY", "quantity": 400,
"estimated_notional": 99748.0,
"risk": {
"approved": false,
"reasons": [
"Order notional $99,748 exceeds per-order cap $20,000.",
"Resulting position notional $99,748 exceeds position cap $60,000."
]
},
"confirmation_token": null,
"next_step": "Order REJECTED by risk checks; not placeable."
}
=== 10. place_order with a bogus token -> guarded ===
{ "blocked": "Unknown or already-used confirmation token. Call preview_order first." }On the backends. The live
ib_asyncbackend (broker/ibkr.py) is fully implemented; the server simply defaults to the offline simulator so the project is reviewable with zero setup. Pointing it at a real IBKR paper account is a two-env-var change (IBKR_BACKEND=ib,IBKR_TRADING_ENABLED=true) — see Against a real (paper) IBKR account.
Why this design
Letting an LLM place trades is the interesting, dangerous part. Three decisions carry the design:
The agent never touches the broker SDK directly. Tools talk to a
TradingSession, which talks to aBrokerinterface. Two implementations sit behind that interface — a liveib_asyncbackend and an in-memory simulator — so the agent-facing contract is identical whether you're on a paper account or running offline.Trading is a two-step handshake, not one tool call. The model must
preview_order(...)first; that returns the live quote, the estimated notional, a risk decision, and — only if risk passes and trading is enabled — a single-useconfirmation_token. Onlyplace_order(token)submits. The order is re-validated against the risk limits at execution time, because price and position may have moved since the preview.Safe by default. With no configuration you get the
mockbackend with trading disabled (read-only). Going live is an explicit, multi-flag opt-in.
Related MCP server: IBKR TWS MCP Server
Architecture
MCP client (Claude)
│ stdio / JSON-RPC
▼
┌──────────────────┐ tool docstrings = the agent's contract
│ server.py │ get_status · get_account_summary · get_positions
│ (FastMCP tools) │ get_quote · get_open_orders · get_trades
└────────┬─────────┘ preview_order ──► place_order · cancel_order
▼
┌──────────────────┐ two-step order flow, single-use confirmation tokens,
│ session.py │ execution-time re-validation
└────┬───────────┬─┘
▼ ▼
┌─────────┐ ┌──────────────────┐
│ risk.py │ │ broker/ (Broker) │
│ pre- │ │ ├─ mock.py ◄── offline simulator (default)
│ trade │ │ └─ ibkr.py ◄── live ib_async → TWS / IB Gateway
│ checks │ └──────────────────┘
└─────────┘Everything except server.py (FastMCP) and broker/ibkr.py (ib_async) is pure
standard library, which is why the simulator and tests need no dependencies.
Tool catalog
Tool | Purpose |
| Backend, connection, trading on/off, active risk limits |
| Net liquidation, cash, buying power, P&L |
| Open positions with cost basis and unrealized P&L |
| Bid / ask / last / mid snapshot |
| Working (unfilled) orders |
| Execution blotter |
| Step 1 — risk-check an order, return a confirmation token |
| Step 2 — submit a previewed, re-validated order |
| Cancel a working order |
Risk controls (risk.py)
Enforced before any order is accepted, and again at execution time:
per-order quantity cap
per-order notional cap
resulting position notional cap
short-selling switch (off by default)
optional symbol whitelist
daily order count cap
All are configurable via environment variables (see .env.example).
Running it
Offline demo / tests (no install)
python examples/demo_cli.py
python tests/test_risk.py && python tests/test_session.pyAs an MCP server
pip install "mcp[cli]"
python -m ibkr_mcp.server # serves over stdioRegister it with an MCP client using examples/claude_desktop_config.example.json.
Against a real (paper) IBKR account
pip install ib_asyncLaunch TWS or IB Gateway with the API enabled, logged into a paper account (account id starts with
DU).Set the environment and run:
export IBKR_BACKEND=ib export IBKR_TRADING_ENABLED=true export IBKR_PORT=7497 # paper TWS export IBKR_ACCOUNT_ID=DUxxxxxxx python -m ibkr_mcp.server
Safety: keep
IBKR_TRADING_ENABLED=falsefor read-only analysis. Point at a paper account before ever enabling trades. The risk caps are the backstop, not the first line of defense — the read-only default is.
Layout
ibkr_mcp/
models.py dataclasses: Quote, Position, Order, Trade, AccountSummary
config.py env-driven Settings + RiskLimits (safe defaults)
risk.py pure pre-trade risk engine
session.py two-step order flow, token store, re-validation
server.py FastMCP tool layer (the agent contract)
broker/
base.py abstract Broker interface
mock.py offline market simulator
ibkr.py live ib_async backend
examples/ offline demo + MCP client config
tests/ risk + session/safety-flow testsLicense
MIT
Available Tools
9 toolscancel_orderA
Cancel a working order by its order_id (from get_open_orders).
Inputs: order_id (required).
get_account_summaryA
Return account net liquidation, cash, buying power and P&L.
Inputs: no named parameters.
get_open_ordersA
Return working (unfilled) orders currently resting at the venue.
Inputs: no named parameters. Returns: result
get_positionsA
Return all open positions with quantity, average cost, market price, market value and unrealized P&L.
Inputs: no named parameters. Returns: result
get_quoteB
Return a current bid/ask/last/mid snapshot for a stock symbol (e.g. AAPL).
Inputs: symbol (required).
get_statusA
Return server status: backend (mock/ib), connection, whether trading is enabled, the account id, and the active risk limits. Call this first to understand what the account can and cannot do.
Inputs: no named parameters.
get_tradesA
Return the executions/fills for this session (the trade blotter).
Inputs: no named parameters. Returns: result
place_orderA
STEP 2 of 2 for trading. Submit the order previously approved by
preview_order, identified by its confirmation_token. The order is
re-validated against risk limits at this moment before submission. Tokens are
single-use and expire. Returns the resulting order with its fill status.
Inputs: confirmation_token (required).
preview_orderA
STEP 1 of 2 for trading. Validate a proposed order against the risk limits
WITHOUT sending it. Returns the live quote, estimated notional, the risk
decision (approved + reasons), and -- only if approved AND trading is enabled
-- a one-time confirmation_token. Show the user the risk decision and cost,
then call place_order with that token.
action: BUY or SELL. order_type: MKT or LMT (limit_price required for LMT).
Inputs: action (required), symbol (required), quantity (required), order_type, +1 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 9 tools
Each tool targets a distinct function: account summary, positions, orders, quotes, trades, status, and a two-step order placement. No overlap in purpose.
All tool names follow a consistent verb_noun pattern (e.g., cancel_order, get_account_summary, place_order) using underscores.
9 tools is well-scoped for an IBKR trading server, covering account info, order management, quoting, and trade history without being excessive.
Core workflows are covered: quoting, order preview/placement/cancellation, account summary, positions, open orders, and trade blotter. Missing perhaps order modification, but that can be handled via cancel+reorder.
Related MCP Connectors
Agentic brokerage access to a US brokerage account: quotes, orders, positions, cash and documents.
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.
Related MCP Servers
- AlicenseBqualityCmaintenanceEnables AI assistants to interact with Interactive Brokers trading accounts to retrieve market data, check positions, and place trades. Includes pre-configured IB Gateway and handles OAuth authentication automatically.14317 npm227MIT
- FlicenseNot gradedqualityDmaintenanceEnables LLM clients to interact with Interactive Brokers Trader Workstation for automated trading workflows. Supports market data retrieval, portfolio management, and order execution through the TWS API.5-
- AlicenseNot gradedqualityDmaintenanceProvides 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.18MIT
- AlicenseNot gradedqualityBmaintenanceEnables read-only access to Interactive Brokers data including contracts, market data, news, fundamentals, and portfolio/account information for LLM workflows and autonomous agents.23 PyPI19BSD 3-Clause