Skip to main content
Glama
ib-gateway-mcp

ib-gateway-mcp

ib-gateway-mcp

CI License: MIT Python 3.12 | 3.13 | 3.14

An MCP server and Python library for the Interactive Brokers TWS API, built as a companion to gnzsnz/ib-gateway-docker.

Add one service next to your IB Gateway container, and any MCP client (Claude, Cursor, and others) gets what the gateway offers: contracts, market data, history, scanners, news, fundamentals, account and P&L, and orders. Orders sit behind safety rails.

Status: early development. Releases are published on PyPI as ib-gateway-mcp and as the container image ghcr.io/aiordanescu/ib-gateway-mcp. Beyond the offline test suite, it has been tested against a real IB Gateway: the order suite on a paper login and the read-only suite on paper and live accounts (10.45), and the login-state reader against the logs of 10.45 and 10.50 and a running 10.50 paper gateway.

Why

As of September 2026, the MCP options for Interactive Brokers are either hosted services that stop short of placing orders, or community servers that each cover a slice of the TWS API, many of them read-only.

ib-gateway-mcp covers the TWS API broadly (70 tools; coverage maps every API request), runs on your own infrastructure next to your own gateway, and guards agent trading with safety rails that are on by default.

Related MCP server: IB MCP Server

Features

  • TWS API coverage, through ib_async 2.1.0:

    • contracts: symbol search, details, qualification, option chains, market rules

    • market data: snapshots, and streaming quotes (with generic ticks such as option statistics, shortability, ETF NAV), market depth, tick-by-tick data, 5-second and live-updating bars

    • historical bars and ticks, head timestamps, histograms, trading schedules

    • scanners, news (providers, headlines, articles, bulletins), Refinitiv fundamentals, Wall Street Horizon events

    • account summary and values, positions, portfolio, P&L, executions, open and completed orders

    • IBKR's option calculators and chain quotes with greeks

    • orders: MKT, LMT, STP, STP LMT, TRAIL, TRAIL LIMIT, REL, MIT, LIT, MOC, LOC, MIDPRICE, PEG MID and PEG MKT; brackets, OCA groups, combos (BAG); the Adaptive, TWAP, VWAP, Arrival Price, Percentage of Volume and Close Price algos; good-after and good-till times, all-or-none, hidden and iceberg orders; modify, cancel, cancel-all and option exercise

    • financial advisor (FA) logins: FA group configuration (read and replace), model-code orders, soft dollar tiers, family codes. Allocating one order across an FA group isn't supported yet.

    • not yet: order conditions, cash-quantity orders and the rarer order types and algos (list)

  • Toolsets: register only what you need. Three profiles: readonly (default), trading, full. The tool list is large (the readonly profile's 50 tools carry about 175,000 characters of descriptions and input schemas), so a narrower IBKR_MCP_TOOLSETS leaves more of the model's context for the task.

  • Safety rails for orders (see Safety): preview tokens, limits, rate limits, circuit breaker, audit log, and human confirmation for live orders.

  • Operational awareness: a health tool that reports the connection plainly (refused, lost or restored, cut off from IBKR, API in read-only mode) and when it last went down. The API doesn't say why a gateway refuses connections; with read access to the gateway's settings directory, the tool also reports its login phase, such as waiting for 2FA approval or a rejected login (Gateway login state).

  • Library plus server: an MCP server over stdio or streamable HTTP (bearer-token auth), and an importable async Python library.

Quick start with Docker

examples/docker-compose.yml runs ib-gateway-docker on a paper login next to this server. The gateway's own settings (2FA, trading mode, settings volume, VNC) are documented in ib-gateway-docker's README.

mkdir ib-gateway-mcp && cd ib-gateway-mcp
curl -fsSLO https://raw.githubusercontent.com/aiordanescu/ib-gateway-mcp/main/examples/docker-compose.yml
umask 077                                        # secrets readable by their owner only
printf 'TWS_USERID=...\n' > .env
printf '%s' '<paper password>' > tws_password.txt
openssl rand -hex 32 > mcp_auth_token.txt
sudo chown 1000 tws_password.txt                 # Linux only: the gateway image's user
sudo chown 10001 mcp_auth_token.txt              # Linux only: this image's user
docker compose up -d

Compose mounts secret files with their owner and mode from the host, hence the chown on Linux (Docker Desktop needs none). Run it on a host you do not share. The example publishes no gateway API port: the server reaches the gateway on the compose network, and a published API port would let any local process place orders around the safety rails. It also mounts the gateway's settings volume read-only into the server, so get_health reports the gateway's login phase (Gateway login state).

Point an MCP client at http://127.0.0.1:8000/mcp with the header Authorization: Bearer <contents of mcp_auth_token.txt>. For Claude Code:

claude mcp add --transport http ib-gateway http://127.0.0.1:8000/mcp \
  --header "Authorization: Bearer $(cat mcp_auth_token.txt)"

If ib-gateway-docker already runs in its own stack, run the server as a second stack, so updating one never recreates the other: copy the ib-gateway-mcp service with its secret and volume, set IB_HOST to the gateway's service name, and attach the service to the gateway stack's network (declared under networks: with external: true). Inside that network the gateway listens on 4004 (paper) and 4003 (live).

The image is published for amd64 and arm64 as ghcr.io/aiordanescu/ib-gateway-mcp, tagged with each version (0.2.2), its minor series (0.2), and latest and stable for the latest release. Each image carries an SBOM and a build provenance attestation (gh attestation verify oci://ghcr.io/aiordanescu/ib-gateway-mcp:0.2.2 --owner aiordanescu). docker build -t ib-gateway-mcp:local . in a clone builds it yourself. The image runs as a non-root user (uid and gid 10001), serves streamable HTTP on port 8000 (/mcp), and has a Docker healthcheck on /healthz. The compose example runs it with a read-only root filesystem, no capabilities, and the audit log on a volume at /audit. /healthz (liveness) and /readyz (200 only while the gateway connection is up) are unauthenticated and return only {"state", "ready"}.

Running without Docker

Needs Python 3.12 or newer. With uv, uvx runs the latest release from PyPI with nothing to install first (pip install ib-gateway-mcp works too):

IB_HOST=127.0.0.1 IB_PORT=4002 uvx ib-gateway-mcp                # stdio

openssl rand -hex 32 > mcp_auth_token.txt                        # HTTP on 127.0.0.1:8000
IBKR_MCP_AUTH_TOKEN_FILE=mcp_auth_token.txt uvx ib-gateway-mcp --transport http --port 8000

HTTP always needs a bearer token of at least 32 characters. For a quick test on the loopback address only, IBKR_MCP_ALLOW_NO_AUTH=true serves it without one.

A stdio entry for an MCP client:

{
  "mcpServers": {
    "ib-gateway": {
      "command": "uvx",
      "args": ["ib-gateway-mcp"],
      "env": { "IB_HOST": "127.0.0.1", "IB_PORT": "4002", "IBKR_MCP_PROFILE": "readonly" }
    }
  }
}

Pin a version with ib-gateway-mcp==0.2.2 in place of ib-gateway-mcp. To run a clone instead (for development, or an unreleased commit), use uv sync in it, then uv run ib-gateway-mcp with the same variables and options, or "command": "uv" with "args": ["--directory", "/path/to/ib-gateway-mcp", "run", "ib-gateway-mcp"] in the client entry.

The server starts even when the gateway is down and keeps reconnecting; tools then fail with not_connected, and get_health reports what is known about why.

Gateway login state (optional)

When the gateway refuses a connection, the TWS API doesn't say why: a gateway that is stopped, starting, waiting for a 2FA approval or stuck at its login looks the same. IB Gateway does log its login steps, to launcher.log in its settings directory. With IB_GATEWAY_SETTINGS_DIR set to that directory, get_health adds login_state: the phase (restarting, logging_in, awaiting_2fa, throttled, login_rejected, login_idle, logged_in or unknown) and since when, when the gateway's pause after repeated failed logins ends (retry_at), and the login attempts and 2FA challenges since the last successful login. While the gateway refuses the connection, the health hint then words that phase. The gateway stops writing to launcher.log once a login succeeds, so logged_in only means that the last login succeeded. Without the setting, get_health still reports last_disconnect_at, when the connection last went down. It is null if the server's first connection attempt succeeded and the connection hasn't dropped since; if the gateway was already down when the server started, it is the server's start time, also after the connection comes back, and the outage may be older. docs/tools.md describes the fields.

After a 2FA challenge nobody answered, or once the gateway's pause after failed logins ends, the gateway logs in again by itself only with ib-gateway-docker's RELOGIN_AFTER_TWOFA_TIMEOUT=yes (its default is no), which also means a new 2FA push after each unanswered one. Otherwise login_state turns login_idle, and the gateway container needs a restart.

The gateway writes launcher.log to a volume only when ib-gateway-docker's TWS_SETTINGS_PATH is set: its default is empty, which leaves the file inside the gateway container. Mount the directory, not the file (the gateway rotates the log by renaming it), and mount it read-only. examples/docker-compose.yml does this for a paper login:

services:
  tws-settings-init:            # gives the new volume to the gateway's user (uid 1000)
    image: ghcr.io/gnzsnz/ib-gateway:stable
    user: "0:0"
    entrypoint: ["chown", "1000:1000", "/home/ibgateway/tws_settings"]
    volumes:
      - tws_settings:/home/ibgateway/tws_settings
    restart: "no"
  ib-gateway:
    depends_on:
      tws-settings-init:
        condition: service_completed_successfully
    environment:
      TWS_SETTINGS_PATH: /home/ibgateway/tws_settings
    volumes:
      - tws_settings:/home/ibgateway/tws_settings
  ib-gateway-mcp:
    environment:
      IB_GATEWAY_SETTINGS_DIR: /gateway/tws_settings
    volumes:
      - type: volume
        source: tws_settings
        target: /gateway/tws_settings    # not a path in this server's image
        read_only: true
        volume:
          nocopy: true
volumes:
  tws_settings:

Docker creates a new named volume owned by root when the image has no such path, and ib-gateway-docker runs as uid 1000, so without tws-settings-init the gateway can't write its settings. The long syntax is what takes nocopy: together with a target that doesn't exist in this server's image, it keeps Docker from copying anything from the image into the gateway's volume.

With TRADING_MODE=both, ib-gateway-docker appends _live and _paper to TWS_SETTINGS_PATH and never uses the path itself, so put the volume on the parent directory and point the server at the directory of the login behind its IB_PORT:

services:
  settings-init:                # as above, for the parent directory
    image: ghcr.io/gnzsnz/ib-gateway:stable
    user: "0:0"
    entrypoint: ["chown", "1000:1000", "/home/ibgateway/settings"]
    volumes:
      - gateway_settings:/home/ibgateway/settings
    restart: "no"
  ib-gateway:
    depends_on:
      settings-init:
        condition: service_completed_successfully
    environment:
      TRADING_MODE: both
      TWS_SETTINGS_PATH: /home/ibgateway/settings/tws    # the gateway uses tws_live and tws_paper
    volumes:
      - gateway_settings:/home/ibgateway/settings
  ib-gateway-mcp:
    environment:
      IB_PORT: "4004"                                    # paper; 4003 is live
      IB_GATEWAY_SETTINGS_DIR: /gateway/tws_paper        # /gateway/tws_live for 4003
    volumes:
      - type: volume
        source: gateway_settings
        target: /gateway
        read_only: true
        volume:
          nocopy: true
volumes:
  gateway_settings:

With bind mounts, mount the same host directory into both containers: ./tws_settings:/home/ibgateway/tws_settings on the gateway and ./tws_settings:/gateway/tws_settings:ro on the server. Create the directory before the first start and, on Linux, give it to the gateway's user (sudo chown 1000:1000 tws_settings): Docker creates a missing one owned by root. Under SELinux in enforcing mode (Fedora, RHEL), add :z to both mounts (:ro,z on the server's); never :Z, which makes the directory private to one container.

A server run on the host (stdio, uvx) reads the directory itself, so the gateway needs a bind mount on that same host, and IB_GATEWAY_SETTINGS_DIR names the host path. Docker Desktop keeps named volumes inside its virtual machine, out of the host's reach, and a gateway on another machine (reached over an SSH tunnel, for example) can't be read at all. The server only reads the directory, and warns at start-up when it could write to it; on the host, run the server as a user that can read the directory but not write to it.

This works with IB Gateway (ib-gateway-docker's gateway image) and was tested against the logs of IB Gateway 10.45 and 10.50; TWS is untested. The log format is IBKR's own and undocumented, so a gateway update may change it; whatever the server doesn't recognize reads as unknown.

Privacy. Read access to the settings directory exposes more than the login phase. launcher.log holds, among other things, the host's local and public IP addresses, its MAC address, IBKR session ids, masked session-token prefixes and token hashes, a log upload key, and ad-request ids that base64-encode the login's user identifier. The gateway masks the username in its login lines, and no account ids were found in the log. During the daily auto-restart the directory briefly holds a file with the session token the restart reuses. The server opens only launcher.log and its rotated copies (launcher.YYYYMMDD.log), and returns only the parsed phase, times and counts, never log text. Mount the directory read-only and into this server only, and never mount /home/ibgateway or IBC's directory, which can hold the password.

Configuration

Everything is set with environment variables. IB_* variables describe the gateway connection, IBKR_MCP_* the server's behaviour; other names (such as a bare PROFILE) are ignored. Secrets also take a _FILE variant (Docker secrets). A blank value (VAR=) counts as unset, so the default applies.

Variable

Default

Meaning

IB_HOST

127.0.0.1

Gateway host (ib-gateway in the image).

IB_PORT

4004

Gateway API port. In ib-gateway-docker's network: 4004 paper, 4003 live.

IB_CLIENT_ID

80

API client id; keep it stable and unique on the login. 0 is refused.

IB_ACCOUNT

Default account. Without it, a login that manages several accounts has no default, and calls must name one.

IB_CONNECT_TIMEOUT

10

Seconds per connection attempt.

IB_REQUEST_TIMEOUT

30

Seconds per request.

IB_GATEWAY_SETTINGS_DIR

The gateway's settings directory, where it writes launcher.log (ib-gateway-docker's TWS_SETTINGS_PATH; with TRADING_MODE=both the _live or _paper one for IB_PORT), mounted read-only. get_health then reports the gateway's login phase (login_state). IB Gateway only.

IBKR_MCP_ACCOUNTS

Comma-separated accounts allowed besides the default; empty means only the default.

IBKR_MCP_PROFILE

readonly

readonly, trading or full.

IBKR_MCP_TOOLSETS

Comma-separated toolsets; overrides the profile.

IBKR_MCP_ALLOW_LIVE

false

Allow order tools on live (non-paper) accounts.

IBKR_MCP_LIVE_CONFIRM

true

Ask a human (elicitation) before each live order, cancel or FA change.

IBKR_MCP_TOKEN_TTL

120

Seconds a preview token stays valid.

IBKR_MCP_MAX_NOTIONAL

Largest order notional, in the order's own currency (no FX conversion). While set, bond and event-contract orders are refused (their notional is not quantity x price).

IBKR_MCP_MAX_QUANTITY

Largest order quantity.

IBKR_MCP_ALLOWED_SYMBOLS

Comma-separated symbols orders may use; empty means any.

IBKR_MCP_ALLOWED_SEC_TYPES

Comma-separated security types (STK,OPT...); empty means any.

IBKR_MCP_ALLOWED_CURRENCIES

Comma-separated order currencies (USD...); empty means any. Set it to make IBKR_MCP_MAX_NOTIONAL a cap in one currency.

IBKR_MCP_MAX_ORDERS_PER_MINUTE

10

Order rate limit.

IBKR_MCP_MAX_PREVIEWS_PER_MINUTE

60

Preview rate limit (each preview sends what-if checks to IBKR).

IBKR_MCP_CIRCUIT_BREAKER_REJECTS

5

Consecutive IBKR rejections that halt order submission.

IBKR_MCP_ALLOW_GLOBAL_CANCEL

false

Allow preview_cancel_all_orders(scope="global"), IBKR's cancel of every order on the login.

IBKR_MCP_AUDIT_LOG

JSONL audit file; unset logs to the ib_gateway_mcp.audit logger only. An open circuit breaker is kept next to it (audit.breaker.json for audit.jsonl). With write tools on, the server refuses to start if the file cannot be written.

IBKR_MCP_MAX_SUBSCRIPTIONS

50

Open streams allowed.

IBKR_MCP_SUBSCRIPTION_IDLE_TTL

900

Seconds without a read before a stream is cancelled.

IBKR_MCP_MARKET_DATA_TYPE

1

1 live, 2 frozen, 3 delayed, 4 delayed-frozen.

IBKR_MCP_ALLOW_REGULATORY_SNAPSHOTS

false

Allow get_quotes(regulatory_snapshot=true), which IBKR bills (about USD 0.01 each); each is audited.

IBKR_MCP_TRANSPORT

stdio

stdio or http (http in the image).

IBKR_MCP_HTTP_HOST

127.0.0.1

HTTP listen address (0.0.0.0 in the image).

IBKR_MCP_HTTP_PORT

8000

HTTP listen port.

IBKR_MCP_AUTH_TOKEN / _FILE

Bearer token, at least 32 characters. Required for HTTP.

IBKR_MCP_ALLOW_NO_AUTH

false

Allow HTTP without a token, on a loopback address only.

IBKR_MCP_LOG_LEVEL

INFO

Log level (logs go to stderr). The audit logger stays at INFO.

Command-line flags (--transport, --host, --port, --profile, --toolsets, --log-level) override the environment.

Profiles and tools

Profile

Toolsets

Tools

readonly (default)

ops, contracts, market_data, history, scanners, news, fundamentals, account, options

50

trading

readonly + orders

60

full

trading + advisor, admin

70

The profiles are broad on purpose, and most agents need only a slice. Every tool description and schema goes into the model's context, and a model picks tools more reliably from a short list, so set IBKR_MCP_TOOLSETS to what the agent actually uses. It overrides the profile; ops (health, connection, accounts, user and server time) is always on, and market_data comes with scanners, news or admin, whose streams it reads and cancels.

Toolset

Tools

ops (always on)

5

contracts

7

market_data

10

history

5

scanners

3

news

5

fundamentals

3

account

9

options

3

orders

10

advisor

5

admin

5

For example, IBKR_MCP_TOOLSETS=account gives a portfolio monitor 14 tools, contracts,market_data,history gives a research agent 27, and contracts,account,orders gives a trading agent 31 behind the same rails as the trading profile.

Every tool, with its parameters: docs/tools.md. Streams (subscribe_*) return a subscription id; get_subscription_data reads it, unsubscribe stops it, and streams nobody reads are cancelled after IBKR_MCP_SUBSCRIPTION_IDLE_TTL.

Safety

  • Read-only by default. The readonly profile registers no order, advisor or admin tool. Every write path (orders, cancels, FA changes, admin settings) also passes the trading gate: the gateway is connected, a write toolset is enabled, the login's accounts are known and one of them is allowed, no live account is in scope unless IBKR_MCP_ALLOW_LIVE=true, and the gateway's API is not read-only. For a deployment that must never trade, turn on the gateway's own Read-Only API setting too (READ_ONLY_API=yes in ib-gateway-docker): it's the only guarantee enforced by IBKR's software rather than this server.

  • Paper unless told otherwise. Paper and live are told apart from the account ids (paper ids start with D). Order tools refuse live accounts unless IBKR_MCP_ALLOW_LIVE=true.

  • Two-step orders. A preview_* tool runs IBKR's what-if check (margin, commission) and the limits, and returns a token: a single-use, expiring key (192 random bits) to the exact order and account, which stay on the server. submit_order takes only the token and checks everything again.

  • A human confirms live actions. With IBKR_MCP_LIVE_CONFIRM=true (the default), submitting, cancelling or changing FA configuration on a live account asks the person at the client through MCP elicitation. The model can't answer for them. The question is built by the server; anything the model wrote into it (a model code, a tier or FA group name, a reason) is quoted and must be one line of plain text.

  • Limits: notional, quantity, symbols, security types and currencies, order and preview rate limits, and a circuit breaker that halts submission after consecutive rejections until a human resets it; with an audit file it stays open across restarts. get_health shows the breaker. A notional check that had to use delayed, frozen or previous-close prices says so in the preview and in the confirmation.

  • Audit log of every preview, submit, modify, cancel, exercise, FA change, billed snapshot, circuit-breaker reset, admin change (server log level, display group) and refusal at the trading gate (JSONL, no secrets). The server logs its safety configuration at start-up and warns about risky combinations. A failed write to the audit file is logged at ERROR and does not stop the order, so watch the logs, and keep the file on a volume the server's user can write (start-up already fails when it can't).

