mcp-server-feraterra 1.0.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fera Terra (https://feraterra.app)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-server-feraterra
3
+ Version: 1.0.2
4
+ Summary: Model Context Protocol (MCP) stdio server for Fera Terra C++23 L3 FIFO Polymarket & Hyperliquid order-book backtesting
5
+ Author-email: Fera Terra <engineering@feraterra.app>
6
+ License: MIT
7
+ Project-URL: Homepage, https://feraterra.app
8
+ Project-URL: Repository, https://github.com/FeraTerra/mcp-server-feraterra
9
+ Project-URL: Documentation, https://feraterra.app/guides
10
+ Keywords: mcp,model-context-protocol,polymarket,hyperliquid,backtesting,orderbook,trading-bot,quant,cursor,claude-code
11
+ Requires-Python: >=3.11
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: feraterra>=1.0.2
15
+ Dynamic: license-file
16
+
17
+ <!-- mcp-name: io.github.FeraTerra/mcp-server-feraterra -->
18
+
19
+ # `mcp-server-feraterra` — Polymarket & Hyperliquid Backtesting MCP Server
20
+
21
+ [![MCP Server Stdio & C++23 Engine CI](https://github.com/FeraTerra/mcp-server-feraterra/actions/workflows/ci.yml/badge.svg)](https://github.com/FeraTerra/mcp-server-feraterra/actions/workflows/ci.yml)
22
+ [![PyPI - feraterra](https://img.shields.io/pypi/v/feraterra.svg)](https://pypi.org/project/feraterra/)
23
+ [![License: MIT](https://img.shields.io/badge/License-MIT-emerald.svg)](LICENSE)
24
+
25
+ <a href="https://glama.ai/mcp/servers/FeraTerra/mcp-server-feraterra">
26
+ <img width="380" height="200" src="https://glama.ai/mcp/servers/FeraTerra/mcp-server-feraterra/badges/score.svg" alt="FeraTerra/mcp-server-feraterra MCP server" />
27
+ </a>
28
+
29
+ Model Context Protocol (`stdio` JSON-RPC 2.0) server giving **Claude Code**, **Cursor**, **Claude Desktop**, and **Windsurf** direct access to [**Fera Terra**](https://feraterra.app)'s local C++23 L3 FIFO order-book matching engine (`pip install feraterra`).
30
+
31
+ Instead of letting coding agents validate trading bots with naive mid-price fill assumptions, `mcp-server-feraterra` lets your AI coding agent test Polymarket (`$0.001` binary claim books) and Hyperliquid (`BTC-PERP`, `ETH-PERP`, `SOL-PERP` ALO perps) strategies against real resting queue priority, taker sweeps, and cancel-window latency — **100% locally on your machine with zero API keys**.
32
+
33
+ ---
34
+
35
+ ## Exposed MCP Tools
36
+
37
+ | Tool Name | Description |
38
+ | :--- | :--- |
39
+ | `feraterra_doctor` | Run `<1s` preflight diagnostics on the local C++23 Shadow-CLOB engine, Python environment, license tier, and localhost ports. |
40
+ | `feraterra_list_crash_packs` | List deterministic 5-sigma microstructure stress scenarios (`polymarket_news_shock`, `whipsaw_funding_squeeze`, `flash_crash_5sigma`, `liquidity_vacuum_cascade`). |
41
+ | `feraterra_simulate_strategy` | Run a deterministic C++23 L3 FIFO vs. Naive Paper simulation with configurable `scenario`, `steps`, `order_latency_ms`, `cancel_latency_ms`, `half_spread_ticks`, and `quote_size_lots`. Works free on the `$0` Hobby tier. |
42
+ | `feraterra_replay_trace` | Replay any local `.trace.jsonl` order-book & trade-sweep tape against a custom Python `ArenaTwinBot` file (`bot_path`). |
43
+ | `feraterra_import_trace` | Convert historical Tardis.dev `book_snapshot_25`/`trades` CSVs (`.csv.gz`) or Hyperliquid S3 `l2Book` JSONL archives into `.trace.jsonl`. |
44
+
45
+ ---
46
+
47
+ ## Quick Setup (1-Click Remote HTTP or Local `uvx`)
48
+
49
+ ### Option A: Zero-Install Remote Streamable HTTP (`https://mcp.feraterra.app/mcp`)
50
+
51
+ Connect **Claude Code** or **Cursor** immediately with zero local install:
52
+
53
+ ```bash
54
+ claude mcp add --transport http feraterra https://mcp.feraterra.app/mcp
55
+ ```
56
+
57
+ Or in `.cursor/mcp.json`:
58
+
59
+ ```json
60
+ {
61
+ "mcpServers": {
62
+ "feraterra": {
63
+ "url": "https://mcp.feraterra.app/mcp"
64
+ }
65
+ }
66
+ }
67
+ ```
68
+
69
+ ### Option B: Local `stdio` via `uvx` (Test Your Own Local Python / Rust / Go Bots)
70
+
71
+ Add to `.cursor/mcp.json` or `claude_desktop_config.json`:
72
+
73
+ ```json
74
+ {
75
+ "mcpServers": {
76
+ "feraterra": {
77
+ "command": "uvx",
78
+ "args": [
79
+ "--from",
80
+ "git+https://github.com/FeraTerra/mcp-server-feraterra.git",
81
+ "mcp-server-feraterra"
82
+ ]
83
+ }
84
+ }
85
+ }
86
+ ```
87
+
88
+ ### Option C: Claude Code Local `stdio` CLI
89
+
90
+ ```bash
91
+ claude mcp add feraterra -- uvx --from git+https://github.com/FeraTerra/mcp-server-feraterra.git mcp-server-feraterra
92
+ ```
93
+
94
+ ### Option D: Local `pip` Install
95
+
96
+ ```bash
97
+ pip install "git+https://github.com/FeraTerra/mcp-server-feraterra.git"
98
+ mcp-server-feraterra
99
+ ```
100
+
101
+ ---
102
+
103
+ ## Glama MCP Server Listing & Online Inspector
104
+
105
+ View [`FeraTerra/mcp-server-feraterra` on Glama](https://glama.ai/mcp/servers/FeraTerra/mcp-server-feraterra) to:
106
+ - Browse the server's exposed tools, schemas, and quality score.
107
+ - Test the server online using the [MCP Inspector](https://glama.ai/mcp/inspector).
108
+
109
+ ## Links
110
+
111
+ - **Website & Interactive Sandbox:** [https://feraterra.app](https://feraterra.app)
112
+ - **Free Execution Fee & Slippage Calculators:** [https://feraterra.app/tools](https://feraterra.app/tools)
113
+ - **Polymarket Starter Repo:** [https://github.com/FeraTerra/polymarket-paper-trading](https://github.com/FeraTerra/polymarket-paper-trading)
114
+ - **Hyperliquid Starter Repo:** [https://github.com/FeraTerra/hyperliquid-backtest-sim](https://github.com/FeraTerra/hyperliquid-backtest-sim)
115
+
116
+ <!-- mcp-name: io.github.FeraTerra/mcp-server-feraterra -->
@@ -0,0 +1,100 @@
1
+ <!-- mcp-name: io.github.FeraTerra/mcp-server-feraterra -->
2
+
3
+ # `mcp-server-feraterra` — Polymarket & Hyperliquid Backtesting MCP Server
4
+
5
+ [![MCP Server Stdio & C++23 Engine CI](https://github.com/FeraTerra/mcp-server-feraterra/actions/workflows/ci.yml/badge.svg)](https://github.com/FeraTerra/mcp-server-feraterra/actions/workflows/ci.yml)
6
+ [![PyPI - feraterra](https://img.shields.io/pypi/v/feraterra.svg)](https://pypi.org/project/feraterra/)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-emerald.svg)](LICENSE)
8
+
9
+ <a href="https://glama.ai/mcp/servers/FeraTerra/mcp-server-feraterra">
10
+ <img width="380" height="200" src="https://glama.ai/mcp/servers/FeraTerra/mcp-server-feraterra/badges/score.svg" alt="FeraTerra/mcp-server-feraterra MCP server" />
11
+ </a>
12
+
13
+ Model Context Protocol (`stdio` JSON-RPC 2.0) server giving **Claude Code**, **Cursor**, **Claude Desktop**, and **Windsurf** direct access to [**Fera Terra**](https://feraterra.app)'s local C++23 L3 FIFO order-book matching engine (`pip install feraterra`).
14
+
15
+ Instead of letting coding agents validate trading bots with naive mid-price fill assumptions, `mcp-server-feraterra` lets your AI coding agent test Polymarket (`$0.001` binary claim books) and Hyperliquid (`BTC-PERP`, `ETH-PERP`, `SOL-PERP` ALO perps) strategies against real resting queue priority, taker sweeps, and cancel-window latency — **100% locally on your machine with zero API keys**.
16
+
17
+ ---
18
+
19
+ ## Exposed MCP Tools
20
+
21
+ | Tool Name | Description |
22
+ | :--- | :--- |
23
+ | `feraterra_doctor` | Run `<1s` preflight diagnostics on the local C++23 Shadow-CLOB engine, Python environment, license tier, and localhost ports. |
24
+ | `feraterra_list_crash_packs` | List deterministic 5-sigma microstructure stress scenarios (`polymarket_news_shock`, `whipsaw_funding_squeeze`, `flash_crash_5sigma`, `liquidity_vacuum_cascade`). |
25
+ | `feraterra_simulate_strategy` | Run a deterministic C++23 L3 FIFO vs. Naive Paper simulation with configurable `scenario`, `steps`, `order_latency_ms`, `cancel_latency_ms`, `half_spread_ticks`, and `quote_size_lots`. Works free on the `$0` Hobby tier. |
26
+ | `feraterra_replay_trace` | Replay any local `.trace.jsonl` order-book & trade-sweep tape against a custom Python `ArenaTwinBot` file (`bot_path`). |
27
+ | `feraterra_import_trace` | Convert historical Tardis.dev `book_snapshot_25`/`trades` CSVs (`.csv.gz`) or Hyperliquid S3 `l2Book` JSONL archives into `.trace.jsonl`. |
28
+
29
+ ---
30
+
31
+ ## Quick Setup (1-Click Remote HTTP or Local `uvx`)
32
+
33
+ ### Option A: Zero-Install Remote Streamable HTTP (`https://mcp.feraterra.app/mcp`)
34
+
35
+ Connect **Claude Code** or **Cursor** immediately with zero local install:
36
+
37
+ ```bash
38
+ claude mcp add --transport http feraterra https://mcp.feraterra.app/mcp
39
+ ```
40
+
41
+ Or in `.cursor/mcp.json`:
42
+
43
+ ```json
44
+ {
45
+ "mcpServers": {
46
+ "feraterra": {
47
+ "url": "https://mcp.feraterra.app/mcp"
48
+ }
49
+ }
50
+ }
51
+ ```
52
+
53
+ ### Option B: Local `stdio` via `uvx` (Test Your Own Local Python / Rust / Go Bots)
54
+
55
+ Add to `.cursor/mcp.json` or `claude_desktop_config.json`:
56
+
57
+ ```json
58
+ {
59
+ "mcpServers": {
60
+ "feraterra": {
61
+ "command": "uvx",
62
+ "args": [
63
+ "--from",
64
+ "git+https://github.com/FeraTerra/mcp-server-feraterra.git",
65
+ "mcp-server-feraterra"
66
+ ]
67
+ }
68
+ }
69
+ }
70
+ ```
71
+
72
+ ### Option C: Claude Code Local `stdio` CLI
73
+
74
+ ```bash
75
+ claude mcp add feraterra -- uvx --from git+https://github.com/FeraTerra/mcp-server-feraterra.git mcp-server-feraterra
76
+ ```
77
+
78
+ ### Option D: Local `pip` Install
79
+
80
+ ```bash
81
+ pip install "git+https://github.com/FeraTerra/mcp-server-feraterra.git"
82
+ mcp-server-feraterra
83
+ ```
84
+
85
+ ---
86
+
87
+ ## Glama MCP Server Listing & Online Inspector
88
+
89
+ View [`FeraTerra/mcp-server-feraterra` on Glama](https://glama.ai/mcp/servers/FeraTerra/mcp-server-feraterra) to:
90
+ - Browse the server's exposed tools, schemas, and quality score.
91
+ - Test the server online using the [MCP Inspector](https://glama.ai/mcp/inspector).
92
+
93
+ ## Links
94
+
95
+ - **Website & Interactive Sandbox:** [https://feraterra.app](https://feraterra.app)
96
+ - **Free Execution Fee & Slippage Calculators:** [https://feraterra.app/tools](https://feraterra.app/tools)
97
+ - **Polymarket Starter Repo:** [https://github.com/FeraTerra/polymarket-paper-trading](https://github.com/FeraTerra/polymarket-paper-trading)
98
+ - **Hyperliquid Starter Repo:** [https://github.com/FeraTerra/hyperliquid-backtest-sim](https://github.com/FeraTerra/hyperliquid-backtest-sim)
99
+
100
+ <!-- mcp-name: io.github.FeraTerra/mcp-server-feraterra -->
@@ -0,0 +1,3 @@
1
+ """Fera Terra Model Context Protocol (MCP) stdio server."""
2
+
3
+ __version__ = "1.0.2"
@@ -0,0 +1,6 @@
1
+ """Module entrypoint for `python -m feraterra_mcp`."""
2
+
3
+ from feraterra_mcp.server import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,500 @@
1
+ """Stdlib-only JSON-RPC 2.0 MCP stdio server wrapping Fera Terra C++23 Shadow-CLOB."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import io
7
+ import json
8
+ import pathlib
9
+ import subprocess
10
+ import sys
11
+ from typing import Any, Dict, List, Optional
12
+
13
+ from arenatwin.cli import run_step_sequence_simulation
14
+ from arenatwin.crash_packs import CrashPack, list_crash_packs
15
+ from arenatwin.importer import import_historical_trace
16
+ from arenatwin.proxy_gateway import FaultInjectedError, SimulationSession
17
+ from arenatwin.types import MarketSpec
18
+
19
+ SERVER_NAME = "mcp-server-feraterra"
20
+ SERVER_VERSION = "1.0.2"
21
+ SUPPORTED_PROTOCOLS = ("2025-06-18", "2025-03-26", "2024-11-05")
22
+
23
+
24
+ class _ConfigurableMakerBot:
25
+ """Built-in two-sided passive maker bot used by `feraterra_simulate_strategy`."""
26
+
27
+ def __init__(
28
+ self,
29
+ *,
30
+ half_spread_ticks: int = 1,
31
+ quote_size_lots: int = 50,
32
+ requote_threshold_ticks: int = 2,
33
+ max_inventory_lots: int = 400,
34
+ ) -> None:
35
+ self.half_spread_ticks = max(1, int(half_spread_ticks))
36
+ self.quote_size_lots = max(1, int(quote_size_lots))
37
+ self.requote_threshold_ticks = max(1, int(requote_threshold_ticks))
38
+ self.max_inventory_lots = max(1, int(max_inventory_lots))
39
+ self._bid_coid: Optional[str] = None
40
+ self._ask_coid: Optional[str] = None
41
+ self._quoted_mid_t: Optional[int] = None
42
+ self._seeded: set[int] = set()
43
+
44
+ def _inv_lots(self, session: SimulationSession, market_id: int) -> int:
45
+ total = 0
46
+ for fill in session.real_fills:
47
+ if fill.market_id == market_id:
48
+ total += fill.qty_lots if fill.side == "bid" else -fill.qty_lots
49
+ return total
50
+
51
+ def on_tick(
52
+ self,
53
+ session: SimulationSession,
54
+ spec: MarketSpec,
55
+ best_bid_usd: float,
56
+ best_ask_usd: float,
57
+ mid_usd: float,
58
+ step_idx: int,
59
+ ) -> None:
60
+ if spec.kind == "claim" and spec.venue == "polymarket" and spec.market_id not in self._seeded:
61
+ with contextlib.suppress(Exception):
62
+ session.split_claim_position(spec.symbol, spec.lots_to_size(max(self.max_inventory_lots, self.quote_size_lots * 4)))
63
+ self._seeded.add(spec.market_id)
64
+
65
+ for attr in ("_bid_coid", "_ask_coid"):
66
+ coid = getattr(self, attr)
67
+ if coid:
68
+ tr = session.orders_by_client_id.get(coid)
69
+ if tr is None or tr.status != "open":
70
+ setattr(self, attr, None)
71
+
72
+ mid_t = spec.price_to_ticks(mid_usd)
73
+ if (
74
+ self._quoted_mid_t is not None
75
+ and abs(mid_t - self._quoted_mid_t) < self.requote_threshold_ticks
76
+ and (self._bid_coid is not None or self._ask_coid is not None)
77
+ ):
78
+ return
79
+
80
+ for coid in (self._bid_coid, self._ask_coid):
81
+ if coid is not None:
82
+ with contextlib.suppress(FaultInjectedError):
83
+ session.cancel_order(client_order_id=coid)
84
+ self._bid_coid = None
85
+ self._ask_coid = None
86
+
87
+ inv = self._inv_lots(session, spec.market_id)
88
+ skew = int(round(-2.0 * (inv / max(1, self.max_inventory_lots))))
89
+ res_t = mid_t + skew
90
+ bid_t = max(1, res_t - self.half_spread_ticks)
91
+ ask_t = res_t + self.half_spread_ticks
92
+ if spec.kind == "claim":
93
+ ask_t = min(spec.claim_cap_ticks - 1, ask_t)
94
+ if ask_t <= bid_t:
95
+ ask_t = bid_t + 1
96
+
97
+ sz = spec.lots_to_size(self.quote_size_lots)
98
+ if inv < self.max_inventory_lots:
99
+ with contextlib.suppress(FaultInjectedError):
100
+ rb = session.submit_order(symbol=spec.symbol, side="bid", price_usd=spec.ticks_to_price(bid_t), size=sz, post_only=True)
101
+ if rb.get("ok"):
102
+ self._bid_coid = str(rb["client_order_id"])
103
+ if inv > -self.max_inventory_lots:
104
+ with contextlib.suppress(FaultInjectedError):
105
+ ra = session.submit_order(symbol=spec.symbol, side="ask", price_usd=spec.ticks_to_price(ask_t), size=sz, post_only=True)
106
+ if ra.get("ok"):
107
+ self._ask_coid = str(ra["client_order_id"])
108
+ self._quoted_mid_t = mid_t
109
+
110
+
111
+ TOOLS: List[Dict[str, Any]] = [
112
+ {
113
+ "name": "feraterra_doctor",
114
+ "description": (
115
+ "Run <1s preflight diagnostics on the local Fera Terra C++23 Shadow-CLOB engine, "
116
+ "Python environment, license tier, and localhost proxy ports."
117
+ ),
118
+ "inputSchema": {
119
+ "type": "object",
120
+ "properties": {},
121
+ "additionalProperties": False,
122
+ },
123
+ },
124
+ {
125
+ "name": "feraterra_list_crash_packs",
126
+ "description": (
127
+ "List built-in deterministic microstructure stress scenarios for Polymarket and Hyperliquid "
128
+ "(flash crashes, macro news shocks, funding whipsaws, and liquidity vacuums)."
129
+ ),
130
+ "inputSchema": {
131
+ "type": "object",
132
+ "properties": {},
133
+ "additionalProperties": False,
134
+ },
135
+ },
136
+ {
137
+ "name": "feraterra_simulate_strategy",
138
+ "description": (
139
+ "Execute a deterministic C++23 L3 FIFO vs. Naive Paper order-book simulation on Polymarket "
140
+ "or Hyperliquid and return PnL illusion gap, queue-blocked non-fills, cancel-lag snipes, and markouts."
141
+ ),
142
+ "inputSchema": {
143
+ "type": "object",
144
+ "properties": {
145
+ "scenario": {
146
+ "type": "string",
147
+ "enum": [
148
+ "polymarket_news_shock",
149
+ "whipsaw_funding_squeeze",
150
+ "flash_crash_5sigma",
151
+ "liquidity_vacuum_cascade",
152
+ ],
153
+ "default": "polymarket_news_shock",
154
+ "description": "Microstructure scenario to simulate.",
155
+ },
156
+ "steps": {
157
+ "type": "integer",
158
+ "minimum": 15,
159
+ "maximum": 120,
160
+ "default": 60,
161
+ "description": "Number of 100ms order-book steps (15..120).",
162
+ },
163
+ "order_latency_ms": {
164
+ "type": "number",
165
+ "minimum": 0.0,
166
+ "maximum": 2000.0,
167
+ "default": 25.0,
168
+ "description": "Simulated one-way order placement latency in milliseconds.",
169
+ },
170
+ "cancel_latency_ms": {
171
+ "type": "number",
172
+ "minimum": 0.0,
173
+ "maximum": 5000.0,
174
+ "default": 120.0,
175
+ "description": "Simulated cancel round-trip latency in milliseconds.",
176
+ },
177
+ "half_spread_ticks": {
178
+ "type": "integer",
179
+ "minimum": 1,
180
+ "maximum": 50,
181
+ "default": 1,
182
+ "description": "Maker quote half-spread in ticks from reservation price.",
183
+ },
184
+ "quote_size_lots": {
185
+ "type": "integer",
186
+ "minimum": 1,
187
+ "maximum": 5000,
188
+ "default": 50,
189
+ "description": "Order size per quote side in integer lots.",
190
+ },
191
+ "seed": {
192
+ "type": "integer",
193
+ "default": 42,
194
+ "description": "Deterministic PRNG seed.",
195
+ },
196
+ },
197
+ "additionalProperties": False,
198
+ },
199
+ },
200
+ {
201
+ "name": "feraterra_replay_trace",
202
+ "description": (
203
+ "Deterministically replay a recorded `.trace.jsonl` L2 + trade-sweep session against a custom "
204
+ "Python `--bot` file inside the C++23 L3 FIFO matching engine."
205
+ ),
206
+ "inputSchema": {
207
+ "type": "object",
208
+ "properties": {
209
+ "trace_path": {
210
+ "type": "string",
211
+ "description": "Path to a `feraterra_l2_trace_v1` `.trace.jsonl` file.",
212
+ },
213
+ "bot_path": {
214
+ "type": "string",
215
+ "description": "Optional path to a Python module defining `ArenaTwinBot`.",
216
+ },
217
+ "order_latency_ms": {
218
+ "type": "number",
219
+ "minimum": 0.0,
220
+ "default": 25.0,
221
+ },
222
+ "cancel_latency_ms": {
223
+ "type": "number",
224
+ "minimum": 0.0,
225
+ "default": 120.0,
226
+ },
227
+ },
228
+ "required": ["trace_path"],
229
+ "additionalProperties": False,
230
+ },
231
+ },
232
+ {
233
+ "name": "feraterra_import_trace",
234
+ "description": (
235
+ "Import historical Tardis.dev book_snapshot_25/trades CSVs (.csv/.csv.gz), Hyperliquid S3 l2Book "
236
+ "JSON/JSONL archives, or Polymarket CLOB snapshots into a deterministic `.trace.jsonl` file."
237
+ ),
238
+ "inputSchema": {
239
+ "type": "object",
240
+ "properties": {
241
+ "input_path": {
242
+ "type": "string",
243
+ "description": "Path to historical L2 snapshot file (.csv, .csv.gz, .jsonl, .json).",
244
+ },
245
+ "out_path": {
246
+ "type": "string",
247
+ "description": "Output `.trace.jsonl` path.",
248
+ },
249
+ "trades_path": {
250
+ "type": "string",
251
+ "description": "Optional separate trade tape path (e.g., Tardis trades.csv.gz).",
252
+ },
253
+ "venue": {
254
+ "type": "string",
255
+ "enum": ["auto", "hyperliquid", "polymarket"],
256
+ "default": "auto",
257
+ },
258
+ "symbol": {
259
+ "type": "string",
260
+ "description": "Optional symbol override (e.g., BTC, SOL, FED-CUT-YES).",
261
+ },
262
+ },
263
+ "required": ["input_path", "out_path"],
264
+ "additionalProperties": False,
265
+ },
266
+ },
267
+ ]
268
+
269
+
270
+ def _call_tool(name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
271
+ if name == "feraterra_doctor":
272
+ proc = subprocess.run(
273
+ [sys.executable, "-m", "feraterra", "doctor", "--json"],
274
+ capture_output=True,
275
+ text=True,
276
+ timeout=20,
277
+ )
278
+ out = proc.stdout.strip() or proc.stderr.strip()
279
+ try:
280
+ payload = json.loads(out)
281
+ except Exception:
282
+ payload = {"exit_code": proc.returncode, "output": out}
283
+ return {"content": [{"type": "text", "text": json.dumps(payload, indent=2)}], "isError": proc.returncode != 0}
284
+
285
+ if name == "feraterra_list_crash_packs":
286
+ packs = list_crash_packs()
287
+ return {"content": [{"type": "text", "text": json.dumps({"crash_packs": packs}, indent=2)}], "isError": False}
288
+
289
+ if name == "feraterra_simulate_strategy":
290
+ scenario = str(arguments.get("scenario", "polymarket_news_shock"))
291
+ steps = max(15, min(120, int(arguments.get("steps", 60))))
292
+ order_ms = float(arguments.get("order_latency_ms", 25.0))
293
+ cancel_ms = float(arguments.get("cancel_latency_ms", 120.0))
294
+ half_spread = max(1, int(arguments.get("half_spread_ticks", 1)))
295
+ quote_lots = max(1, int(arguments.get("quote_size_lots", 50)))
296
+ seed = int(arguments.get("seed", 42))
297
+
298
+ pack = CrashPack.from_name(scenario, seed=seed, steps=steps)
299
+ bot = _ConfigurableMakerBot(
300
+ half_spread_ticks=half_spread,
301
+ quote_size_lots=quote_lots,
302
+ max_inventory_lots=max(200, quote_lots * 8),
303
+ )
304
+ with contextlib.redirect_stdout(io.StringIO()):
305
+ report = run_step_sequence_simulation(
306
+ scenario_name=scenario,
307
+ pack_spec=pack.spec,
308
+ crash_steps=pack.steps,
309
+ bot_instance=bot,
310
+ seed=seed,
311
+ order_latency_ms=order_ms,
312
+ cancel_latency_ms=cancel_ms,
313
+ require_ci=False,
314
+ use_crash_pack_gate=False,
315
+ )
316
+ summary = {
317
+ "scenario": report.scenario_name,
318
+ "venue": report.venue,
319
+ "symbols": report.symbols,
320
+ "steps": steps,
321
+ "order_latency_ms": report.order_latency_ms,
322
+ "cancel_latency_ms": report.cancel_latency_ms,
323
+ "total_orders_submitted": report.total_orders_submitted,
324
+ "naive_paper_fills": report.naive_paper_fills,
325
+ "real_fifo_fills": report.real_fifo_fills,
326
+ "queue_blocked_non_fills": report.queue_blocked_non_fills,
327
+ "cancel_lag_snipes": report.cancel_lag_snipes,
328
+ "naive_paper_net_pnl_usd": round(report.naive_paper_net_pnl_usd, 4),
329
+ "real_fifo_net_pnl_usd": round(report.real_fifo_net_pnl_usd, 4),
330
+ "backtest_illusion_gap_usd": round(report.backtest_illusion_gap_usd, 4),
331
+ "spread_capture_usd": round(report.spread_capture_usd, 4),
332
+ "adverse_selection_loss_usd": round(report.adverse_selection_loss_usd, 4),
333
+ "fees_paid_usd": round(report.fees_paid_usd, 4),
334
+ "top_blunders": [
335
+ {"category": b.category, "loss_usd": round(b.loss_usd, 4), "summary": b.summary}
336
+ for b in report.blunders[:5]
337
+ ],
338
+ }
339
+ return {"content": [{"type": "text", "text": json.dumps(summary, indent=2)}], "isError": False}
340
+
341
+ if name == "feraterra_replay_trace":
342
+ trace_path = pathlib.Path(str(arguments["trace_path"])).expanduser().resolve()
343
+ if not trace_path.is_file():
344
+ return {
345
+ "content": [{"type": "text", "text": f"Trace file not found: {trace_path}"}],
346
+ "isError": True,
347
+ }
348
+ order_ms = float(arguments.get("order_latency_ms", 25.0))
349
+ cancel_ms = float(arguments.get("cancel_latency_ms", 120.0))
350
+ cmd = [
351
+ sys.executable,
352
+ "-m",
353
+ "feraterra",
354
+ "replay",
355
+ "--trace",
356
+ str(trace_path),
357
+ "--order-latency-ms",
358
+ str(order_ms),
359
+ "--cancel-latency-ms",
360
+ str(cancel_ms),
361
+ ]
362
+ bot_path = arguments.get("bot_path")
363
+ if bot_path:
364
+ cmd.extend(["--bot", str(pathlib.Path(str(bot_path)).expanduser().resolve())])
365
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
366
+ text_out = (proc.stdout + "\n" + proc.stderr).strip()
367
+ return {"content": [{"type": "text", "text": text_out}], "isError": proc.returncode != 0}
368
+
369
+ if name == "feraterra_import_trace":
370
+ in_p = pathlib.Path(str(arguments["input_path"])).expanduser().resolve()
371
+ out_p = pathlib.Path(str(arguments["out_path"])).expanduser().resolve()
372
+ tr_raw = str(arguments.get("trades_path") or "").strip()
373
+ tr_p = str(pathlib.Path(tr_raw).expanduser().resolve()) if tr_raw else ""
374
+ res = import_historical_trace(
375
+ input_path=in_p,
376
+ out_path=out_p,
377
+ trades_path=tr_p,
378
+ venue=str(arguments.get("venue") or "auto"),
379
+ symbol=str(arguments.get("symbol") or ""),
380
+ )
381
+ return {"content": [{"type": "text", "text": json.dumps(res, indent=2)}], "isError": False}
382
+
383
+ raise KeyError(f"Unknown tool: {name}")
384
+
385
+
386
+ def handle_rpc_request(msg: Dict[str, Any]) -> Optional[Dict[str, Any]]:
387
+ method = msg.get("method")
388
+ req_id = msg.get("id")
389
+ params = msg.get("params") or {}
390
+
391
+ # JSON-RPC notifications have no "id" and must not emit a response
392
+ if "id" not in msg:
393
+ return None
394
+
395
+ if method == "initialize":
396
+ requested_proto = str(params.get("protocolVersion") or "2024-11-05")
397
+ proto = requested_proto if requested_proto in SUPPORTED_PROTOCOLS else "2024-11-05"
398
+ return {
399
+ "jsonrpc": "2.0",
400
+ "id": req_id,
401
+ "result": {
402
+ "protocolVersion": proto,
403
+ "capabilities": {"tools": {"listChanged": False}},
404
+ "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
405
+ },
406
+ }
407
+
408
+ if method == "ping":
409
+ return {"jsonrpc": "2.0", "id": req_id, "result": {}}
410
+
411
+ if method == "tools/list":
412
+ return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}}
413
+
414
+ if method == "resources/list":
415
+ return {"jsonrpc": "2.0", "id": req_id, "result": {"resources": []}}
416
+
417
+ if method == "prompts/list":
418
+ return {"jsonrpc": "2.0", "id": req_id, "result": {"prompts": []}}
419
+
420
+ if method == "tools/call":
421
+ tool_name = str(params.get("name") or "")
422
+ tool_args = params.get("arguments") or {}
423
+ if not isinstance(tool_args, dict):
424
+ return {
425
+ "jsonrpc": "2.0",
426
+ "id": req_id,
427
+ "error": {"code": -32602, "message": "Invalid arguments object"},
428
+ }
429
+ try:
430
+ result = _call_tool(tool_name, tool_args)
431
+ return {"jsonrpc": "2.0", "id": req_id, "result": result}
432
+ except KeyError as exc:
433
+ return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": str(exc)}}
434
+ except Exception as exc:
435
+ return {
436
+ "jsonrpc": "2.0",
437
+ "id": req_id,
438
+ "result": {
439
+ "content": [{"type": "text", "text": f"Tool execution error: {exc}"}],
440
+ "isError": True,
441
+ },
442
+ }
443
+
444
+ return {
445
+ "jsonrpc": "2.0",
446
+ "id": req_id,
447
+ "error": {"code": -32601, "message": f"Method not found: {method}"},
448
+ }
449
+
450
+
451
+ def main() -> None:
452
+ stdin_buf = sys.stdin.buffer
453
+ stdout_buf = sys.stdout.buffer
454
+
455
+ while True:
456
+ raw_line = stdin_buf.readline()
457
+ if not raw_line:
458
+ break
459
+ stripped = raw_line.strip()
460
+ if not stripped:
461
+ continue
462
+
463
+ use_content_length = False
464
+ if stripped.lower().startswith(b"content-length:"):
465
+ use_content_length = True
466
+ length = int(stripped.split(b":", 1)[1].strip())
467
+ while True:
468
+ hdr = stdin_buf.readline()
469
+ if not hdr or hdr in (b"\r\n", b"\n"):
470
+ break
471
+ body = stdin_buf.read(length)
472
+ else:
473
+ body = stripped
474
+
475
+ try:
476
+ msg = json.loads(body.decode("utf-8"))
477
+ except Exception as exc:
478
+ err = {
479
+ "jsonrpc": "2.0",
480
+ "id": None,
481
+ "error": {"code": -32700, "message": f"Parse error: {exc}"},
482
+ }
483
+ out_bytes = json.dumps(err, separators=(",", ":")).encode("utf-8")
484
+ stdout_buf.write(out_bytes + b"\n")
485
+ stdout_buf.flush()
486
+ continue
487
+
488
+ resp = handle_rpc_request(msg)
489
+ if resp is not None:
490
+ payload = json.dumps(resp, separators=(",", ":")).encode("utf-8")
491
+ if use_content_length:
492
+ header = f"Content-Length: {len(payload)}\r\n\r\n".encode("ascii")
493
+ stdout_buf.write(header + payload)
494
+ else:
495
+ stdout_buf.write(payload + b"\n")
496
+ stdout_buf.flush()
497
+
498
+
499
+ if __name__ == "__main__":
500
+ main()
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-server-feraterra
3
+ Version: 1.0.2
4
+ Summary: Model Context Protocol (MCP) stdio server for Fera Terra C++23 L3 FIFO Polymarket & Hyperliquid order-book backtesting
5
+ Author-email: Fera Terra <engineering@feraterra.app>
6
+ License: MIT
7
+ Project-URL: Homepage, https://feraterra.app
8
+ Project-URL: Repository, https://github.com/FeraTerra/mcp-server-feraterra
9
+ Project-URL: Documentation, https://feraterra.app/guides
10
+ Keywords: mcp,model-context-protocol,polymarket,hyperliquid,backtesting,orderbook,trading-bot,quant,cursor,claude-code
11
+ Requires-Python: >=3.11
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: feraterra>=1.0.2
15
+ Dynamic: license-file
16
+
17
+ <!-- mcp-name: io.github.FeraTerra/mcp-server-feraterra -->
18
+
19
+ # `mcp-server-feraterra` — Polymarket & Hyperliquid Backtesting MCP Server
20
+
21
+ [![MCP Server Stdio & C++23 Engine CI](https://github.com/FeraTerra/mcp-server-feraterra/actions/workflows/ci.yml/badge.svg)](https://github.com/FeraTerra/mcp-server-feraterra/actions/workflows/ci.yml)
22
+ [![PyPI - feraterra](https://img.shields.io/pypi/v/feraterra.svg)](https://pypi.org/project/feraterra/)
23
+ [![License: MIT](https://img.shields.io/badge/License-MIT-emerald.svg)](LICENSE)
24
+
25
+ <a href="https://glama.ai/mcp/servers/FeraTerra/mcp-server-feraterra">
26
+ <img width="380" height="200" src="https://glama.ai/mcp/servers/FeraTerra/mcp-server-feraterra/badges/score.svg" alt="FeraTerra/mcp-server-feraterra MCP server" />
27
+ </a>
28
+
29
+ Model Context Protocol (`stdio` JSON-RPC 2.0) server giving **Claude Code**, **Cursor**, **Claude Desktop**, and **Windsurf** direct access to [**Fera Terra**](https://feraterra.app)'s local C++23 L3 FIFO order-book matching engine (`pip install feraterra`).
30
+
31
+ Instead of letting coding agents validate trading bots with naive mid-price fill assumptions, `mcp-server-feraterra` lets your AI coding agent test Polymarket (`$0.001` binary claim books) and Hyperliquid (`BTC-PERP`, `ETH-PERP`, `SOL-PERP` ALO perps) strategies against real resting queue priority, taker sweeps, and cancel-window latency — **100% locally on your machine with zero API keys**.
32
+
33
+ ---
34
+
35
+ ## Exposed MCP Tools
36
+
37
+ | Tool Name | Description |
38
+ | :--- | :--- |
39
+ | `feraterra_doctor` | Run `<1s` preflight diagnostics on the local C++23 Shadow-CLOB engine, Python environment, license tier, and localhost ports. |
40
+ | `feraterra_list_crash_packs` | List deterministic 5-sigma microstructure stress scenarios (`polymarket_news_shock`, `whipsaw_funding_squeeze`, `flash_crash_5sigma`, `liquidity_vacuum_cascade`). |
41
+ | `feraterra_simulate_strategy` | Run a deterministic C++23 L3 FIFO vs. Naive Paper simulation with configurable `scenario`, `steps`, `order_latency_ms`, `cancel_latency_ms`, `half_spread_ticks`, and `quote_size_lots`. Works free on the `$0` Hobby tier. |
42
+ | `feraterra_replay_trace` | Replay any local `.trace.jsonl` order-book & trade-sweep tape against a custom Python `ArenaTwinBot` file (`bot_path`). |
43
+ | `feraterra_import_trace` | Convert historical Tardis.dev `book_snapshot_25`/`trades` CSVs (`.csv.gz`) or Hyperliquid S3 `l2Book` JSONL archives into `.trace.jsonl`. |
44
+
45
+ ---
46
+
47
+ ## Quick Setup (1-Click Remote HTTP or Local `uvx`)
48
+
49
+ ### Option A: Zero-Install Remote Streamable HTTP (`https://mcp.feraterra.app/mcp`)
50
+
51
+ Connect **Claude Code** or **Cursor** immediately with zero local install:
52
+
53
+ ```bash
54
+ claude mcp add --transport http feraterra https://mcp.feraterra.app/mcp
55
+ ```
56
+
57
+ Or in `.cursor/mcp.json`:
58
+
59
+ ```json
60
+ {
61
+ "mcpServers": {
62
+ "feraterra": {
63
+ "url": "https://mcp.feraterra.app/mcp"
64
+ }
65
+ }
66
+ }
67
+ ```
68
+
69
+ ### Option B: Local `stdio` via `uvx` (Test Your Own Local Python / Rust / Go Bots)
70
+
71
+ Add to `.cursor/mcp.json` or `claude_desktop_config.json`:
72
+
73
+ ```json
74
+ {
75
+ "mcpServers": {
76
+ "feraterra": {
77
+ "command": "uvx",
78
+ "args": [
79
+ "--from",
80
+ "git+https://github.com/FeraTerra/mcp-server-feraterra.git",
81
+ "mcp-server-feraterra"
82
+ ]
83
+ }
84
+ }
85
+ }
86
+ ```
87
+
88
+ ### Option C: Claude Code Local `stdio` CLI
89
+
90
+ ```bash
91
+ claude mcp add feraterra -- uvx --from git+https://github.com/FeraTerra/mcp-server-feraterra.git mcp-server-feraterra
92
+ ```
93
+
94
+ ### Option D: Local `pip` Install
95
+
96
+ ```bash
97
+ pip install "git+https://github.com/FeraTerra/mcp-server-feraterra.git"
98
+ mcp-server-feraterra
99
+ ```
100
+
101
+ ---
102
+
103
+ ## Glama MCP Server Listing & Online Inspector
104
+
105
+ View [`FeraTerra/mcp-server-feraterra` on Glama](https://glama.ai/mcp/servers/FeraTerra/mcp-server-feraterra) to:
106
+ - Browse the server's exposed tools, schemas, and quality score.
107
+ - Test the server online using the [MCP Inspector](https://glama.ai/mcp/inspector).
108
+
109
+ ## Links
110
+
111
+ - **Website & Interactive Sandbox:** [https://feraterra.app](https://feraterra.app)
112
+ - **Free Execution Fee & Slippage Calculators:** [https://feraterra.app/tools](https://feraterra.app/tools)
113
+ - **Polymarket Starter Repo:** [https://github.com/FeraTerra/polymarket-paper-trading](https://github.com/FeraTerra/polymarket-paper-trading)
114
+ - **Hyperliquid Starter Repo:** [https://github.com/FeraTerra/hyperliquid-backtest-sim](https://github.com/FeraTerra/hyperliquid-backtest-sim)
115
+
116
+ <!-- mcp-name: io.github.FeraTerra/mcp-server-feraterra -->
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ feraterra_mcp/__init__.py
5
+ feraterra_mcp/__main__.py
6
+ feraterra_mcp/server.py
7
+ mcp_server_feraterra.egg-info/PKG-INFO
8
+ mcp_server_feraterra.egg-info/SOURCES.txt
9
+ mcp_server_feraterra.egg-info/dependency_links.txt
10
+ mcp_server_feraterra.egg-info/entry_points.txt
11
+ mcp_server_feraterra.egg-info/requires.txt
12
+ mcp_server_feraterra.egg-info/top_level.txt
13
+ tests/test_mcp_stdio.py
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ feraterra-mcp = feraterra_mcp.server:main
3
+ mcp-server-feraterra = feraterra_mcp.server:main
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mcp-server-feraterra"
7
+ version = "1.0.2"
8
+ description = "Model Context Protocol (MCP) stdio server for Fera Terra C++23 L3 FIFO Polymarket & Hyperliquid order-book backtesting"
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.11"
12
+ authors = [
13
+ {name = "Fera Terra", email = "engineering@feraterra.app"},
14
+ ]
15
+ keywords = [
16
+ "mcp",
17
+ "model-context-protocol",
18
+ "polymarket",
19
+ "hyperliquid",
20
+ "backtesting",
21
+ "orderbook",
22
+ "trading-bot",
23
+ "quant",
24
+ "cursor",
25
+ "claude-code",
26
+ ]
27
+ dependencies = [
28
+ "feraterra>=1.0.2",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://feraterra.app"
33
+ Repository = "https://github.com/FeraTerra/mcp-server-feraterra"
34
+ Documentation = "https://feraterra.app/guides"
35
+
36
+ [project.scripts]
37
+ mcp-server-feraterra = "feraterra_mcp.server:main"
38
+ feraterra-mcp = "feraterra_mcp.server:main"
39
+
40
+ [tool.setuptools.packages.find]
41
+ where = ["."]
42
+ include = ["feraterra_mcp*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,136 @@
1
+ """End-to-end stdio JSON-RPC 2.0 tests for mcp-server-feraterra."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import pathlib
8
+ import subprocess
9
+ import sys
10
+ import unittest
11
+
12
+ REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
13
+
14
+
15
+ class TestFeraTerraMcpStdio(unittest.TestCase):
16
+ def test_stdio_lifecycle_and_cpp23_simulation(self) -> None:
17
+ env = dict(os.environ)
18
+ existing_pp = env.get("PYTHONPATH", "")
19
+ env["PYTHONPATH"] = f"{REPO_ROOT}{os.pathsep}{existing_pp}" if existing_pp else str(REPO_ROOT)
20
+
21
+ proc = subprocess.Popen(
22
+ [sys.executable, "-m", "feraterra_mcp"],
23
+ stdin=subprocess.PIPE,
24
+ stdout=subprocess.PIPE,
25
+ stderr=subprocess.PIPE,
26
+ text=True,
27
+ encoding="utf-8",
28
+ env=env,
29
+ )
30
+ assert proc.stdin is not None and proc.stdout is not None
31
+
32
+ def rpc(msg: dict) -> dict:
33
+ proc.stdin.write(json.dumps(msg) + "\n")
34
+ proc.stdin.flush()
35
+ line = proc.stdout.readline()
36
+ self.assertTrue(line, "Expected JSON-RPC response line on stdout")
37
+ return json.loads(line)
38
+
39
+ try:
40
+ init_resp = rpc(
41
+ {
42
+ "jsonrpc": "2.0",
43
+ "id": 1,
44
+ "method": "initialize",
45
+ "params": {
46
+ "protocolVersion": "2024-11-05",
47
+ "capabilities": {},
48
+ "clientInfo": {"name": "test-suite", "version": "1.0.0"},
49
+ },
50
+ }
51
+ )
52
+ self.assertEqual(init_resp["result"]["serverInfo"]["name"], "mcp-server-feraterra")
53
+
54
+ # Notification must not emit a response
55
+ proc.stdin.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}) + "\n")
56
+ proc.stdin.flush()
57
+
58
+ ping_resp = rpc({"jsonrpc": "2.0", "id": 2, "method": "ping"})
59
+ self.assertEqual(ping_resp["result"], {})
60
+
61
+ tools_resp = rpc({"jsonrpc": "2.0", "id": 3, "method": "tools/list"})
62
+ tool_names = [t["name"] for t in tools_resp["result"]["tools"]]
63
+ self.assertEqual(
64
+ tool_names,
65
+ [
66
+ "feraterra_doctor",
67
+ "feraterra_list_crash_packs",
68
+ "feraterra_simulate_strategy",
69
+ "feraterra_replay_trace",
70
+ "feraterra_import_trace",
71
+ ],
72
+ )
73
+
74
+ packs_resp = rpc(
75
+ {
76
+ "jsonrpc": "2.0",
77
+ "id": 4,
78
+ "method": "tools/call",
79
+ "params": {"name": "feraterra_list_crash_packs", "arguments": {}},
80
+ }
81
+ )
82
+ self.assertFalse(packs_resp["result"]["isError"])
83
+ packs_data = json.loads(packs_resp["result"]["content"][0]["text"])
84
+ self.assertGreaterEqual(len(packs_data["crash_packs"]), 4)
85
+
86
+ sim_pm = rpc(
87
+ {
88
+ "jsonrpc": "2.0",
89
+ "id": 5,
90
+ "method": "tools/call",
91
+ "params": {
92
+ "name": "feraterra_simulate_strategy",
93
+ "arguments": {
94
+ "scenario": "polymarket_news_shock",
95
+ "steps": 45,
96
+ "cancel_latency_ms": 140.0,
97
+ "half_spread_ticks": 1,
98
+ },
99
+ },
100
+ }
101
+ )
102
+ self.assertFalse(sim_pm["result"]["isError"], sim_pm)
103
+ pm_summary = json.loads(sim_pm["result"]["content"][0]["text"])
104
+ self.assertEqual(pm_summary["venue"], "polymarket")
105
+ self.assertGreater(pm_summary["total_orders_submitted"], 0)
106
+
107
+ sim_hl = rpc(
108
+ {
109
+ "jsonrpc": "2.0",
110
+ "id": 6,
111
+ "method": "tools/call",
112
+ "params": {
113
+ "name": "feraterra_simulate_strategy",
114
+ "arguments": {
115
+ "scenario": "whipsaw_funding_squeeze",
116
+ "steps": 45,
117
+ "cancel_latency_ms": 120.0,
118
+ "half_spread_ticks": 1,
119
+ },
120
+ },
121
+ }
122
+ )
123
+ self.assertFalse(sim_hl["result"]["isError"], sim_hl)
124
+ hl_summary = json.loads(sim_hl["result"]["content"][0]["text"])
125
+ self.assertEqual(hl_summary["venue"], "hyperliquid")
126
+ self.assertGreater(hl_summary["total_orders_submitted"], 0)
127
+ finally:
128
+ proc.stdin.close()
129
+ proc.stdout.close()
130
+ if proc.stderr is not None:
131
+ proc.stderr.close()
132
+ proc.wait(timeout=10)
133
+
134
+
135
+ if __name__ == "__main__":
136
+ unittest.main()