mcp-aevo-server 0.2.0__py3-none-any.whl

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 @@
1
+ """Aevo MCP server package."""
@@ -0,0 +1,409 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import hashlib
5
+ import hmac
6
+ import json as json_mod
7
+ import random
8
+ import sys
9
+ import time
10
+ from typing import Any
11
+
12
+ import httpx
13
+
14
+ from .config import AevoMcpConfig
15
+ from .utils.rate_limit import RateLimiter
16
+
17
+ AuthPair = tuple[str, str]
18
+
19
+
20
+ class AevoApiError(RuntimeError):
21
+ def __init__(self, status_code: int, message: str, response: str | None = None):
22
+ self.status_code = status_code
23
+ self.response = response
24
+ if message:
25
+ message = f"[HTTP {status_code}] {message}"
26
+ super().__init__(message)
27
+
28
+
29
+ class AevoAPIClient:
30
+ def __init__(self, config: AevoMcpConfig):
31
+ self.config = config
32
+ self._client: httpx.AsyncClient | None = None
33
+ self._api_key = config.api_key
34
+ self._api_secret = config.api_secret
35
+ self._market_cache: tuple[float, list[dict[str, Any]]] = (0.0, [])
36
+ self._rate_limiter = RateLimiter(rate=30.0)
37
+
38
+ async def _ensure_client(self) -> httpx.AsyncClient:
39
+ if self._client is None:
40
+ self._client = httpx.AsyncClient(timeout=self.config.request_timeout_seconds)
41
+ return self._client
42
+
43
+ async def close(self) -> None:
44
+ if self._client is not None:
45
+ await self._client.aclose()
46
+ self._client = None
47
+
48
+ @property
49
+ def base_headers(self) -> dict[str, str]:
50
+ return {
51
+ "Accept": "application/json",
52
+ "Content-Type": "application/json",
53
+ }
54
+
55
+ @property
56
+ def has_credentials(self) -> bool:
57
+ return bool(self._api_key and self._api_secret)
58
+
59
+ def set_credentials(self, api_key: str, api_secret: str) -> None:
60
+ self._api_key = (api_key or "").strip()
61
+ self._api_secret = (api_secret or "").strip()
62
+
63
+ def clear_credentials(self) -> None:
64
+ self._api_key = ""
65
+ self._api_secret = ""
66
+
67
+ async def _request(
68
+ self,
69
+ method: str,
70
+ path: str,
71
+ *,
72
+ params: dict[str, str] | None = None,
73
+ json: dict[str, Any] | list[Any] | None = None,
74
+ headers: dict[str, str] | None = None,
75
+ auth: AuthPair | None = None,
76
+ ) -> Any:
77
+ await self._rate_limiter.acquire()
78
+ client = await self._ensure_client()
79
+ url = f"{self.config.api_base_url.rstrip('/')}/{path.lstrip('/')}"
80
+ merged_headers = self.base_headers.copy()
81
+ auth_key, auth_secret = auth or (self._api_key, self._api_secret)
82
+ auth_key = (auth_key or "").strip()
83
+ auth_secret = (auth_secret or "").strip()
84
+ if headers is not None:
85
+ merged_headers.update(headers)
86
+ else:
87
+ if auth_key and auth_secret:
88
+ timestamp = str(time.time_ns())
89
+ body_str = json_mod.dumps(json, separators=(",", ":")) if json else ""
90
+ message = f"{auth_key},{timestamp},{method.upper()},{path},{body_str}"
91
+ signature = hmac.new(auth_secret.encode(), message.encode(), hashlib.sha256).hexdigest()
92
+ merged_headers["AEVO-KEY"] = auth_key
93
+ merged_headers["AEVO-TIMESTAMP"] = timestamp
94
+ merged_headers["AEVO-SIGNATURE"] = signature
95
+
96
+ # Log order mutations to stderr
97
+ is_mutation = method.upper() in ("POST", "DELETE") and "order" in path.lower()
98
+ if is_mutation:
99
+ print(f"[aevo-mcp] {method.upper()} {path}", file=sys.stderr)
100
+
101
+ last_error = None
102
+ for attempt in range(1, self.config.request_retries + 1):
103
+ try:
104
+ response = await client.request(
105
+ method,
106
+ url,
107
+ params=params,
108
+ json=json,
109
+ headers=merged_headers,
110
+ )
111
+ except httpx.HTTPError as err:
112
+ last_error = err
113
+ if attempt >= self.config.request_retries:
114
+ raise AevoApiError(0, f"network error: {err}") from err
115
+ else:
116
+ last_error = None
117
+ if response.status_code >= 500 and attempt < self.config.request_retries:
118
+ # Jittered backoff
119
+ base_wait = 0.001 * (self.config.request_retry_base_ms * attempt)
120
+ jitter = base_wait * (0.5 + random.random())
121
+ await asyncio.sleep(jitter)
122
+ continue
123
+ if response.status_code >= 400:
124
+ try:
125
+ body = response.text
126
+ payload = response.json()
127
+ err = payload.get("error") if isinstance(payload, dict) else None
128
+ except Exception:
129
+ body = response.text
130
+ err = None
131
+ message = err or response.reason_phrase or "unknown error"
132
+ raise AevoApiError(response.status_code, message, response=body)
133
+
134
+ text = response.text or ""
135
+ if not text:
136
+ return {}
137
+ try:
138
+ return response.json()
139
+ except ValueError as err:
140
+ raise AevoApiError(response.status_code, f"invalid JSON response: {err}") from err
141
+
142
+ # Jittered backoff for network errors
143
+ base_wait = 0.001 * (self.config.request_retry_base_ms * attempt)
144
+ jitter = base_wait * (0.5 + random.random())
145
+ await asyncio.sleep(jitter)
146
+
147
+ if last_error is not None:
148
+ raise AevoApiError(0, f"request retries exhausted: {last_error}") from last_error
149
+ raise AevoApiError(0, "unexpected request state")
150
+
151
+ async def get_markets(
152
+ self, *, asset: str = "", instrument_type: str = "", use_cache: bool = True
153
+ ) -> list[dict[str, Any]]:
154
+ is_filtered = bool(asset or instrument_type)
155
+
156
+ if use_cache and not is_filtered:
157
+ now = time.time()
158
+ cached_at, cached_markets = self._market_cache
159
+ if now - cached_at < 20 and cached_markets:
160
+ return cached_markets
161
+
162
+ params = {}
163
+ if asset:
164
+ params["asset"] = asset
165
+ if instrument_type:
166
+ params["instrument_type"] = instrument_type
167
+
168
+ response = await self._request("GET", "/markets", params=params)
169
+ markets = response if isinstance(response, list) else response.get("data", response)
170
+ markets_list = list(markets)
171
+ if not is_filtered:
172
+ self._market_cache = (time.time(), markets_list)
173
+ return markets_list
174
+
175
+ async def resolve_instrument_id(self, instrument_name: str) -> str | None:
176
+ normalized = (instrument_name or "").strip()
177
+ if normalized.isdigit():
178
+ return normalized
179
+
180
+ markets = await self.get_markets()
181
+ direct = {str(item.get("instrument_name")): item for item in markets}
182
+ direct_match = direct.get(normalized)
183
+ if direct_match:
184
+ return str(direct_match.get("instrument_id"))
185
+
186
+ lowered = normalized.lower()
187
+ for item in markets:
188
+ candidate = str(item.get("instrument_name", "")).strip().lower()
189
+ if candidate == lowered:
190
+ return str(item.get("instrument_id"))
191
+ return None
192
+
193
+ async def get_assets(self) -> Any:
194
+ return await self._request("GET", "/assets")
195
+
196
+ async def get_orderbook(self, instrument_name: str) -> Any:
197
+ return await self._request("GET", "/orderbook", params={"instrument_name": instrument_name})
198
+
199
+ async def get_instrument(self, instrument_name: str) -> Any:
200
+ return await self._request("GET", f"/instrument/{instrument_name}")
201
+
202
+ async def update_leverage(self, instrument_id: int, leverage: int, auth: AuthPair | None = None) -> Any:
203
+ return await self._request(
204
+ "POST",
205
+ "/account/leverage",
206
+ json={"instrument": instrument_id, "leverage": leverage},
207
+ auth=auth,
208
+ )
209
+
210
+ async def get_account(self, auth: AuthPair | None = None) -> Any:
211
+ return await self._request("GET", "/account", auth=auth)
212
+
213
+ async def get_positions(self, auth: AuthPair | None = None) -> Any:
214
+ return await self._request("GET", "/positions", auth=auth)
215
+
216
+ async def get_portfolio(self, auth: AuthPair | None = None) -> Any:
217
+ return await self._request("GET", "/portfolio", auth=auth)
218
+
219
+ async def get_orders(self, auth: AuthPair | None = None) -> Any:
220
+ return await self._request("GET", "/orders", auth=auth)
221
+
222
+ async def get_order(self, order_id: str, auth: AuthPair | None = None) -> Any:
223
+ return await self._request("GET", f"/orders/{order_id}", auth=auth)
224
+
225
+ async def create_order(self, payload: dict[str, Any], auth: AuthPair | None = None) -> Any:
226
+ return await self._request("POST", "/orders", json=payload, auth=auth)
227
+
228
+ async def cancel_order(self, order_id: str, auth: AuthPair | None = None) -> Any:
229
+ return await self._request("DELETE", f"/orders/{order_id}", auth=auth)
230
+
231
+ async def cancel_all_orders(
232
+ self,
233
+ instrument_type: str | None = None,
234
+ asset: str | None = None,
235
+ auth: AuthPair | None = None,
236
+ ) -> Any:
237
+ body: dict[str, Any] = {}
238
+ if instrument_type:
239
+ body["instrument_type"] = instrument_type
240
+ if asset:
241
+ body["asset"] = asset
242
+ return await self._request("DELETE", "/orders-all", json=body or None, auth=auth)
243
+
244
+ async def cancel_orders(
245
+ self, order_ids: list[str], instrument_type: str | None = None, auth: AuthPair | None = None
246
+ ) -> Any:
247
+ body: dict[str, Any] = {"order_ids": order_ids}
248
+ if instrument_type:
249
+ body["instrument_type"] = instrument_type
250
+ return await self._request("DELETE", "/orders", json=body, auth=auth)
251
+
252
+ # -- Public market data --
253
+
254
+ async def get_funding(self, instrument_name: str) -> Any:
255
+ return await self._request("GET", "/funding", params={"instrument_name": instrument_name})
256
+
257
+ async def get_funding_history(
258
+ self,
259
+ instrument_name: str,
260
+ start_time: str = "",
261
+ end_time: str = "",
262
+ limit: str = "",
263
+ offset: str = "",
264
+ ) -> Any:
265
+ params: dict[str, str] = {"instrument_name": instrument_name}
266
+ if start_time:
267
+ params["start_time"] = start_time
268
+ if end_time:
269
+ params["end_time"] = end_time
270
+ if limit:
271
+ params["limit"] = limit
272
+ if offset:
273
+ params["offset"] = offset
274
+ return await self._request("GET", "/funding-history", params=params)
275
+
276
+ async def get_trade_history_public(self, instrument_name: str) -> Any:
277
+ return await self._request("GET", f"/instrument/{instrument_name}/trade-history")
278
+
279
+ async def get_statistics(self) -> Any:
280
+ return await self._request("GET", "/statistics")
281
+
282
+ async def get_index(self, asset: str) -> Any:
283
+ return await self._request("GET", "/index", params={"asset": asset})
284
+
285
+ async def get_index_history(
286
+ self,
287
+ asset: str,
288
+ resolution: str = "",
289
+ start_time: str = "",
290
+ end_time: str = "",
291
+ limit: str = "",
292
+ ) -> Any:
293
+ params: dict[str, str] = {"asset": asset}
294
+ if resolution:
295
+ params["resolution"] = resolution
296
+ if start_time:
297
+ params["start_time"] = start_time
298
+ if end_time:
299
+ params["end_time"] = end_time
300
+ if limit:
301
+ params["limit"] = limit
302
+ return await self._request("GET", "/index-history", params=params)
303
+
304
+ async def get_mark_history(
305
+ self,
306
+ instrument_name: str,
307
+ resolution: str = "",
308
+ start_time: str = "",
309
+ end_time: str = "",
310
+ limit: str = "",
311
+ ) -> Any:
312
+ params: dict[str, str] = {"instrument_name": instrument_name}
313
+ if resolution:
314
+ params["resolution"] = resolution
315
+ if start_time:
316
+ params["start_time"] = start_time
317
+ if end_time:
318
+ params["end_time"] = end_time
319
+ if limit:
320
+ params["limit"] = limit
321
+ return await self._request("GET", "/mark-history", params=params)
322
+
323
+ async def get_settlement_history(
324
+ self,
325
+ asset: str = "",
326
+ start_time: str = "",
327
+ end_time: str = "",
328
+ limit: str = "",
329
+ ) -> Any:
330
+ params: dict[str, str] = {}
331
+ if asset:
332
+ params["asset"] = asset
333
+ if start_time:
334
+ params["start_time"] = start_time
335
+ if end_time:
336
+ params["end_time"] = end_time
337
+ if limit:
338
+ params["limit"] = limit
339
+ return await self._request("GET", "/settlement-history", params=params)
340
+
341
+ async def get_expiries(self, asset: str) -> Any:
342
+ return await self._request("GET", "/expiries", params={"asset": asset})
343
+
344
+ async def get_time(self) -> Any:
345
+ return await self._request("GET", "/time")
346
+
347
+ # -- Private (auth-gated) --
348
+
349
+ async def get_account_trade_history(
350
+ self,
351
+ start_time: str = "",
352
+ end_time: str = "",
353
+ limit: str = "",
354
+ offset: str = "",
355
+ trade_types: str = "",
356
+ instrument_name: str = "",
357
+ instrument_type: str = "",
358
+ asset: str = "",
359
+ auth: AuthPair | None = None,
360
+ ) -> Any:
361
+ params: dict[str, str] = {}
362
+ if start_time:
363
+ params["start_time"] = start_time
364
+ if end_time:
365
+ params["end_time"] = end_time
366
+ if limit:
367
+ params["limit"] = limit
368
+ if offset:
369
+ params["offset"] = offset
370
+ if trade_types:
371
+ params["trade_types"] = trade_types
372
+ if instrument_name:
373
+ params["instrument_name"] = instrument_name
374
+ if instrument_type:
375
+ params["instrument_type"] = instrument_type
376
+ if asset:
377
+ params["asset"] = asset
378
+ return await self._request("GET", "/trade-history", params=params, auth=auth)
379
+
380
+ async def get_order_history(
381
+ self,
382
+ start_time: str = "",
383
+ end_time: str = "",
384
+ limit: str = "",
385
+ offset: str = "",
386
+ instrument_name: str = "",
387
+ instrument_type: str = "",
388
+ asset: str = "",
389
+ auth: AuthPair | None = None,
390
+ ) -> Any:
391
+ params: dict[str, str] = {}
392
+ if start_time:
393
+ params["start_time"] = start_time
394
+ if end_time:
395
+ params["end_time"] = end_time
396
+ if limit:
397
+ params["limit"] = limit
398
+ if offset:
399
+ params["offset"] = offset
400
+ if instrument_name:
401
+ params["instrument_name"] = instrument_name
402
+ if instrument_type:
403
+ params["instrument_type"] = instrument_type
404
+ if asset:
405
+ params["asset"] = asset
406
+ return await self._request("GET", "/order-history", params=params, auth=auth)
407
+
408
+ async def register(self, payload: dict[str, Any]) -> Any:
409
+ return await self._request("POST", "/register", json=payload, headers={})
@@ -0,0 +1,114 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from dataclasses import dataclass
6
+
7
+
8
+ class AevoConfigError(ValueError):
9
+ """Raised when required AEVO MCP environment configuration is invalid."""
10
+
11
+
12
+ NETWORKS: dict[str, dict[str, object]] = {
13
+ "mainnet": {
14
+ "domain": "Aevo Mainnet",
15
+ "chain_id": 1,
16
+ "api_base_url": "https://api.aevo.xyz",
17
+ },
18
+ "testnet": {
19
+ "domain": "Aevo Testnet",
20
+ "chain_id": 11155111,
21
+ "api_base_url": "https://api-testnet.aevo.xyz",
22
+ },
23
+ }
24
+
25
+
26
+ def _env(name: str, default: str | None = None) -> str | None:
27
+ value = os.getenv(name)
28
+ if value is not None:
29
+ value = value.strip()
30
+ if value == "":
31
+ return default
32
+ return value if value is not None else default
33
+
34
+
35
+ def _env_int(name: str, default: int) -> int:
36
+ raw = _env(name, None)
37
+ if raw is None:
38
+ return default
39
+ try:
40
+ return int(raw)
41
+ except ValueError as err:
42
+ raise AevoConfigError(f"{name} must be an integer") from err
43
+
44
+
45
+ def _env_bool(name: str, default: bool) -> bool:
46
+ raw = _env(name, str(default)).lower()
47
+ if raw in {"1", "true", "yes", "y", "on"}:
48
+ return True
49
+ if raw in {"0", "false", "no", "n", "off"}:
50
+ return False
51
+ raise AevoConfigError(f"{name} must be true|false")
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class AevoNetworkConfig:
56
+ name: str
57
+ chain_id: int
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class AevoMcpConfig:
62
+ environment: str
63
+ api_base_url: str
64
+ wallet_address: str
65
+ wallet_private_key: str
66
+ signing_key_private_key: str
67
+ api_key: str
68
+ api_secret: str
69
+ auto_register: bool
70
+ request_timeout_seconds: int
71
+ request_retries: int
72
+ request_retry_base_ms: int
73
+ request_id_prefix: str
74
+ mcp_host: str
75
+ mcp_port: int
76
+ mcp_path: str
77
+ mcp_transport: str
78
+
79
+ @property
80
+ def network(self) -> AevoNetworkConfig:
81
+ info = NETWORKS[self.environment]
82
+ return AevoNetworkConfig(name=info["domain"], chain_id=int(info["chain_id"]))
83
+
84
+
85
+ def load_config() -> AevoMcpConfig:
86
+ environment = ((_env("AEVO_ENVIRONMENT") or _env("AEVO_ENV") or "mainnet") or "mainnet").lower()
87
+ if environment not in NETWORKS:
88
+ raise AevoConfigError(f"AEVO_ENVIRONMENT (or AEVO_ENV) must be one of: {', '.join(sorted(NETWORKS.keys()))}")
89
+ env_cfg = NETWORKS[environment]
90
+
91
+ # Warn on deprecated env var names
92
+ if _env("AEVO_ACCOUNT_ADDRESS"):
93
+ print("[aevo-mcp] AEVO_ACCOUNT_ADDRESS is deprecated, use AEVO_WALLET_ADDRESS", file=sys.stderr)
94
+ if _env("AEVO_ACCOUNT_PRIVATE_KEY"):
95
+ print("[aevo-mcp] AEVO_ACCOUNT_PRIVATE_KEY is deprecated, use AEVO_WALLET_PRIVATE_KEY", file=sys.stderr)
96
+
97
+ return AevoMcpConfig(
98
+ environment=environment,
99
+ api_base_url=(_env("AEVO_API_BASE_URL", env_cfg["api_base_url"]) or env_cfg["api_base_url"]).rstrip("/"),
100
+ wallet_address=_env("AEVO_WALLET_ADDRESS") or _env("AEVO_ACCOUNT_ADDRESS", "") or "",
101
+ wallet_private_key=_env("AEVO_WALLET_PRIVATE_KEY") or _env("AEVO_ACCOUNT_PRIVATE_KEY", "") or "",
102
+ signing_key_private_key=_env("AEVO_SIGNING_KEY_PRIVATE_KEY", "") or "",
103
+ api_key=_env("AEVO_API_KEY", "") or "",
104
+ api_secret=_env("AEVO_API_SECRET", "") or "",
105
+ auto_register=_env_bool("AEVO_AUTO_REGISTER", False),
106
+ request_timeout_seconds=_env_int("AEVO_REQUEST_TIMEOUT_SECONDS", 12),
107
+ request_retries=_env_int("AEVO_REQUEST_RETRIES", 3),
108
+ request_retry_base_ms=_env_int("AEVO_REQUEST_RETRY_BASE_MS", 200),
109
+ request_id_prefix=_env("AEVO_REQUEST_ID_PREFIX", "aevo-mcp"),
110
+ mcp_host=_env("AEVO_MCP_HOST", "127.0.0.1") or "127.0.0.1",
111
+ mcp_port=_env_int("AEVO_MCP_PORT", 8080),
112
+ mcp_path=(_env("AEVO_MCP_PATH", "/mcp") or "/mcp"),
113
+ mcp_transport=(_env("AEVO_MCP_TRANSPORT", "streamable-http") or "streamable-http").lower(),
114
+ )
@@ -0,0 +1,6 @@
1
+ """Prompt modules for AEVO MCP."""
2
+
3
+ from .options_prompts import register_options_prompts
4
+ from .trader_prompts import register_prompts
5
+
6
+ __all__ = ["register_options_prompts", "register_prompts"]