Caveats:

  • Clients without form elicitation can't confirm live orders, so live submits, cancels and FA changes are refused there (fail closed). Paper orders, cancels and FA changes never ask.

  • Resetting the circuit breaker always asks a human, on paper too, through reset_circuit_breaker in the admin toolset (the full profile). Without elicitation or that toolset: with no audit file, restart the server; with one, stop the server, delete the .breaker.json file next to the audit file (audit.breaker.json for audit.jsonl), and start it again.

  • The rails assume the model reaches the gateway only through this server. An agent that can open the gateway's API port itself, or restart this server and edit its files, can go around them; keep the API port unpublished and the server's host and volumes out of the agent's reach.

  • Paper logins see market data only with sharing. Enable market data sharing with the paper account in IBKR's settings, or use delayed data (IBKR_MCP_MARKET_DATA_TYPE=3).

  • Client ids matter. An API client can modify and cancel only the orders it placed itself. IB_CLIENT_ID defaults to 80; give every API client on the login (this server, other bots, notebooks) its own stable id. 0 is refused, because orders entered by hand in TWS bind to client 0. get_open_orders marks other clients' and manual orders as not modifiable, and get_order_status reads their status from IBKR each time.

  • preview_cancel_all_orders(scope="global") is IBKR's global cancel: every working order on the login, including other API clients' and manual orders. It's refused unless IBKR_MCP_ALLOW_GLOBAL_CANCEL=true and the allowlist covers every managed account.

  • Preview tokens live in memory; a restart invalidates them.

