API.md•6.63 kB
# IBKR TWS MCP Server API Reference
This document provides a reference for the Model Context Protocol (MCP) tools exposed by the IBKR TWS MCP Server. The server is implemented using the FastMCP framework and is accessible via HTTP at the `/api/v1` prefix.
## Introduction
This document lists all MCP tools exposed by the IBKR TWS MCP Server. The server leverages the `ib_async` Python library (maintained fork of ib-insync) to interact asynchronously with the Interactive Brokers TWS API.
All tools are prefixed with `ibkr_` and are designed to be asynchronous, reflecting the `ib_async` library's nature.
| Tool Name | Description | Parameters | Returns |
| :--- | :--- | :--- | :--- |
| **ibkr_connect** | Connect to IBKR TWS or IB Gateway. | `host` (str), `port` (int), `clientId` (int) | `{"status": "connected", ...}` |
| **ibkr_disconnect** | Disconnect from TWS/IB Gateway. | None | `{"status": "disconnected"}` |
| **ibkr_get_status** | Get the current connection status. | None | `{"is_connected": bool}` |
| **ibkr_get_contract_details** | Get contract details for a given symbol. | `symbol` (str), `secType` (str, default: STK), `exchange` (str, default: SMART), `currency` (str, default: USD) | List of contract detail objects. |
| **ibkr_get_historical_data** | Get historical market data for a contract. | `symbol` (str), `durationStr` (str, default: 1 Y), `barSizeSetting` (str, default: 1 day), `whatToShow` (str, default: TRADES), `secType`, `exchange`, `currency` | List of historical bar objects. |
| **ibkr_stream_market_data** | Stream real-time market data for a symbol for a given duration. | `symbol` (str), `duration_seconds` (int, default: 60), `secType`, `exchange`, `currency` | `{"symbol": str, "updates_count": int, "message": str}` (updates are sent via `ctx.info`) |
| **ibkr_get_account_summary** | Get overall account summary metrics. | None | List of account summary objects. |
| **ibkr_get_positions** | Get current portfolio positions. | None | List of position objects. |
| **ibkr_stream_account_updates** | Stream real-time account and position updates for a given duration. | `account` (str), `duration_seconds` (int, default: 60) | `{"account": str, "updates_count": int, "message": str}` (updates are sent via `ctx.info`) |
| **ibkr_get_pnl** | Get overall Profit and Loss. | None | PnL object. |
| **ibkr_get_pnl_single** | Get PnL for a single account/model. | `account` (str), `modelCode` (str) | PnL single object. |
| **ibkr_place_order** | Place an order. | `symbol` (str), `action` (str, BUY/SELL), `totalQuantity` (int), `orderType` (str, default: MKT), `lmtPrice` (float, optional), `secType`, `exchange`, `currency` | Order status object. |
| **ibkr_cancel_order** | Cancel an order by ID. | `orderId` (int) | Order status object. |
| **ibkr_get_open_orders** | Get all open orders. | None | List of open order objects. |
| **ibkr_get_executions** | Get all executions. | None | List of execution objects. |
## 2. End-to-End Testing with Claude MCP Inspector
The **Claude MCP Inspector** is a powerful web-based tool for testing and interacting with any MCP-compliant server, including this IBKR TWS MCP Server. It allows you to directly invoke the exposed tools and observe the streaming responses, simulating how an LLM client would interact with your server.
### Prerequisites
1. **Running TWS/IB Gateway:** The Interactive Brokers Trader Workstation (TWS) or IB Gateway must be running and logged in, preferably in **Paper Trading** mode.
2. **Running MCP Server:** Your `ibkr-tws-mcp-server` must be running and publicly accessible. For local testing, you can use a tunneling service like `ngrok` to expose your local `http://localhost:8000` to the internet.
### Step-by-Step Usage Guide
1. **Start the MCP Server**
Run the server locally using the `uvicorn` command:
```bash
uv run python main.py
```
The server will typically start at `http://0.0.0.0:8000`.
2. **Expose the Local Server (if necessary)**
If you are running the Inspector on a different machine or want to use the public Inspector URL, you must expose your local server. For example, using `ngrok`:
```bash
ngrok http 8000
```
This will provide a public URL (e.g., `https://xxxx-xxxx-xxxx.ngrok-free.app`).
3. **Open the Claude MCP Inspector**
Navigate to the Inspector URL: **`https://www.claudemcp.com/inspector`**
4. **Configure the Server Endpoint**
In the Inspector interface, locate the **"Server Endpoint"** input field and enter the full URL to your server's MCP endpoint:
* **Local (Advanced Users):** `http://localhost:8000/api/v1`
* **Public (Recommended):** `https://xxxx-xxxx-xxxx.ngrok-free.app/api/v1`
Click the **"Connect"** button. The Inspector will fetch the server's manifest, and the list of available tools will populate the sidebar.
5. **Invoke Tools for E2E Testing**
The E2E workflow for portfolio rebalancing can be tested by invoking the tools in sequence:
* **A. Connect to TWS:**
* Select the **`ibkr_connect`** tool.
* Enter the TWS connection parameters (e.g., `host: 127.0.0.1`, `port: 7496`, `clientId: 1`).
* Click **"Invoke"**. The response should confirm `{"status": "connected"}`.
* **B. Get Data:**
* Select **`ibkr_get_historical_data`** (e.g., for symbol VTI).
* Select **`ibkr_get_account_summary`** and **`ibkr_get_positions`**.
* Invoke each tool and verify the returned data structure and content.
* **C. Stream Data (Optional):**
* Select **`ibkr_stream_market_data`** (e.g., for symbol SPY).
* Set a short `duration_seconds` (e.g., 10).
* Click **"Invoke"**. You will see the streaming updates appear in the Inspector's output panel as Server-Sent Events (SSE) messages, demonstrating the real-time capability.
* **D. Order Management:**
* Select **`ibkr_place_order`** and enter a test order (e.g., BUY 1 share of AAPL).
* Select **`ibkr_get_open_orders`** and **`ibkr_get_executions`** to monitor the order lifecycle.
6. **Analyze the Output**
The Inspector's output panel displays the full MCP request and response cycle, including the tool call arguments and the returned data. For streaming tools, it clearly separates the final JSON response from the intermediate `ctx.info()` messages, which is crucial for debugging the server's real-time communication.
This process provides a robust way to manually verify all server functionalities and ensure the server is ready for integration with an LLM client.