Skip to main content
Glama
jotorresro

mcp-ibkr

by jotorresro

mcp-ibkr

Custom MCP (Model Context Protocol) server to connect Claude Code with Interactive Brokers (IBKR), starting in read-only mode on a Paper Trading account.

Project status: 12 of 12 phases complete. See "Current status" section.

1. What this project is

A bridge between Claude Code and IBKR: Claude Code launches this server, the server exposes "tools" (functions with names and descriptions), and Claude uses them when the user asks for account information, positions, or market data. No tool talks directly to IBKR: all of them go through a centralized integration layer.

Related MCP server: IB Portfolio Tracker MCP Server

2. Architecture

Claude Code (cliente MCP)
      │  stdio / JSON-RPC
      v
Servidor MCP (src/server.py)
      │
      v
Tool Registry (src/tools/*)
      │
      v
Capa de integración IBKR (src/ibkr/*)
      │  ib_async → socket TCP
      v
IB Gateway (Paper Trading, puerto 4002)
      │
      v
Interactive Brokers

3. Folder structure

mcp-ibkr/
├── src/
│   ├── server.py          # Punto de entrada del servidor MCP
│   ├── ibkr/
│   │   └── connection.py     # UNICO lugar que habla con ib_async / IB Gateway
│   ├── tools/
│   │   ├── registry.py       # Registro central: conecta archivos de herramienta con el servidor
│   │   ├── account/            # Saldo, resumen de cuenta, verificar conexión
│   │   ├── market/              # Precio, cotización, históricos
│   │   ├── positions/            # Posiciones abiertas, P&L
│   │   └── orders/                # Consultar (activa) + crear/cancelar (ACTION, deshabilitadas)
│   ├── config/
│   │   └── settings.py       # Carga .env, rechaza arrancar en config insegura
│   └── utils/
│       └── risk.py            # RiskLevel: READ_ONLY / ACTION
├── tests/
├── .env.example
├── .gitignore
├── .mcp.json          # Registro del servidor para Claude Code (scope project)
├── pyproject.toml      # Configuracion de pytest
├── requirements.txt     # Dependencias exactas (pip freeze)
└── README.md

4. Requirements

  • Python 3.11+ (tested with 3.14).

  • Git.

  • curl (to download get-pip.py in section 5 and the IB Gateway installer in section 6).

  • IB Gateway installed, with a Paper Trading session started (see section 6).

5. Installation and configuration

cd ~/mcp-ibkr

# Crear entorno virtual aislado para este proyecto
python3 -m venv --without-pip .venv

# Instalar pip dentro del venv (no viene incluido con --without-pip)
curl -sS https://bootstrap.pypa.io/get-pip.py -o /tmp/get-pip.py
.venv/bin/python3 /tmp/get-pip.py

# Instalar dependencias del proyecto
.venv/bin/python3 -m pip install -r requirements.txt

# Configuración local (nunca se sube a Git)
cp .env.example .env

Note about requirements.txt: we only install 4 packages directly (mcp, ib_async, python-dotenv, pytest), but the file has many more lines because pip freeze also includes the dependencies of those packages (dependencies of their dependencies). That's normal — it doesn't mean the project uses all those libraries directly.

Note: on Debian/Ubuntu systems, python3 -m venv by itself can fail if the system package python3-venv is missing (it's installed with sudo apt install python3-venv). If you don't have sudo access, the combination --without-pip + installing pip manually inside the venv (the steps above) gives an equally isolated environment without needing admin privileges.

6. Connecting to IBKR (Paper Trading)

  1. Install IB Gateway (official download, stable-standalone):

    curl -o ibgateway-stable-standalone-linux-x64.sh \
      https://download.interactivebrokers.com/installers/ibgateway/stable-standalone/ibgateway-stable-standalone-linux-x64.sh
    chmod u+x ibgateway-stable-standalone-linux-x64.sh
    ./ibgateway-stable-standalone-linux-x64.sh
  2. Open it and log in explicitly selecting "Paper Trading" (not "Live Trading"), with your Paper Trading username/password.

  3. Verify that the API port is 4002 (Paper). You can confirm it like this:

    ss -ltnp | grep 4002   # deberia aparecer un proceso "java" escuchando
  4. Copy .env.example to .env (if you haven't already) and adjust the values if your configuration is different.

Why this is safe: src/config/settings.py refuses to start if IBKR_PORT is not exactly 4002, and also if IBKR_PAPER_TRADING_CONFIRMED doesn't say true. Additionally, the connection (src/ibkr/connection.py) is opened with readonly=True, which makes IB Gateway reject any attempt to send orders at the API level, even before order tools exist.

7. Claude Code configuration

The server is registered in .mcp.json (project root), with scope project. This means the file is versioned in Git and anyone who opens this repo in Claude Code will see the proposed server — but it is not run automatically: Claude Code marks it as "Pending approval" until you open a session inside this folder and approve it.

cd ~/mcp-ibkr
claude    # al iniciar, Claude Code te preguntará si confías en mcp-ibkr

To check the server status at any time:

claude mcp list
claude mcp get mcp-ibkr

If you ever want to remove it:

claude mcp remove mcp-ibkr -s project

8. Available tools

Tool

Category

Risk

Status

Description

verificar_conexion_ibkr

account

READ_ONLY

Active

Confirms there is an active connection with IB Gateway (Paper Trading) and lists visible accounts.

consultar_resumen_cuenta

account

READ_ONLY

Active

Net value, available cash, buying power, and margin.

consultar_precio_mercado

market

READ_ONLY

Active

Last price, bid/ask, previous close, and volume of a stock.

consultar_datos_historicos

market

READ_ONLY

Active

Historical OHLCV candles of a stock.

consultar_posiciones

positions

READ_ONLY

Active

Open positions (all or filtered by symbol).

consultar_pnl

positions

READ_ONLY

Active

Daily, unrealized, and realized P&L of the account.

consultar_ordenes

orders

READ_ONLY

Active

Lists open orders and their status.

crear_orden

orders

ACTION

Disabled

Creates an MKT/LMT order. Requires double activation (see section 11).

cancelar_orden

orders

ACTION

Disabled

Cancels an open order by orderId. Requires double activation.

9. How to add / modify / delete / disable a tool

Each tool is one file inside src/tools/<category>/, with this shape (see src/tools/account/verificar_conexion_ibkr.py as a real example):

from mcp.types import ToolAnnotations
from src.utils.risk import RiskLevel

NAME = "mi_herramienta"
DESCRIPTION = "Que hace, cuando usarla, que devuelve, si modifica la cuenta."
ANNOTATIONS = ToolAnnotations(readOnlyHint=True, openWorldHint=True)
ENABLED = True
RISK_LEVEL = RiskLevel.READ_ONLY  # o RiskLevel.ACTION si modifica algo

def mi_herramienta(parametro: str) -> str:
    return "resultado"

The function must be named the same as NAME — that way the central registry (src/tools/registry.py) finds it automatically. If RISK_LEVEL is ACTION, in addition to ENABLED = True you also need IBKR_ENABLE_ACTION_TOOLS=true in .env (see section 11) — two independent keys, on purpose.

About ANNOTATIONS: destructiveHint and idempotentHint are only meaningful when readOnlyHint=False (that's what the MCP spec documents) — that's why in a read-only tool it's enough with readOnlyHint and openWorldHint. Only add them if RISK_LEVEL is ACTION, as in src/tools/orders/crear_orden.py.

Adding a tool

  1. Create the file in the corresponding category (or create a new category, see below).

  2. Add the file name (without .py) to the TOOLS list in the __init__.py of that category.

  3. Restart the Claude Code session so it picks it up (Claude Code reads the tools only once, when the server starts; claude mcp list only checks the connection status, it doesn't reload anything).

Modifying a tool

Edit its file directly — DESCRIPTION, function parameters, internal logic, etc. No need to touch registry.py.

Deleting a tool

Delete the file and remove its name from TOOLS in the __init__.py of its category.

Disabling a tool (without deleting it)

Set ENABLED = False in its file. registry.py skips it automatically.

Creating a new category

Create the folder src/tools/<category>/ with an __init__.py that defines TOOLS: list[str] = [...], and add the category name to CATEGORIES in src/tools/registry.py.

10. Testing

cd ~/mcp-ibkr
.venv/bin/python3 -m pytest tests/ -v
  • tests/test_server.py — the server starts and exposes the expected tools (the same ones Claude Code would see when connecting); the read-only tools don't set annotations that don't apply; and each tool responds with a friendly message if IBKR is not available, instead of letting an exception escape.

  • tests/test_settings.py — the configuration rejects a port other than 4002 and the lack of IBKR_PAPER_TRADING_CONFIRMED.

  • tests/test_connection.py — the connection layer serializes connection attempts (with a simulated IBKR, no real Gateway required): if two tools are called almost at the same time, there are never two connection attempts running in parallel.

  • tests/test_risk_system.py — the ACTION tools (crear_orden, cancelar_orden) are not registered by default, and the order validations (quantity, type, price) reject invalid parameters.

  • tests/test_ibkr_integration.py — real connection against IB Gateway. If Gateway is not running, this test is skipped (it doesn't fail) — that's expected, not a project error.

All order-related tests use validar_parametros_orden in isolation (without touching IBKR) or depend on crear_orden being disabled by default: no test in this project sends a real order, not even in Paper Trading.

11. From Paper Trading to Live Trading

⚠️ Live Trading is not supported by this project yet, and crear_orden/cancelar_orden are disabled by default. What follows is the explanation of the security layers, not an invitation to enable them without thinking.

There are three independent layers that prevent a real order from being sent by accident:

  1. Mandatory port 4002src/config/settings.py refuses to start if IBKR_PORT is not exactly the Paper Trading one. This version of the project has no code path to use port 4001 (Live).

  2. Double key for ACTION toolscrear_orden and cancelar_orden need ENABLED = True in their own file and IBKR_ENABLE_ACTION_TOOLS=true in .env. Neither of the two is enabled by default. Both are read only when the server starts: if you change them while the server is already running, you need to restart the Claude Code session for the change to take effect.

  3. Read-only connection at the API level — while IBKR_ENABLE_ACTION_TOOLS is false, src/ibkr/connection.py connects with readonly=True: IB Gateway rejects any order even if someone managed to bypass the previous two layers.

If in the future you decide to enable order sending in Paper Trading, the path would be: review and strengthen the validations in src/tools/orders/crear_orden.py, set IBKR_ENABLE_ACTION_TOOLS=true in .env, and ENABLED = True in the order files. Support for real Live Trading is not implemented or planned in this project — a completely separate security review would be needed before considering it.

12. Current status

  • Phase 1 — Architecture and concepts

  • Phase 2 — Minimal project structure

  • Phase 3 — Development environment

  • Phase 4 — Minimal MCP server

  • Phase 5 — Connect Claude Code with the MCP

  • Phase 6 — First test tool

  • Phase 7 — Connection with IB Gateway (Paper Trading)

  • Phase 8 — Query tools

  • Phase 9 — Validation and risk system

  • Phase 10 — Order tools (blocked)

  • Phase 11 — Complete testing

  • Phase 12 — Final documentation

F
license - not found
Not graded
quality - not tested
B
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • A
    license
    B
    quality
    A
    maintenance
    Enables 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.
    14
    518
    212
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Connects Claude AI to Interactive Brokers accounts to enable real-time portfolio tracking, position management, and historical market data retrieval. It also integrates financial news and sentiment analysis from multiple sources, including Finnhub and IB native feeds.
    MIT
  • F
    license
    C
    quality
    B
    maintenance
    Enables interaction with Interactive Brokers through the TWS API for account management, market data, contract resolution, and order placement, with paper trading by default.
    14
    1
  • A
    license
    Not graded
    quality
    B
    maintenance
    Enables read-only access to Interactive Brokers data including contracts, market data, news, fundamentals, and portfolio/account information for LLM workflows and autonomous agents.
    17
    BSD 3-Clause

View all related MCP servers

Related MCP Connectors

  • Trade Robinhood through natural language in Claude Code.

  • Read-only bank access for your AI agent. Connects Claude, ChatGPT, Cursor, Gemini, Codex.

  • Connect Claude to Fathom meeting recordings, transcripts, and summaries

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/jotorresro/mcp-ibkr'

If you have feedback or need assistance with the MCP directory API, please join our Discord server