Troubleshooting

  • Orders fail with error 321, or the gateway shows "API client needs write access". The gateway's API is read-only: get_health reports api_read_only: true and the trading gate stays closed. Set READ_ONLY_API=no in ib-gateway-docker, or untick Read-Only API in the gateway's own settings (Configure > Settings > API > Settings, over VNC in ib-gateway-docker). If READ_ONLY_API is already no and the error persists, the gateway can still hold the old setting in its settings volume: set READ_ONLY_API=yes, restart the gateway, then set it back to no and restart it again. The server reconnects by itself after a gateway restart, which clears api_read_only; after a change in the gateway's settings alone, restart the server. While the API is read-only, IBKR also refuses get_completed_orders (error 321, at once), and get_open_orders for this server's own orders reads every client's orders and filters them, saying so in note.

  • get_health reports login_rejected after the gateway's daily auto-restart (its detail says IBKR refused the saved session). The auto-restart reuses the saved session instead of logging in; IBKR refused it and asked for the password, which an auto-restart can't enter, so the gateway waits at its login screen and doesn't retry. Approving a 2FA prompt won't help: restart the gateway container, a cold restart that logs in with the password (and a second factor, where the login has one). IBKR also ends saved sessions once a week (Sundays at 1:00 am ET): with ib-gateway-docker's TWS_COLD_RESTART set to a time after that, the gateway restarts cold every Sunday then. That covers the weekly case only.

  • Quotes fail with error 10089 although delayed data is selected. IBKR offers the login no delayed data for that instrument either (IB Gateway 10.45 does this for some instruments on paper logins); historical bars can still work. Subscribe to the exchange's data, or share market data with the paper account.

Library

The services behind the tools are an async Python library:

uv add ib-gateway-mcp        # or: pip install ib-gateway-mcp
import asyncio

from ib_gateway_mcp import ContractSpec, Gateway, Settings
from ib_gateway_mcp.models import OrderSpec, QuoteStreamData


async def main() -> None:
    # Write access (orders, FA, admin) follows the toolsets, as for the server.
    settings = Settings(ib_port=4002, profile="trading")
    async with Gateway(settings) as gw:
        await gw.wait_connected(timeout=15)
        print(gw.ops.health().state)

        spy = ContractSpec(symbol="SPY")
        quotes = await gw.market_data.quotes([spy])
        print(quotes.quotes[0].last)

        preview = await gw.orders.preview_order(
            OrderSpec(contract=spy, action="BUY", quantity=1, order_type="LMT", limit_price=1.00)
        )
        print(preview.summary, preview.what_if)
        # result = await gw.orders.submit(preview.token)

        sub = await gw.market_data.subscribe_quotes(spy)
        async for data in gw.market_data.watch(sub.subscription_id, QuoteStreamData):
            print(data.quote.last)
            break
        await gw.market_data.unsubscribe(sub.subscription_id)


asyncio.run(main())

Services: gw.ops, gw.contracts, gw.market_data, gw.history, gw.scanners, gw.news, gw.fundamentals, gw.account, gw.options, gw.orders, gw.advisor, gw.admin. They take and return the pydantic models in ib_gateway_mcp.models and raise the errors in ib_gateway_mcp.errors (all derived from IbGatewayMcpError). Error messages are written for the MCP tools and name them where they point to a next step; docs/tools.md gives the service method behind each tool. Contract resolution (qualify, qualify_details, qualify_many) is shared by every service; gw.contracts has the lookups proper. The library applies the same account scope, trading gate and order rails as the server; gw.ib is a raw ib_async.IB escape hatch that bypasses them.

