Skip to main content
Glama
jotorresro

mcp-ibkr

by jotorresro

mcp-ibkr

Claude Code를 Interactive Brokers(IBKR)에 연결하기 위한 자체 MCP(Model Context Protocol) 서버로, Paper Trading 계정에서 읽기 전용 모드로 시작합니다.

프로젝트 상태: 12개 중 12개 단계 완료. "현재 상태" 섹션 참조.

1. 이 프로젝트가 무엇인가

Claude Code와 IBKR 사이의 다리: Claude Code가 이 서버를 실행하고, 서버는 "도구"(이름과 설명이 있는 함수)를 노출하며, 사용자가 계정, 포지션 또는 시장 정보를 요청할 때 Claude가 이를 사용합니다. 어떤 도구도 IBKR과 직접 통신하지 않습니다. 모든 도구는 중앙 집중식 통합 계층을 거칩니다.

Related MCP server: IB Portfolio Tracker MCP Server

2. 아키텍처

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. 폴더 구조

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. 요구 사항

  • Python 3.11+ (3.14로 테스트됨).

  • Git.

  • curl (섹션 5에서 get-pip.py 및 섹션 6에서 IB Gateway 설치 프로그램을 다운로드하기 위해).

  • IB Gateway 설치, Paper Trading 세션으로 로그인됨 (섹션 6 참조).

5. 설치 및 구성

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

requirements.txt에 대한 참고: 4개의 패키지만 직접 설치합니다 (mcp, ib_async, python-dotenv, pytest), 하지만 파일에는 pip freeze가 해당 패키지의 종속성(그 종속성의 종속성)도 포함하기 때문에 더 많은 줄이 있습니다. 정상입니다 — 프로젝트가 해당 라이브러리를 모두 직접 사용한다는 의미는 아닙니다.

참고: Debian/Ubuntu 시스템에서 python3 -m venv 단독으로는 시스템 패키지 python3-venv가 없으면 실패할 수 있습니다 (sudo apt install python3-venv로 설치). sudo 액세스 권한이 없는 경우, --without-pip + venv 내부에 pip를 수동으로 설치하는 조합(위 단계)은 관리자 권한 없이도 동일하게 격리된 환경을 제공합니다.

