ibkr-mcp
Enables LLM agents to interact with Interactive Brokers accounts for market data, account info, and order entry with built-in risk controls and a two-step confirmation flow.
README
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
<details> <summary><b>Sample run</b> — the safety flow and a risk-blocked order (click to expand)</summary>
=== 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." }
</details>
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.
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 |
|---|---|
get_status |
Backend, connection, trading on/off, active risk limits |
get_account_summary |
Net liquidation, cash, buying power, P&L |
get_positions |
Open positions with cost basis and unrealized P&L |
get_quote(symbol) |
Bid / ask / last / mid snapshot |
get_open_orders |
Working (unfilled) orders |
get_trades |
Execution blotter |
preview_order(...) |
Step 1 — risk-check an order, return a confirmation token |
place_order(token) |
Step 2 — submit a previewed, re-validated order |
cancel_order(order_id) |
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.py
As an MCP server
pip install "mcp[cli]"
python -m ibkr_mcp.server # serves over stdio
Register it with an MCP client using examples/claude_desktop_config.example.json.
Against a real (paper) IBKR account
pip install ib_async- Launch 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 tests
License
MIT
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。