Agent skill (optional)

skills/ib-gateway-mcp is an Agent Skills guide for the agent that uses this server. The tool descriptions cover each tool; the skill covers the workflows across them: preview, submit and fill checks, brackets, OCA groups and combos, market data types, which errors are final, and what to report while the gateway is down. It uses only the fields of the specification and bare tool names, so it works in any agent that loads skills. Install the release that matches your server; the commands below pin v0.2.2.

Any agent, with npx skills (it asks which agents to install for) or the GitHub CLI's gh skill (a preview command):

npx skills add aiordanescu/ib-gateway-mcp#v0.2.2 --skill ib-gateway-mcp
gh skill install aiordanescu/ib-gateway-mcp ib-gateway-mcp@v0.2.2 --agent <agent> --scope user

Claude Code:

npx skills add aiordanescu/ib-gateway-mcp#v0.2.2 --skill ib-gateway-mcp -a claude-code -g

Codex, inside a session:

$skill-installer install https://github.com/aiordanescu/ib-gateway-mcp/tree/v0.2.2/skills/ib-gateway-mcp

Hermes Agent:

hermes skills install https://raw.githubusercontent.com/aiordanescu/ib-gateway-mcp/v0.2.2/skills/ib-gateway-mcp/SKILL.md

Or copy skills/ib-gateway-mcp/ from the v0.2.2 tag into the agent's skills directory: ~/.claude/skills/ for Claude Code, ~/.agents/skills/ for most other agents.

Development

uv sync
uv run ruff check . && uv run ruff format --check . && uv run mypy && uv run pytest
uv run python scripts/gen_docs.py    # regenerate docs/tools.md after changing a tool

Unit, MCP and end-to-end tests run against fakes (a mock ib_async.IB, and a fake TWS socket server on localhost) and never reach a real gateway. Two integration suites run only on demand, never in CI:

  • IB_HOST=... IB_PORT=... uv run pytest -m live_readonly: read-only probes of every read toolset.

  • IB_HOST=... IB_PORT=... IB_ACCOUNT=DU... uv run pytest -m paper: order round trips; they refuse to run unless every account on the login is a paper account.

The contributor guide, with the architecture, the test tiers and the safety invariants every change keeps, is CLAUDE.md. See also CONTRIBUTING.md, SECURITY.md and CHANGELOG.md.

Disclaimer

This project is not affiliated with, endorsed by, or supported by Interactive Brokers. "Interactive Brokers", "IBKR", "IB Gateway" and "TWS" are trademarks of their owners and are used here only to name the software this project works with. Trading involves the risk of loss, and software that places orders can place wrong ones. Nothing here is investment advice. Use it at your own risk; the software comes with no warranty (see the license), and you are responsible for every order it places on your accounts.

License

MIT

Available Tools

50 tools
calculate_implied_volatilityImplied volatility calculatorA
Read-only

Compute an option's implied volatility from a given option price, with IBKR's model.

`contract` must be one option (sec_type OPT or FOP with symbol, expiry, strike and
right, or its con_id; futures options also need their exchange, e.g. CME). Returns
`implied_vol` as a decimal (0.25 = 25%) and the greeks at that volatility (delta,
gamma, vega, theta, dividend present value). Useful for what-if pricing: pass a
hypothetical option or underlying price. Nothing is stored or streamed.

Errors: invalid_request when the contract is not an option or no volatility fits the
prices (e.g. an option price below intrinsic value); not_found or ambiguous_contract
when the option cannot be resolved (get_option_chain lists expiries and strikes);
request_timeout when IBKR does not answer within 4 seconds; ib_api_error if IBKR
refuses (it may want market data permissions for the option and its underlying).

Inputs: contract (required), option_price (required), underlying_price (required). Returns: IBKR's implied volatility (and greeks) for one option at a given option price.

calculate_option_priceOption price calculatorA
Read-only

Compute an option's theoretical price and greeks at a given volatility, with IBKR's model.

`contract` must be one option (sec_type OPT or FOP with symbol, expiry, strike and
right, or its con_id; futures options also need their exchange, e.g. CME). Returns
`option_price` per share (multiply by the contract multiplier for the premium) and
the greeks (delta, gamma, vega, theta, dividend present value). Useful for
scenarios: vary volatility or underlying_price.

Errors: invalid_request when the contract is not an option, volatility looks like a
percent (above 10), or IBKR computed no price; not_found or ambiguous_contract when
the option cannot be resolved; request_timeout when IBKR does not answer within 4
seconds; ib_api_error if IBKR refuses (e.g. missing market data permissions).

Inputs: contract (required), volatility (required), underlying_price (required). Returns: IBKR's theoretical price (and greeks) for one option at a given volatility.

get_account_summaryAccount summaryA
Read-only

Return an account's headline balances: net liquidation, cash, buying power, margin.

Headline fields (in `base_currency`): net_liquidation, total_cash_value, settled_cash,
buying_power, available_funds, excess_liquidity, equity_with_loan_value,
gross_position_value, init/maint margin requirement, sma, cushion (fraction), leverage
and day_trades_remaining (-1 = unlimited). `values` holds every summary row,
including per-currency ledger rows (CashBalance, UnrealizedPnL... with currency BASE
for converted totals). IBKR refreshes the summary about every 3 minutes, and right
after trades. No market-data subscription needed.
Errors: invalid_request lists the valid tags when a tag is unknown.

Inputs: tags, account. Returns: Headline balances and margin figures for one account. Amounts are in ``base_cur…

get_account_valuesAccount valuesA
Read-only

Return the full key/value account data: every tag IBKR reports, per currency.

Use it for details the summary lacks (per-currency cash, accrued interest, segment
values with -C/-S suffixes, currency exchange rates...). Each row has the raw `value`
and, when numeric, `amount`. Values update about every 3 minutes or on change.
With `model_code` (financial advisors) the values of that model are fetched once.
Default limit 200, maximum 1000; `truncated` says whether more matched.
Errors: invalid_request lists the valid tags when a tag is unknown.

Inputs: tags, limit, account, currency, +1 more. Returns: Key/value account data for one account (all tags, per currency).

get_completed_ordersCompleted ordersA
Read-only

List recently filled or cancelled orders, newest first, with IBKR's completion status.

IBKR decides how far back this reaches (the current and recent sessions). Use
get_executions for fill prices and commissions. Default limit 100, maximum 1000.
Errors: ib_api_error 321, at once, when the gateway's API is read-only (get_health:
api_read_only), which refuses this request; get_executions still lists recent fills.

Inputs: limit, account, api_only. Returns: Completed orders in one account, newest first.

get_connection_infoConnection detailsA
Read-only

Return technical details of the API session: endpoint, client id, API versions.

Includes the negotiated server version, the API version range this client speaks,
whether open and completed orders were synced (`orders_synced`), when the session
started, and traffic counters. Works when disconnected too (the session fields are
then null).

Inputs: no named parameters. Returns: Technical details of the API session.

get_contract_detailsContract detailsA
Read-only

Return IBKR's full contract details for every instrument a spec matches.

For each contract: identifiers (con_id, local symbol, trading class, multiplier),
long name (`contract.description`), industry and category, stock type, the
exchange time zone, trading and liquid (regular-hours) sessions for about the next
week with closed days, min tick, size increments, valid exchanges with their market
rule ids (same order; see get_market_rule), accepted order types, ISIN and other
security ids, the underlying of a derivative, and bond terms for bonds.

The contract may be partial: symbol + sec_type FUT + exchange lists every future expiry.
Derivatives are sorted by expiry, strike and right; `limit` defaults to 20 (cap 200),
`total` and `truncated` say how many matched. Broad option specs are slow and
throttled by IBKR: use get_option_chain for expiries and strikes, then look up single
options. Futures and indexes need their listing exchange (CME, CBOE...), not SMART;
set include_expired for expired futures. Errors: not_found for an unknown
instrument; invalid_request for combos (BAG).

Inputs: contract (required), limit. Returns: Contract details for every instrument a (possibly partial) spec matches.

get_depth_exchangesMarket depth exchangesA
Read-only

List the exchanges that offer market depth (level 2 order book), per security type.

Each row gives the exchange, security type, listing exchange and IBKR's depth service type (Deep or Deep2). Check it before subscribing to market depth. Depth itself needs a separate depth data subscription at IBKR; this list does not. The list is static and cached for the gateway session.

