# Master Guide: Connecting AI Harnesses, Claude, Cursor & Custom Agents

TM Pro is built from the ground up to work not only for human clicks, but also as a **governed execution harness for AI coding and trading agents** (**Claude Desktop**, **Claude Code**, **Cursor**, **Antigravity**, **local Ollama**, and custom **Python / Node / Webhook** scripts).

Most importantly, **no AI harness can bypass your safety rules**:

* Every AI request goes through the exact same **Order Planner** and **Risk Guard** (`Max Risk %`, `Max Daily Loss %`, `Max Lots`, `Stop Loss Required`) as the manual Order Ticket.
* When **"Ask me before trading"** is enabled on an agent token (the default), any trade proposed by an AI harness pauses and surfaces an **Approve / Reject card** at the top of your TM Pro window—so **you** always have the final click.



***

## Part 1: Creating a Scoped Agent Token (`Agents` Tab)[​](#part-1-creating-a-scoped-agent-token-agents-tab "Direct link to part-1-creating-a-scoped-agent-token-agents-tab")

Before connecting any external AI harness (Claude, Cursor, or a script), issue it a dedicated token so you can control its permissions and revoke it at any time:

1. Open the **TM Pro** desktop app and click the **Agents** tab (`Bot` icon).

2. In the **New agent token** card:

   

   * **Name**: Give the harness a clear name (for example, `Claude Code`, `Cursor IDE`, or `My Python Bot`).

   * **Scopes**:

     

     * **`read`**: Allows the AI harness to inspect your connected terminals, live prices, account balance/equity, open positions, and **AI Quant Regime signals** (`Hurst`, `ATR`, `Quarter-Kelly`, `VaR`). Cannot place or modify trades.
     * **`trade`**: Allows the AI harness to preview orders, place orders, modify stops, and close positions (subject to your Risk Guard and Approval setting).
     * **`admin`**: Full administrative scope.

   * **`Ask me before trading` Checkbox**:

     

     * **Keep this CHECKED (`ON`)** (Recommended): Whenever the AI harness calls `place_order`, `modify_position`, or `close_position`, TM Pro pauses the command and shows an **Approval Card** at the top of your window for you to click **Approve** or **Reject**.
     * **Uncheck (`OFF`)**: Allows the AI harness to execute trades autonomously without waiting for a click (still strictly bounded by your **Risk Guard** limits in `Settings`!).

3. Click **Create**.

4. **Copy the yellow token banner immediately** (it starts with `tmpro_...`). For security, TM Pro stores only the `SHA-256` hash on disk and never displays the raw token again.

***

## Part 2: Connecting Claude Code, Claude Desktop & Cursor via MCP[​](#part-2-connecting-claude-code-claude-desktop--cursor-via-mcp "Direct link to Part 2: Connecting Claude Code, Claude Desktop & Cursor via MCP")

TM Pro ships with a native **Model Context Protocol (MCP)** stdio server located at `app/dist/mcp/tmpro-mcp.js`. Connecting it gives your AI harness direct, typed access to your live MetaTrader terminals.

### Option A — Connect to **Claude Code** (1 Command in Terminal)[​](#option-a--connect-to-claude-code-1-command-in-terminal "Direct link to option-a--connect-to-claude-code-1-command-in-terminal")

Run this single command in PowerShell or Command Prompt (replace `tmpro_YOUR_TOKEN` with the token you copied from the **Agents** tab):

```
claude mcp add tmpro -e TMPRO_TOKEN=tmpro_YOUR_TOKEN -- node "D:/itrad/repos/itradeaims-tmpro/app/dist/mcp/tmpro-mcp.js"
```

Verify it is connected by typing `/mcp` inside Claude Code.

### Option B — Connect to **Claude Desktop**, **Cursor**, or **Antigravity** (`mcp.json`)[​](#option-b--connect-to-claude-desktop-cursor-or-antigravity-mcpjson "Direct link to option-b--connect-to-claude-desktop-cursor-or-antigravity-mcpjson")

Add the `tmpro` block to your MCP configuration file:

* **Claude Desktop**: `%APPDATA%\Claude\claude_desktop_config.json`
* **Cursor**: `.cursor/mcp.json` (or `Cursor Settings -> MCP -> Add new global MCP server`)