6. IBKR 연결 (Paper Trading)

  1. IB Gateway 설치 (공식 다운로드, 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. 열고 "Paper Trading" ( "Live Trading"이 아님)을 명시적으로 선택하여 로그인하고, Paper Trading 사용자 이름/비밀번호를 사용합니다.

  3. API 포트가 4002 (Paper)인지 확인합니다. 다음과 같이 확인할 수 있습니다:

    ss -ltnp | grep 4002   # deberia aparecer un proceso "java" escuchando
  4. .env.example.env로 복사하고 (아직 안 했다면) 구성이 다른 경우 값을 조정합니다.

이것이 안전한 이유: src/config/settings.pyIBKR_PORT가 정확히 4002가 아니면 시작을 거부하고, IBKR_PAPER_TRADING_CONFIRMEDtrue가 아니어도 거부합니다. 또한 연결(src/ibkr/connection.py)은 readonly=True로 열리므로, IB Gateway는 주문 도구가 존재하기 전에도 API 수준에서 주문 전송 시도를 거부합니다.

7. Claude Code 구성

서버는 .mcp.json (프로젝트 루트)에 project 범위로 등록되어 있습니다. 이는 파일이 Git에 버전 관리되고 이 저장소를 Claude Code에서 여는 사람은 누구나 제안된 서버를 볼 수 있음을 의미합니다 — 하지만 자동으로 실행되지는 않습니다: Claude Code는 이 폴더에서 세션을 열고 승인할 때까지 "Pending approval"로 표시합니다.

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

언제든지 서버 상태를 확인하려면:

claude mcp list
claude mcp get mcp-ibkr

제거하려면:

claude mcp remove mcp-ibkr -s project

8. 사용 가능한 도구

도구

카테고리

위험

상태

설명

verificar_conexion_ibkr

account

READ_ONLY

활성

IB Gateway(Paper Trading)와의 활성 연결을 확인하고 표시되는 계정을 나열합니다.

consultar_resumen_cuenta

account

READ_ONLY

활성

순자산, 사용 가능한 현금, 구매력 및 마진.

consultar_precio_mercado

market

READ_ONLY

활성

주식의 최신 가격, 매수/매도 호가, 이전 종가 및 거래량.

consultar_datos_historicos

market

READ_ONLY

활성

주식의 과거 OHLCV 캔들.

consultar_posiciones

positions

READ_ONLY

활성

열린 포지션 (전체 또는 심볼로 필터링).

consultar_pnl

positions

READ_ONLY

활성

계정의 일일, 미실현 및 실현 손익.

consultar_ordenes

orders

READ_ONLY

활성

열린 주문 및 상태를 나열합니다.

crear_orden

orders

ACTION

비활성

MKT/LMT 주문을 생성합니다. 이중 활성화 필요 (섹션 11 참조).

cancelar_orden

orders

ACTION

비활성

orderId로 열린 주문을 취소합니다. 이중 활성화 필요.

9. 도구 추가 / 수정 / 삭제 / 비활성화 방법

각 도구는 src/tools/<categoria>/ 내의 하나의 파일이며, 다음과 같은 형식입니다 (실제 예로 src/tools/account/verificar_conexion_ibkr.py 참조):

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"

함수는 NAME과 동일하게 호출되어야 합니다 — 그래야 중앙 등록부(src/tools/registry.py)가 자동으로 찾습니다. RISK_LEVELACTION인 경우, ENABLED = True 외에도 .envIBKR_ENABLE_ACTION_TOOLS=true가 필요합니다 (섹션 11 참조) — 의도적으로 독립적인 두 개의 키입니다.

ANNOTATIONS에 대해: destructiveHintidempotentHintreadOnlyHint=False일 때만 의미가 있습니다 (MCP 사양에 문서화됨) — 그래서 읽기 전용 도구에서는 readOnlyHintopenWorldHint만으로 충분합니다. RISK_LEVELACTION인 경우에만 추가하세요. src/tools/orders/crear_orden.py에서와 같이.

도구 추가

  1. 해당 카테고리에 파일을 생성합니다 (또는 새 카테고리 생성, 아래 참조).

  2. 해당 카테고리의 __init__.py에 있는 TOOLS 목록에 파일 이름(.py 제외)을 추가합니다.

  3. Claude Code 세션을 다시 시작하여 인식하게 합니다 (Claude Code는 서버 시작 시 도구를 한 번만 읽습니다; claude mcp list는 연결 상태만 확인하고 아무것도 다시 로드하지 않습니다).

도구 수정

파일을 직접 편집합니다 — DESCRIPTION, 함수 매개변수, 내부 로직 등. registry.py를 건드릴 필요가 없습니다.

도구 삭제

파일을 삭제하고 해당 카테고리의 __init__.py에 있는 TOOLS에서 이름을 제거합니다.

도구 비활성화 (삭제하지 않고)

파일에서 ENABLED = False로 설정합니다. registry.py가 자동으로 건너뜁니다.

새 카테고리 생성

TOOLS: list[str] = [...]를 정의하는 __init__.py와 함께 src/tools/<categoria>/ 폴더를 만들고, src/tools/registry.pyCATEGORIES에 카테고리 이름을 추가합니다.

10. 테스트

cd ~/mcp-ibkr
.venv/bin/python3 -m pytest tests/ -v
  • tests/test_server.py — 서버가 시작되고 예상 도구를 노출합니다 (Claude Code가 연결할 때 보는 것과 동일); 읽기 전용 도구는 적용되지 않는 주석을 설정하지 않습니다; 각 도구는 IBKR을 사용할 수 없을 때 예외를 노출하는 대신 친숙한 메시지로 응답합니다.

  • tests/test_settings.py — 구성이 4002가 아닌 포트와 IBKR_PAPER_TRADING_CONFIRMED 부재를 거부합니다.

  • tests/test_connection.py — 연결 계층이 연결 시도를 직렬화합니다 (시뮬레이션된 IBKR 사용, 실제 Gateway 불필요): 두 도구가 거의 동시에 호출되면 병렬로 실행되는 연결 시도가 없습니다.

  • tests/test_risk_system.pyACTION 도구(crear_orden, cancelar_orden)는 기본적으로 등록되지 않으며, 주문 검증(수량, 유형, 가격)은 잘못된 매개변수를 거부합니다.

  • tests/test_ibkr_integration.py — IB Gateway에 대한 실제 연결. Gateway가 실행 중이 아니면 이 테스트는 건너뜁니다 (실패하지 않음) — 예상된 동작이며 프로젝트 오류가 아닙니다.

주문 관련 모든 테스트는 validar_parametros_orden을 격리된 방식으로 사용하거나(IBKR을 건드리지 않음) crear_orden이 기본적으로 비활성화되어 있다는 사실에 의존합니다: 이 프로젝트의 어떤 테스트도 실제 주문을 보내지 않습니다, Paper Trading에서도 마찬가지입니다.

11. Paper Trading에서 Live Trading으로

⚠️ Live Trading은 아직 이 프로젝트에서 지원되지 않으며, crear_orden/cancelar_orden은 기본적으로 비활성화되어 있습니다. 다음은 보안 계층에 대한 설명이지, 생각 없이 활성화하라는 초대가 아닙니다.

실제 주문이 실수로 전송되는 것을 방지하는 세 가지 독립적인 계층이 있습니다:

  1. 필수 포트 4002src/config/settings.pyIBKR_PORT가 Paper Trading의 정확한 값이 아니면 시작을 거부합니다. 이 프로젝트 버전에는 포트 4001(Live)을 사용하는 코드 경로가 전혀 없습니다.

  2. ACTION 도구에 대한 이중 키crear_ordencancelar_orden은 자체 파일에서 ENABLED = True .env에서 IBKR_ENABLE_ACTION_TOOLS=true가 필요합니다. 둘 다 기본적으로 활성화되어 있지 않습니다. 둘 다 서버 시작 시에만 읽힙니다: 서버가 이미 실행 중일 때 변경하면 변경 사항을 적용하려면 Claude Code 세션을 다시 시작해야 합니다.

  3. API 수준의 읽기 전용 연결IBKR_ENABLE_ACTION_TOOLSfalse인 동안 src/ibkr/connection.pyreadonly=True로 연결됩니다: 누군가 이전 두 계층을 우회하더라도 IB Gateway는 모든 주문을 거부합니다.

향후 Paper Trading에서 주문 전송을 활성화하기로 결정한다면, 경로는 다음과 같습니다: src/tools/orders/crear_orden.py의 검증을 검토하고 강화하고, .envIBKR_ENABLE_ACTION_TOOLS=true를 설정하고, 주문 파일에서 ENABLED = True로 설정합니다. 실제 Live Trading 지원은 이 프로젝트에서 구현되지 않았고 계획에도 없습니다 — 고려하기 전에 완전히 별도의 보안 검토가 필요할 것입니다.

12. 현재 상태

  • 1단계 — 아키텍처 및 개념

  • 2단계 — 최소 프로젝트 구조

  • 3단계 — 개발 환경

  • 4단계 — 최소 MCP 서버

  • 5단계 — Claude Code를 MCP에 연결

  • 6단계 — 첫 번째 테스트 도구

  • 7단계 — IB Gateway 연결 (Paper Trading)

  • 8단계 — 조회 도구

  • 9단계 — 검증 및 위험 시스템

  • 10단계 — 주문 도구 (차단됨)

  • 11단계 — 전체 테스트

  • 12단계 — 최종 문서화

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