Inputs: no named parameters. Returns: Exchanges offering market depth; IBKR's list is static per session.

get_executionsExecutionsA
Read-only

List the account's executions (fills), newest first, with commission and realized P&L.

Covers the current trading day only (up to 7 days if the gateway's trade-log setting
allows); older trades are not available through the API. `commission` is null until
IBKR reports it (usually within seconds of the fill); realized_pnl is 0 for fills
that opened a position. Default limit 100, maximum 1000.

Inputs: side, limit, since, symbol, +2 more. Returns: Executions for one account, newest first.

get_fundamental_dataFundamental reportA
Read-only

Fetch a Refinitiv fundamentals report for a stock, as XML.

Deprecated by IBKR: reqFundamentalData was removed in TWS API 10.50. It still works on
IB Gateway stable (10.45); newer gateways may refuse it. Stocks only (sec_type STK).
Needs the Refinitiv (Reuters) fundamentals data subscription on the IBKR login.
Whitespace between XML tags is removed; long reports are cut at max_chars (default
50000, max 200000) with truncated=true, so prefer ReportSnapshot or ReportsFinSummary
over the large statement and ownership reports.
Errors: not_found (unknown stock, or IBKR has no such report for it, error
430), ambiguous_contract (give primary_exchange or con_id), ib_api_error 10358 (no
fundamentals subscription), invalid_request (not a stock), request_timeout (a newer
gateway may not answer at all). For key ratios without this report, use
subscribe_quotes with the fundamental_ratios generic tick.

Inputs: contract (required), report_type (required), max_chars. Returns: One fundamental report as XML, cut at ``max_chars`` when longer.

get_head_timestampEarliest historical dataA
Read-only

Return the earliest date and time IBKR has historical data for an instrument.

Use it before long get_historical_bars requests, or when they come back empty, to
learn how far back the data goes for this `what_to_show`. Needs market-data
permissions for the instrument; counts toward IBKR's historical-data limits.

Errors: not_found (no such contract, or no data of that type).

Inputs: contract (required), use_rth, what_to_show. Returns: The earliest point IBKR has historical data for, for one contract and data type.

get_healthGateway healthA
Read-only

Report whether the Interactive Brokers gateway connection is usable, and what is known about why not.

Call this first when another tool fails with not_connected or times out. It never
fails itself. `state` is one of:
- connected: everything works.
- connecting: a connection attempt is in progress.
- not_accepting: the gateway refused or ignored the connection; this alone doesn't say
  why. Retries run in the background.
- connectivity_lost: the gateway is up but cut off from IBKR's servers; usually heals.
- not_connected: stopped, or the connection dropped and a retry is pending.
`hint` explains what to do. `last_disconnect_at` is when the connection last went down,
kept after it comes back (this server's start time if it started during the outage).
`login_state` (if configured) is the gateway's login phase: restarting or logging_in
(in progress), awaiting_2fa (the account holder must approve a challenge), throttled
(paused until retry_at; it logs in again then only if its login automation is set to
retry), login_rejected (it won't retry), login_idle (nothing is retrying), unknown
(detail says why), or logged_in, which only means the last login in the gateway's log
succeeded; later events aren't logged there, and an old log_updated_at is normal then.
Without login_state, relay hint and report last_disconnect_at; don't guess a cause the
hint doesn't name.
`trading_enabled` says whether the trading gate is open (order tools also need
`circuit_open` false: after repeated IBKR rejections the breaker halts submits until a
human resets it). `api_read_only` means the gateway's own settings reject orders.
`is_paper` is true when the login only has paper accounts. `market_data_type` is the
requested data type (set_market_data_type), and `subscriptions_used`/`subscriptions_max`
count open streams. Pass probe=true to test the connection with a real request (the
state alone can lag behind a stalled socket).

Inputs: probe. Returns: A plain-language snapshot of the gateway connection.

get_histogramPrice histogramA
Read-only

Return how trading volume was distributed over price levels during a period.

Each entry is a price and IBKR's count (traded volume) at that price, sorted by
price. Useful for volume-at-price, support/resistance and value-area questions.
Default limit 200 price levels, at most 1000; when there are more, the busiest levels
are kept and `truncated` is true. Needs market-data permissions for the instrument.

Errors: not_found (no data for the period), invalid_request (bad period).

Inputs: contract (required), limit, period, use_rth. Returns: How trading was distributed over price levels during a period.

get_historical_barsHistorical barsA
Read-only

Return historical OHLCV bars for one instrument, oldest first.

Bars cover `duration` back from `end` (now when omitted). Intraday bar times are UTC;
daily, weekly and monthly bars carry the trading date. Default limit 1000 bars, at
most 10000; when there are more, the NEWEST are kept and `truncated` is true (request
a shorter duration or larger bars to see older ones).

Limits (IBKR): bars of 30 seconds or less reach back about 6 months, allow short
durations only (1 secs up to 1800 S, 5 secs up to 3600 S, 10/15 secs up to 14400 S,
30 secs up to 28800 S), and are paced at about 60 requests per 10 minutes, 5 per
contract and data type in 2 seconds, and no identical request within 15 s (this
server answers identical requests from a 15-second cache). Larger bars are not paced
that way; IBKR's guide for the longest duration: 1 min bars about 1 D, 3 mins 1 W,
30 mins 1 M, daily bars years. Needs market-data permissions for the instrument (the
same subscription as live quotes). IBKR keeps no data for expired options; expired
futures need include_expired in the contract.

Errors: not_found (no such contract, or no data in the range: check
what_to_show, use_rth and get_head_timestamp), invalid_request (bad duration or
bar size combination), rate_limit (pacing; retry after the stated time),
ib_api_error 162 (pacing, permissions), request_timeout (shorten the request).

Inputs: contract (required), end, limit, use_rth, +3 more. Returns: Historical bars for one contract, oldest first.

get_historical_newsHistorical headlinesA
Read-only

Return past news headlines about one instrument, newest first.

Each headline has provider_code and article_id for get_news_article, plus the
publication time (UTC). Works for stocks and other instruments IBKR tags news
with. Default limit 50, at most 300 (IBKR's cap per request); for more, move `end`
back to the oldest time returned. Needs a subscription to each provider searched
(see get_news_providers).
Errors: invalid_request for a provider the login is not subscribed to; not_found
when there are no headlines in the range (widen it); request_timeout when IBKR
does not answer within 4 seconds (retry with a narrower range).

Inputs: contract (required), end, limit, start, +1 more. Returns: Historical headlines for one instrument, newest first.

get_historical_ticksHistorical ticksA
Read-only

Return individual historical trades, quote changes or midpoints (time and sales).

Give exactly one of `start` (ticks after it) or `end` (ticks before it). IBKR sends
at most 1000 ticks per request, with one-second timestamps, and may add a few to
finish the last second. When `truncated` is true there are probably more: page on
with start set to the last tick's time (or end set to the first tick's time); ticks
in that same second can repeat.

Needs market-data permissions for the instrument. Paced like small bars (about 60
requests per 10 minutes; BID_ASK counts double), so prefer get_historical_bars for
anything longer than minutes of activity.

Errors: not_found (no ticks in the range), invalid_request (both or neither
of start/end), rate_limit, ib_api_error 162 (pacing, permissions).

Inputs: contract (required), end, count, start, +3 more. Returns: Historical ticks for one contract, oldest first.

get_market_ruleMarket rulesA
Read-only

Return the price increments (tick ladder) of IBKR market rules.

A contract's valid price steps can depend on the price level and exchange: each rule
lists rows of (low_edge, increment), meaning prices from low_edge up to the next row's
low_edge move in steps of increment. Get the ids from get_contract_details; its
market_rule_ids line up with valid_exchanges. Use it to round limit prices correctly.

IBKR answers each rule within a second or not at all: ids it did not answer (probably
unknown) are listed in `missing_ids`; if none was answered the call fails with
not_found.

Inputs: market_rule_ids (required). Returns: Market rules in the order requested.

get_news_articleNews articleA
Read-only

Return the full text of a news article, given its provider code and article id.

Take both from a headline (get_historical_news or a news subscription). HTML
articles are converted to plain text unless plain_text is false. Text longer than
max_chars (default 20000) is cut and truncated is true; total_chars gives the full
length. Binary articles (PDFs) are reported with article_type=binary and their
size, not returned. Needs a subscription to the provider.
Errors: ib_api_error with IBKR's message when the article is unknown or not
permitted; not_found when IBKR sends an empty article.

Inputs: article_id (required), provider_code (required), max_chars, plain_text. Returns: The body of one news article, cut at ``max_chars`` when longer.

get_news_providersNews providersA
Read-only

List the news providers this IBKR login can use through the API (code and name).

Use the codes with get_historical_news, get_news_article and subscribe_news. Only
subscribed providers are listed; the free API feeds (BRFG Briefing.com General
Market Columns, BRFUPDN Briefing.com Analyst Actions, DJNL Dow Jones Newsletters)
must still be enabled in IBKR's market data subscriptions. Errors: not_found when
the login has none.

Inputs: no named parameters. Returns: The news providers available to this login through the API.

get_open_ordersOpen ordersA
Read-only

List the account's working orders: status, filled/remaining quantity and prices.

`modifiable` is true only for orders this server placed (same API client id): only
those can be modified or cancelled with the order tools. Orders of other API clients
and manual TWS orders are shown for information. Filled and cancelled orders are
left out; see get_completed_orders. When the gateway's API is read-only (get_health:
api_read_only), IBKR refuses the request for this server's orders alone, so
include_other_clients=false reads every client's orders and keeps this server's;
`note` says so. Errors: ib_api_error 321, at once, if IBKR refuses open orders
altogether on a read-only API.

Inputs: account, include_other_clients. Returns: Working orders in one account.

get_option_chainOption chainA
Read-only

List the option expirations and strikes available on an underlying (no prices).

Returns one entry per trading class (e.g. SPX monthly and SPXW weekly), with its
multiplier, the exchanges listing it, all expirations (YYYYMMDD) and all strikes.
Strikes are the union across expirations: not every strike exists for every expiry,
so qualify_contract a specific option before quoting it. This is the cheap way to
explore options; it needs no market data subscription and has no pacing concerns.
For US stock and index options pass exchange SMART: IBKR lists a chain per options
exchange, and chains that differ slightly are not merged, so the full answer can be
long. Quotes and greeks come from the options and market_data tools.

Errors: not_found when the underlying is unknown or has no listed options (or none on
`exchange`); invalid_request when `underlying` is itself an option or combo (also when
given by the con_id of one).

Inputs: underlying (required), exchange, fut_fop_exchange. Returns: The option chains IBKR lists for an underlying (no prices).

get_option_quotesOption chain quotesA
Read-only

Snapshot quotes and greeks for a slice of one option expiration (a mini chain).

Picks the chain for `expiration`, chooses strikes either in [strike_min, strike_max]
or the `strikes_around_atm` strikes nearest the underlying's price (taken from a
snapshot of the underlying), and returns for each option (both rights unless `right`
is set): bid/ask/last with sizes, volume, close, and IBKR's model greeks (implied_vol,
delta, gamma, vega, theta, und_price). Legs are sorted by strike, calls before puts.
`limit` caps the legs (strike and right pairs): default 20, max 40; `total` and
`truncated` say how many were selected (a range keeps the lowest strikes, ATM the
nearest). Strikes the chain lists but this expiration lacks are reported in
`skipped`, as are legs IBKR would not quote.