```
{

  "mcpServers": {

    "tmpro": {

      "command": "node",

      "args": [

        "D:/itrad/repos/itradeaims-tmpro/app/dist/mcp/tmpro-mcp.js"

      ],

      "env": {

        "TMPRO_TOKEN": "tmpro_YOUR_TOKEN",

        "TMPRO_API_URL": "http://127.0.0.1:17845"

      }

    }

  }

}
```

### All 6 MCP Tools Available to Your AI Harness[​](#all-6-mcp-tools-available-to-your-ai-harness "Direct link to All 6 MCP Tools Available to Your AI Harness")

Once connected, your AI harness can invoke these six tools automatically when you chat with it:

| MCP Tool Name         | Required Scope | What Your AI Harness Can Do With It                                                                                                                                                                 |
| --------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`get_state`**       | `read`         | Reads all connected MT4/MT5 sessions, live Bid/Ask, balance/equity, open positions, risk limits, and the **on-device AI Quant Regime signal** (`Hurst`, `ATR`, `Quarter-Kelly`, `VaR`).             |
| **`preview_order`**   | `read`         | Dry-runs an order (`market`, `limit`, or `stop`) through the lot-size calculator and Risk Guard—returning exact lots, `SL / TP` prices, dollar risk, and any risk errors *without* placing a trade. |
| **`place_order`**     | `trade`        | Submits a `buy` or `sell` order sized by `risk_percent`, `risk_money`, or `lots`, with optional `slPips`, `tpPips`, `breakEven`, `trailing`, and `partialClose` rules.                              |
| **`modify_position`** | `trade`        | Updates the Stop Loss (`sl`) and/or Take Profit (`tp`) price on an open position ticket.                                                                                                            |
| **`close_position`**  | `trade`        | Closes `100%` of an open position, or a partial `volume` (e.g., `50%`).                                                                                                                             |
| **`set_protection`**  | `trade`        | Updates the autonomous EA protection rules (`breakEven`, `trailing`, `partialClose`) on a connected chart.                                                                                          |

### Example Prompts to Give Your Connected AI Harness[​](#example-prompts-to-give-your-connected-ai-harness "Direct link to Example Prompts to Give Your Connected AI Harness")

Try typing any of these prompts into Claude Code, Claude Desktop, or Cursor once `tmpro` MCP is connected:

* *"Inspect my connected MT5 terminal via TM Pro. What is the current EURUSD Hurst regime, Yang-Zhang volatility, and Quarter-Kelly recommendation?"*
* *"Preview a BUY market order on EURUSD using the Quarter-Kelly risk percentage with a 20-pip stop loss and 40-pip take profit. Tell me the exact lot size and dollar risk."*
* *"Place that EURUSD BUY order with a 15-pip break-even trigger and 20-pip trailing stop so I can approve it in TM Pro."*
* *"Check all my open positions across my connected terminals—are any positions missing a stop loss? If any position is up more than 15 pips, move its stop loss to break-even."*

***

## Part 3: Connecting the Built-In AI Assistant (`AI` Tab)[​](#part-3-connecting-the-built-in-ai-assistant-ai-tab "Direct link to part-3-connecting-the-built-in-ai-assistant-ai-tab")

In addition to external MCP harnesses, TM Pro has a built-in **Account-Aware AI Assistant** right inside the **AI** tab. Whenever you ask it a question, TM Pro automatically injects a live JSON summary of your connected terminals, open positions, risk limits, and Quant Regime signals into the system context.

To enable the chat assistant, open the **Settings** tab → **AI assistant** card and configure any OpenAI-compatible provider:

### Option 1 — Free Local AI with **Ollama** (100% Private on Your PC)[​](#option-1--free-local-ai-with-ollama-100-private-on-your-pc "Direct link to option-1--free-local-ai-with-ollama-100-private-on-your-pc")