Market data: one snapshot per leg, using the connection's market data type (see
`market_data_type`; switch with set_market_data_type). Live quotes for US equity and
index options need IBKR's OPRA subscription for API use (plus the underlying's
exchange data; futures options need the futures exchange's data); without it, try
delayed data. Snapshots take a few seconds and up to about 11. For expiries and
strikes without quotes use get_option_chain; to stream one option use subscribe_quotes.

Errors: not_found (unknown underlying, expiration or strikes not listed, or no
underlying price: then pass strike_min/strike_max); invalid_request (bad arguments,
or several trading classes: pass trading_class); ib_api_error when no leg could be
quoted (the message names the subscription needed); subscription_limit when IBKR's
market-data lines are used up.

Inputs: expiration (required), underlying (required), limit, right, +5 more. Returns: Snapshot quotes with greeks for a slice of one option expiration.

get_pnlAccount P&LA
Read-only

Return the account's live P&L: today's (daily), unrealized and realized, in base currency.

One-shot: subscribes to IBKR's P&L feed, waits a few seconds at most for the first
update (usually about a second), and cancels, so every call is a fresh reading and
nothing needs unsubscribing. Errors: request_timeout when IBKR sends nothing (right
after login, or an account without data); retry once before giving up.

Inputs: account, model_code. Returns: Profit and loss for a whole account (or an advisor model), in the base currency.

get_portfolioPortfolioA
Read-only

List an account's positions with market price, market value and unrealized/realized P&L.

Values are in each position's currency and use IBKR's own valuation (no market-data subscription needed); IBKR refreshes them about every 3 minutes. For an account other than the default the call takes a moment longer, because IBKR streams portfolio data for one account at a time.

Inputs: account. Returns: Positions of one account with market values and P&L, in each position's currenc…

get_position_pnlPosition P&LA
Read-only

Return the live P&L of one position: daily, unrealized, realized and market value.

Pass the position's con_id (from get_positions) for an exact match. Waits a few
seconds at most for IBKR's first update. Errors: not_found when the account has no
position and no P&L today in that contract; ambiguous_contract lists candidates;
invalid_request for a combo (BAG: ask per leg); request_timeout when IBKR sends nothing
for a position the account holds (retry once).

Inputs: contract (required), account, model_code. Returns: Profit and loss of one position.

get_positionsPositionsA
Read-only

List an account's positions: contract, quantity (negative = short) and average cost.

Fast and always current (IBKR streams position changes). avg_cost includes
commissions and, for options and futures, the multiplier. For market value and
unrealized P&L use get_portfolio; for today's P&L of one position use
get_position_pnl. `contract.exchange` is not reported for positions; use the con_id
for follow-up calls. `model_code` (financial advisors) lists one model's positions.

Inputs: account, model_code. Returns: Positions held in one account.

get_quotesQuote snapshotsA
Read-only

Get a one-time quote for up to 25 contracts: bid, ask, last, sizes, OHLC, volume.

Each quote also has `halted`, `market_data_type` (live, frozen, delayed or
delayed_frozen), `bbo_exchange` (expand it with get_smart_components) and, for
options, IBKR model greeks and implied volatility. Snapshots take up to about 11
seconds for quiet contracts. A contract with an open quote stream (subscribe_quotes)
is answered from the stream at no extra cost. Generic ticks (shortable shares,
fundamental ratios...) are not available as snapshots; use subscribe_quotes.

Contracts that fail are listed in `errors` (unknown or ambiguous contract, no market
data permission) while the others still get quotes; if all fail, the call fails.
Needs market data permissions for each exchange. Without them IBKR answers with
error 354, 10089 or 10168: call set_market_data_type with 'delayed' for free
15-20 minute delayed data (10089 with delayed already selected: IBKR has no delayed
data for that instrument on this login). Null prices mean IBKR sent no value.

Inputs: contracts (required), regulatory_snapshot. Returns: Quote snapshots, in the order the contracts were requested.

get_scanner_parametersScanner parametersA
Read-only

Browse IBKR's market scanner catalogue to find valid inputs for run_scanner.

Sections:
- scan_codes: what a scan ranks by (e.g. TOP_PERC_GAIN, MOST_ACTIVE, HOT_BY_VOLUME),
  with the instrument types each supports.
- instruments: instrument types (e.g. STK for US stocks, IND.US, FUT.US).
- locations: markets and exchanges (e.g. STK.US.MAJOR, STK.NASDAQ), nested via parent.
- filters: filter tags for run_scanner's `filters` (e.g. avgVolumeAbove), with
  their value type and, for choice filters, the allowed values.
`query` matches codes and names (case-insensitive substring; for filters also the
filter group and category); `instrument` keeps only entries for that instrument
type. Default limit 50, at most 500; `total` says how many matched. The catalogue
is fetched once per gateway session, so the first call can take a few seconds.
Errors: not_found when nothing matches or the instrument type is unknown.

Inputs: section (required), limit, query, instrument. Returns: A slice of IBKR's scanner catalogue; only the list for ``section`` is filled.

get_server_timeGateway server timeA
Read-only

Return the gateway's current time and how far this server's clock is from it.

Useful as a cheap round-trip check that the gateway answers requests, and before time-sensitive requests (historical data end times, order good-till times). IBKR reports whole seconds, so a skew under a second or two is normal.

Inputs: no named parameters. Returns: The gateway's clock compared with this machine's.

get_smart_componentsSMART componentsA
Read-only

Expand a SMART BBO exchange code into the exchanges behind it.

Quotes on SMART-routed contracts carry a `bbo_exchange` code; this lists the
exchanges it stands for, each with IBKR's single-letter code, which tells you where the
best bid and offer come from. The code only comes from market data (get_quotes needs
a market data subscription or delayed data). When IBKR returns no exchanges (e.g.
outside trading hours, or for a code not taken from a quote) the call fails with
not_found.

Inputs: bbo_exchange (required). Returns: The exchanges behind a SMART BBO exchange code.

get_subscription_dataRead subscriptionA
Read-only

Read the latest state of any subscription: quote, order book, ticks, bars, rows, news...

`data` depends on `kind`: quotes → `quote` (+ `extras`); depth → `bids`/`asks`;
tick_by_tick → `ticks`; realtime_bars and bars → `bars`; scanner → `rows`; news →
`headlines`; news_bulletins → `bulletins`; display_group → `current` and `updates`.
Time series (ticks, bars, headlines, bulletins, display group updates) come oldest
first, cut to the newest `limit` (default 100, max 5000) after `since`;
`data.truncated` is true when older ones were left out.
Stream snapshots also carry `active`, `error` and `notices` (IBKR messages such as
delayed data or a lost subscription). `stale` true means the gateway connection
dropped and values may be old. Each read keeps the subscription alive; one not read
for its idle time is cancelled and this tool then reports subscription_not_found.

Inputs: subscription_id (required), limit, since. Returns: The latest state of one subscription. The shape of ``data`` depends on ``kind``…

get_trading_scheduleTrading scheduleA
Read-only

Return an instrument's trading sessions (start, end, trading date) for recent days.

Times are in the exchange's time zone with the offset included, so holidays, early
closes and overnight sessions show up as they really were. For the upcoming
sessions, get_contract_details also lists trading and liquid hours. Counts toward
IBKR's historical-data limits.

Errors: not_found (no such contract, or no sessions in the range).

Inputs: contract (required), end, use_rth, num_days. Returns: Trading sessions for a range of days.

get_user_infoUser infoA
Read-only

Return details about the logged-in IBKR user: the white-branding id, if any.

The id identifies an introducing broker's white-labelled platform; it is empty for
most direct IBKR clients.

Inputs: no named parameters. Returns: Details about the logged-in user.

get_wsh_eventsWSH corporate eventsA
Read-only

List Wall Street Horizon corporate events: earnings dates, dividends, splits, meetings.

Also shareholder and board meetings, conferences and more (get_wsh_metadata lists
the event types). Give a contract, event_types, a raw filter_json, or
fill_portfolio/fill_watchlist; narrow by start_date/end_date. Returns at most `limit`
events (default 50, max 100); each event is the JSON object WSH sends (event type
tag, dates, company, details), and `request` shows what was asked of IBKR.
truncated=true means more events may exist: narrow the dates to page through them.
The WSH metadata is requested automatically first, as IBKR requires. Needs a Wall
Street Horizon corporate event data subscription (paid) on the IBKR login; without
it IBKR answers with an ib_api_error.

Errors: not_found (no events match: widen the dates or check event_types),
invalid_request (unknown event type, bad filter_json, dates in the wrong order,
nothing to ask for), account_not_allowed (fill_portfolio on a login with accounts
outside the allowlist).

Inputs: limit, contract, end_date, start_date, +5 more. Returns: Corporate events from Wall Street Horizon, in the order IBKR returned them.

get_wsh_metadataWSH metadataA
Read-only

Describe the Wall Street Horizon (WSH) event calendar: event types and filter fields.

Use it to build get_wsh_events queries: `event_types` lists the event type tags
(wshe_ed is the earnings date, for example) and `metadata_json` holds the full
description, filtered by `query` and cut at max_chars (default 30000, max 200000).
The metadata is fetched once and then served from this server's cache (`cached`).
Needs a Wall Street Horizon corporate event data subscription (paid) on the IBKR
login; without it IBKR answers with an ib_api_error. not_found means nothing matched
`query`.

Inputs: query, max_chars. Returns: Wall Street Horizon metadata: the event types and filters WSH queries can use.

list_accountsAccounts in scopeA
Read-only

List the IBKR accounts this server may use, and which one is the default.

Account-scoped tools use `default_account` when called without an account. If it is
null, the login manages several accounts and you must pass one explicitly. Paper
accounts start with D. Accounts outside the server's allowlist are only counted
(`other_managed_accounts`), never named, and cannot be used.

Inputs: no named parameters. Returns: The accounts in scope for this server.

list_subscriptionsList subscriptionsA
Read-only

List every open subscription of every kind: quotes, depth, ticks, bars, scans, news...

For each: its id, kind, key, contract, parameters, when it was created and last
read, when it will be cancelled for being idle (`idle_expires_at`), and `stale`
(true while the gateway connection is down). Also shows capacity: subscriptions
used out of the server maximum, and market depth and tick-by-tick streams used out
of IBKR's limits, plus the connection's current market data type.

Inputs: no named parameters. Returns: Open subscriptions and how much capacity is left.

qualify_contractQualify contractA
Read-only

Resolve a contract spec to exactly one IBKR contract and return it with its con_id.

Use it to check a spec before quoting or ordering, or to turn a symbol into a con_id;
later calls can then pass just the con_id. The returned `description` is the long name
(e.g. APPLE INC) to confirm it is the intended instrument.

If several contracts match (e.g. a stock listed on two exchanges, or an option spec
without trading class), the call fails with ambiguous_contract and the message lists
up to 20 candidates with their con_ids: retry with the right con_id or more fields
(primary_exchange, currency, trading_class...). An unknown spec fails with not_found;
a combo (BAG) with invalid_request (qualify each leg by con_id instead).

Inputs: contract (required). Returns: A contract as IBKR knows it; ``con_id`` identifies it in later calls.

run_scannerRun a market scanA
Read-only

Run an IBKR market scan once and return the ranked instruments, best first.

Example: top % gainers among US listed stocks above $5 is scan_code=TOP_PERC_GAIN,
instrument=STK, location_code=STK.US.MAJOR, above_price=5. Find other scan codes,
locations and filter tags with get_scanner_parameters. Each row has the rank
(1 = top) and the contract (with con_id, for quotes or orders).
Limits: at most 50 rows. IBKR allows 10 scanner subscriptions at a time; a run
uses one for a moment and always releases it. Scans need market data permissions
for the exchanges scanned.
Errors: not_found when nothing matches right now (loosen the filters, or the
market may be closed); ib_api_error with IBKR's message for an unknown scan code,
location or filter; subscription_limit when 10 scanner subscriptions are open.

Inputs: scan_code (required), rows, filters, instrument, +6 more. Returns: The result of a one-shot scan, best first.

search_symbolsSearch symbolsA
Read-only

Find instruments by ticker prefix or company name (IBKR's symbol search).

Returns up to `limit` matches (default 16, IBKR rarely sends more): each with its
con_id, symbol, sec_type, primary exchange, currency, name (`description`) and the
derivative types listed on it (OPT, FUT, WAR...). Use it to discover a symbol or its
con_id, then call qualify_contract or get_contract_details for the exact contract.

Limits: discovery only, not exhaustive (no options or futures months in the results;
use get_option_chain or get_contract_details for those). IBKR allows about one search
per second, so back-to-back searches are spaced out. Errors: not_found when nothing
matches; request_timeout when IBKR did not answer within 4 seconds.

Inputs: pattern (required), limit. Returns: Instruments matching a symbol or name pattern, best matches first.

set_market_data_typeSet market data typeA
Idempotent

Switch the whole gateway connection between live, frozen, delayed and delayed-frozen data.

Applies to every market data request made afterwards (get_quotes and new streams),
for every tool, and is kept across reconnects. Use 'delayed' when quotes fail with
error 354, 10089 or 10168 (no live market data subscription). With live selected,
IBKR still falls back to delayed data where it can (each quote says which it got).
Delayed data has no market depth and no tick-by-tick data. Open streams keep what
they had until you unsubscribe and subscribe again.

Inputs: data_type (required). Returns: The market data type the connection now requests.

subscribe_barsStream live barsA
Read-only

Load recent bars of any size and keep the newest bar updating live.

First loads `duration` of history (like get_historical_bars), then IBKR updates the
last bar and appends new ones as time passes. get_subscription_data returns the
bars oldest first (the newest 100 by default; the server keeps up to 5000). One
stream per contract and parameter set: subscribing again returns the same handle.
Counts against IBKR's historical data pacing (about 60 requests per 10 minutes;
error 162 on a violation) and needs market data permissions. Stop it with
unsubscribe.

Errors: not_found if IBKR has no bars for the period (try a longer duration or
use_rth=false), ib_api_error 321 if IBKR rejects the combination of bar size,
duration and what_to_show (the message names the field).