1. Install [Ollama](https://ollama.com) and pull a model: `ollama run llama3.2` (or `qwen2.5:14b`).

2. In TM Pro **Settings → AI assistant**:

   

   * **Check**: `Enable AI assistant`
   * **Base URL**: `http://127.0.0.1:11434/v1`
   * **Model**: `llama3.2`
   * **API Key**: `ollama` (any non-empty string works for local Ollama)

3. Click **Save AI settings**.

### Option 2 — Cloud Frontier Models (OpenAI / Groq / OpenRouter)[​](#option-2--cloud-frontier-models-openai--groq--openrouter "Direct link to Option 2 — Cloud Frontier Models (OpenAI / Groq / OpenRouter)")

* **OpenAI**:

  

  * **Base URL**: `https://api.openai.com/v1`
  * **Model**: `gpt-4o-mini` or `gpt-4o`
  * **API Key**: Your `sk-...` key (stored locally on your PC, never committed or shared).

***

## Part 4: Connecting Custom Python, Node.js, or Webhook Harnesses via REST (`127.0.0.1:17845`)[​](#part-4-connecting-custom-python-nodejs-or-webhook-harnesses-via-rest-12700117845 "Direct link to part-4-connecting-custom-python-nodejs-or-webhook-harnesses-via-rest-12700117845")

Building your own systematic Python strategy, local TradingView webhook relay, or custom execution script? TM Pro runs a fast, Bearer-authenticated HTTP REST server bound strictly to `127.0.0.1:17845` (local machine only).

### REST Endpoint Reference[​](#rest-endpoint-reference "Direct link to REST Endpoint Reference")

| Method & Path             | Scope   | Description                                                                                                         |
| ------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------- |
| `GET /v1/health`          | *None*  | Returns `{"ok": true, "version": "2.0"}` to verify TM Pro is running.                                               |
| `GET /v1/state`           | `read`  | Returns full JSON snapshot of all sessions, accounts, positions, and `signal` (Quant Regime telemetry).             |
| `POST /v1/orders/preview` | `read`  | Validates and sizes an order request, returning the calculated `plan` and `errors`.                                 |
| `POST /v1/orders`         | `trade` | Submits an `OrderIntent` (`side`, `orderType`, `sizingMode`, `sizingValue`, `slPips`, `tpPips`, `protection`).      |
| `POST /v1/commands`       | `trade` | Submits a general `HubRequest` (`place_order`, `modify_position`, `close_position`, `close_all`, `set_protection`). |

### Ready-to-Run Python Harness Example[​](#ready-to-run-python-harness-example "Direct link to Ready-to-Run Python Harness Example")

```
import requests



TMPRO_URL = "http://127.0.0.1:17845"

HEADERS = {"Authorization": "Bearer tmpro_YOUR_TOKEN"}



# 1. Fetch live multi-terminal state and on-device Quant Regime telemetry

state = requests.get(f"{TMPRO_URL}/v1/state", headers=HEADERS).json()

session = state["sessions"][0]

sid = session["sessionId"]

signal = session.get("signal")



print(f"Connected: {session['hello']['chart']['symbol']} | Equity: ${session['account']['equity']}")

if signal:

    print(f"Quant Regime: {signal['regime']} | Hurst: {signal['metrics']['hurst']} | 1/4-Kelly: {signal['recommendation']['kellyRiskPercent']}%")



# 2. Submit a risk-checked trade using the Quarter-Kelly recommendation

order_payload = {

    "sessionId": sid,

    "side": "buy",

    "orderType": "market",

    "sizingMode": "risk_percent",

    "sizingValue": signal["recommendation"]["kellyRiskPercent"] if signal else 0.5,

    "slPips": signal["recommendation"]["suggestedSlPips"] if signal else 20,

    "tpPips": signal["recommendation"]["suggestedTpPips"] if signal else 40,

}

resp = requests.post(f"{TMPRO_URL}/v1/orders", json=order_payload, headers=HEADERS).json()

print("Order Outcome:", resp)
```

***

## Part 5: How the Human-in-the-Loop Approval Bar Works[​](#part-5-how-the-human-in-the-loop-approval-bar-works "Direct link to Part 5: How the Human-in-the-Loop Approval Bar Works")

Whenever an AI harness (Claude, Cursor, or Python) submits a trade using a token that has **`Ask me before trading`** enabled:

1. The AI call receives `{"status": "pending_approval", "approvalId": "..."}`.

2. An amber **Agent approval needed** banner immediately appears at the very top of your TM Pro desktop window showing:

   

   * Which agent requested the trade (e.g., `Claude Code`),
   * A plain-English summary (e.g., `BUY 0.21 EURUSD (market)`), and
   * The calculated dollar risk (e.g., `$42.50 risk`).

3. Click **Approve** to dispatch the trade immediately to MetaTrader, or **Reject** to cancel it. If you are away from your desk, the request **automatically expires after 5 minutes** so stale orders never fire late.

![TM Pro Activity audit log showing every order command, broker fill ticket, and status](/img/tm-pro/live-5-activity-audit.png)

Every trade—whether clicked by you, allocated by the Fund Manager, or submitted by an AI harness—is recorded in the Activity tab with its exact broker ticket and fill price.