Inputs: bar_size (required), contract (required), use_rth, duration, +1 more. Returns: A handle to a server-side stream, as every ``subscribe_*`` tool returns it. Rea…

subscribe_market_depthStream market depthA
Read-only

Start streaming the order book (Level II market depth) of one contract.

get_subscription_data returns `bids` and `asks` as levels (position 0 is the best
price) with price, size and market maker or venue. IBKR allows only 3 depth
streams at a time by default; this server refuses a 4th (unsubscribe one first).
One depth stream per contract: subscribing again returns the same handle with its
original rows and smart_depth. Needs live data (not available when
set_market_data_type chose delayed) and a Level II (depth of book) subscription
for the exchange; get_depth_exchanges lists exchanges that offer depth. Errors:
309 (depth limit), 10092 (no depth for this contract and exchange), 354 (no
subscription).

Inputs: contract (required), rows, smart_depth. Returns: A handle to a server-side stream, as every ``subscribe_*`` tool returns it. Rea…

subscribe_newsStream news headlinesA
Read-only

Stream live news headlines for one instrument, or a provider's whole feed.

Give a contract for headlines about that instrument (from provider_code, or every
subscribed provider), or only a provider_code for that provider's broad tape (all
its headlines, e.g. BRF for Briefing Trader, BZ for Benzinga, FLY for The Fly;
each needs its own subscription). Returns a handle; read the headlines (oldest
first, the newest 200 kept) with get_subscription_data(subscription_id) and fetch
a full story with get_news_article. Uses one market data line. Stop it with
unsubscribe; it is cancelled after idle_ttl_s seconds without a read.
Errors: invalid_request without a contract or provider_code, or when a contract is
given with a provider the login is not subscribed to (see get_news_providers);
ib_api_error when IBKR refuses the stream (no news permission for that provider).

Inputs: contract, provider_code. Returns: A handle to a server-side stream, as every ``subscribe_*`` tool returns it. Rea…

subscribe_news_bulletinsStream IBKR bulletinsA
Read-only

Stream IBKR's system bulletins: notices and exchanges becoming unavailable or available.

Returns a handle; read the bulletins with get_subscription_data(subscription_id)
(each has type news, exchange_unavailable or exchange_available, the message and the
exchange). There is one bulletin stream per gateway connection, so calling this
again returns the same handle, and all_messages only counts the first time. Stop it
with unsubscribe; it is cancelled after idle_ttl_s seconds without a read.

Inputs: all_messages. Returns: A handle to a server-side stream, as every ``subscribe_*`` tool returns it. Rea…

subscribe_quotesStream quotesA
Read-only

Start streaming live top-of-book quotes for one contract (read with get_subscription_data).

Returns a subscription handle. get_subscription_data(subscription_id) then returns
the current quote (bid/ask/last, sizes, OHLC, volume, greeks for options), the
requested generic tick values under `extras`, and IBKR notices. There is one quote
stream per contract: subscribing again returns the same handle (`deduplicated`
true), adding any new generic ticks to it. Each stream uses one of the login's
market data lines (100 by default); streams nobody reads for `idle_ttl_s` seconds
are cancelled, and unsubscribe frees the line at once.

Needs market data permissions (see set_market_data_type for delayed data). If IBKR
refuses the stream right away (354, 10089, 10168, 10197), the call fails with the
reason; later problems show in the data as `active: false` and `error`.

Inputs: contract (required), generic_ticks. Returns: A handle to a server-side stream, as every ``subscribe_*`` tool returns it. Rea…

subscribe_realtime_barsStream 5-second barsA
Read-only

Start streaming 5-second OHLCV bars for one contract into a ring buffer.

A new bar arrives every 5 seconds; get_subscription_data returns them oldest first
with open, high, low, close, volume, VWAP and trade count. Only 5-second bars exist;
for other sizes use subscribe_bars. One stream per contract, what_to_show and
use_rth: subscribing again returns the same handle. Uses a market data line and
counts against IBKR's historical data pacing. Needs market data permissions; TRADES
is not available for forex (use MIDPOINT). Errors 420 and 162 mean IBKR refused the
request (invalid for the contract, or pacing). Stop it with unsubscribe.

Inputs: contract (required), use_rth, buffer_size, what_to_show. Returns: A handle to a server-side stream, as every ``subscribe_*`` tool returns it. Rea…

subscribe_scannerStream a market scanA
Read-only

Keep a market scan running so its ranking follows the market; returns a handle.

Takes the same arguments as run_scanner. Read the current rows with
get_subscription_data(subscription_id): rows (best first), updated_at, no_matches
(nothing qualifies right now) and error. Stop it with unsubscribe; it is also
cancelled after the idle time in idle_ttl_s without a read. The same scan asked
for twice returns the existing handle (deduplicated=true).
Limits: at most 50 rows; IBKR allows 10 scanner subscriptions at a time.
Errors: ib_api_error when IBKR rejects the scan (check the codes with
get_scanner_parameters); subscription_limit when no slot is free.

Inputs: scan_code (required), rows, filters, instrument, +6 more. Returns: A handle to a server-side stream, as every ``subscribe_*`` tool returns it. Rea…

subscribe_tick_by_tickStream tick-by-tick dataA
Read-only

Start recording every trade, quote change or midpoint of one contract into a ring buffer.

get_subscription_data returns the buffered ticks oldest first (use its `since` and
`limit` to page). Times are when the tick reached this server (UTC). IBKR allows
only about 3 tick-by-tick streams at a time; this server refuses more. One stream
per contract and tick_type: subscribing again returns the same handle. Needs live
data and a market data subscription for the instrument (not available with delayed
data); errors 10189 and 10190 mean IBKR refused it or its limit is reached. Stop it
with unsubscribe.

Inputs: contract (required), tick_type (required), buffer_size, ignore_size. Returns: A handle to a server-side stream, as every ``subscribe_*`` tool returns it. Rea…

unsubscribeUnsubscribeA
Idempotent

Cancel one subscription, or all of them, and free their IBKR market data lines.

Pass either `subscription_id` or `all=true`. Works for every kind of subscription
(quotes, depth, tick-by-tick, bars, scanners, news, bulletins, display groups).
Subscriptions belong to the server, not to one client: `all=true` also stops streams
that other clients of this server opened.

Inputs: all, subscription_id. Returns: What ``unsubscribe`` cancelled.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 50 tools

    Disambiguation4/5

    Most tools have clearly distinct purposes, aided by extremely detailed descriptions that cross-reference alternatives (e.g. snapshot vs. streaming, historical vs. real-time). However, several near-pairs such as get_quotes vs. subscribe_quotes, get_historical_bars vs. subscribe_bars, and get_pnl vs. get_position_pnl require careful reading to avoid misselection, and the sheer breadth raises cognitive load.

    Naming Consistency5/5

    Names follow a predictable snake_case verb_noun pattern throughout (get_*, subscribe_*, list_*, calculate_*, run_scanner, search_symbols, qualify_contract). The few bare verbs like unsubscribe fit naturally into the subscription-management family, so the set is highly consistent.

    Tool Count2/5

    50 tools is far above the typical well-scoped range of 3–15 and feels heavy even for a broad gateway. While each tool has a discernible function, the granular split between snapshot/stream/historical and diagnostic tools suggests over-decomposition that burdens an agent.

    Completeness2/5

    The surface covers data, accounts, news, scanners, options, and fundamentals well, but it critically lacks any order placement, modification, or cancellation tools. Descriptions repeatedly reference 'order tools' and a trading gate, so the absence of a core trading surface is a significant gap for an IB gateway MCP.

    Maintenance

    ActivitySlowing
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      Not graded
      maintenance
      Enables users to interact with Interactive Brokers' official Web API through MCP, supporting account management, reporting, and other brokerage operations via the Client Portal Gateway for retail authentication.
      -
    • F
      license
      Not graded
      quality
      A
      maintenance
      Enables MCP clients to interact with Interactive Brokers' official Web API through a Client Portal Gateway, exposing brokerage account, market data, and trading functionality via authenticated HTTP endpoints.
      -
    • F
      license
      Not graded
      quality
      A
      maintenance
      Enables MCP clients to access Interactive Brokers' Web API for brokerage interactions, including account management, reporting, and endpoint-based trading workflows. It connects via the Client Portal Gateway to provide authenticated, cloud-ready access to IBKR services.
      -
    • F
      license
      Not graded
      quality
      B
      maintenance
      Enables MCP-compatible clients to interact with Interactive Brokers through its official Web API, supporting account management, portfolio reporting, market data, and trading operations.
      -