iwym-mcp 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.
iwym_mcp/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """stdio MCP bridge for iwym catalog maintenance and radar opportunity queries."""
2
+
3
+ __version__ = "0.2.0"
iwym_mcp/client.py ADDED
@@ -0,0 +1,102 @@
1
+ """HTTP client for the iwym operator API (assets / exchanges / radar)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import httpx
8
+
9
+ ASSETS_PREFIX = "/api/v1/assets"
10
+ EXCHANGES_PREFIX = "/api/v1/exchanges"
11
+ RADAR_PREFIX = "/api/v1/radar"
12
+
13
+ # Back-compat alias used by older tests / docs.
14
+ API_PREFIX = ASSETS_PREFIX
15
+
16
+
17
+ class IwymApiError(Exception):
18
+ def __init__(self, status_code: int, detail: object):
19
+ self.status_code = status_code
20
+ self.detail = detail
21
+ super().__init__(f"{status_code}: {detail}")
22
+
23
+
24
+ class IwymApiClient:
25
+ def __init__(self, base_url: str, token: str, *, timeout: float = 120.0):
26
+ self._base = base_url.rstrip("/")
27
+ self._token = token
28
+ self._timeout = timeout
29
+
30
+ def _full_path(self, path: str) -> str:
31
+ """Resolve a relative assets path or absolute ``/api/…`` path."""
32
+ if path.startswith("/api/"):
33
+ return path
34
+ if path in ("", "/"):
35
+ return ASSETS_PREFIX
36
+ if not path.startswith("/"):
37
+ path = f"/{path}"
38
+ return f"{ASSETS_PREFIX}{path}"
39
+
40
+ async def request(
41
+ self,
42
+ method: str,
43
+ path: str,
44
+ *,
45
+ json: Any | None = None,
46
+ params: dict[str, Any] | None = None,
47
+ ) -> Any:
48
+ async with httpx.AsyncClient(base_url=self._base, timeout=self._timeout) as client:
49
+ response = await client.request(
50
+ method,
51
+ self._full_path(path),
52
+ headers={"Authorization": f"Bearer {self._token}"},
53
+ json=json,
54
+ params=params,
55
+ )
56
+ if response.status_code >= 400:
57
+ raise IwymApiError(response.status_code, _error_detail(response))
58
+ if response.status_code == 204 or not response.content:
59
+ return None
60
+ return response.json()
61
+
62
+
63
+ def patch_asset_body(
64
+ *,
65
+ display_symbol: str | None = None,
66
+ kind: str | None = None,
67
+ oracle_feed_type: str | None = None,
68
+ anchor_asset_id: str | None = None,
69
+ enabled: bool | None = None,
70
+ include_anchor: bool = False,
71
+ ) -> dict[str, Any]:
72
+ """Build a PATCH body. Omitted / None fields are left unchanged server-side.
73
+
74
+ Pass ``include_anchor=True`` with ``anchor_asset_id=None`` to clear the
75
+ anchor (send JSON null). Otherwise a None anchor is not sent.
76
+ """
77
+ body: dict[str, Any] = {}
78
+ if display_symbol is not None:
79
+ body["display_symbol"] = display_symbol
80
+ if kind is not None:
81
+ body["kind"] = kind
82
+ if oracle_feed_type is not None:
83
+ body["oracle_feed_type"] = oracle_feed_type
84
+ if enabled is not None:
85
+ body["enabled"] = enabled
86
+ if include_anchor:
87
+ body["anchor_asset_id"] = anchor_asset_id
88
+ elif anchor_asset_id is not None:
89
+ body["anchor_asset_id"] = anchor_asset_id
90
+ return body
91
+
92
+
93
+ def _error_detail(response: httpx.Response) -> object:
94
+ try:
95
+ body = response.json()
96
+ except ValueError:
97
+ return response.text
98
+ if isinstance(body, dict) and isinstance(body.get("error"), dict):
99
+ return body["error"]
100
+ if isinstance(body, dict) and "detail" in body:
101
+ return body["detail"]
102
+ return body
iwym_mcp/server.py ADDED
@@ -0,0 +1,552 @@
1
+ """MCP server (stdio) for iwym catalog maintenance and radar opportunity queries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ from typing import Any
9
+ from urllib.parse import quote
10
+
11
+ from iwym_mcp.client import (
12
+ EXCHANGES_PREFIX,
13
+ RADAR_PREFIX,
14
+ IwymApiClient,
15
+ IwymApiError,
16
+ patch_asset_body,
17
+ )
18
+
19
+ try:
20
+ from mcp.server import MCPServer as _Server
21
+ except ImportError: # pragma: no cover
22
+ from mcp.server.fastmcp import FastMCP as _Server
23
+
24
+ try:
25
+ from mcp.server.mcpserver.exceptions import ToolError
26
+ except ImportError: # pragma: no cover
27
+ try:
28
+ from mcp.server.fastmcp.exceptions import ToolError
29
+ except ImportError: # pragma: no cover
30
+ ToolError = None # type: ignore[misc, assignment]
31
+
32
+ mcp = _Server("iwym")
33
+
34
+ _client: IwymApiClient | None = None
35
+
36
+ _ASSET_KINDS = "spot_crypto, stable, wrapped, leveraged_token, or equity"
37
+ _TOKEN_STATUSES = frozenset({"trading", "offline"})
38
+
39
+
40
+ def _require_env() -> IwymApiClient:
41
+ base_url = os.environ.get("IWYM_API_BASE_URL", "").strip()
42
+ token = os.environ.get("IWYM_OPERATOR_TOKEN", "").strip()
43
+ missing: list[str] = []
44
+ if not base_url:
45
+ missing.append("IWYM_API_BASE_URL")
46
+ if not token:
47
+ missing.append("IWYM_OPERATOR_TOKEN")
48
+ if missing:
49
+ names = ", ".join(missing)
50
+ print(
51
+ f"error: missing required environment variable(s): {names}\n"
52
+ "Set them before starting iwym-mcp, e.g.:\n"
53
+ " export IWYM_API_BASE_URL=http://127.0.0.1:8000\n"
54
+ " export IWYM_OPERATOR_TOKEN=<paste from Settings → System → OPERATOR API>",
55
+ file=sys.stderr,
56
+ )
57
+ raise SystemExit(1)
58
+ return IwymApiClient(base_url, token)
59
+
60
+
61
+ def get_client() -> IwymApiClient:
62
+ global _client
63
+ if _client is None:
64
+ _client = _require_env()
65
+ return _client
66
+
67
+
68
+ def _format_api_error(exc: IwymApiError) -> str:
69
+ detail = exc.detail
70
+ if isinstance(detail, dict | list):
71
+ detail_text = json.dumps(detail, ensure_ascii=False)
72
+ else:
73
+ detail_text = str(detail)
74
+ return f"HTTP {exc.status_code}: {detail_text}"
75
+
76
+
77
+ def _tool_error(exc: IwymApiError) -> dict[str, Any]:
78
+ message = _format_api_error(exc)
79
+ if ToolError is not None:
80
+ raise ToolError(message) from exc
81
+ return {"error": True, "status_code": exc.status_code, "detail": exc.detail}
82
+
83
+
84
+ def _fail(message: str) -> dict[str, Any]:
85
+ if ToolError is not None:
86
+ raise ToolError(message)
87
+ return {"error": True, "detail": message}
88
+
89
+
90
+ async def _request(
91
+ method: str,
92
+ path: str,
93
+ *,
94
+ json_body: Any | None = None,
95
+ params: dict[str, Any] | None = None,
96
+ ) -> Any:
97
+ try:
98
+ return await get_client().request(method, path, json=json_body, params=params)
99
+ except IwymApiError as exc:
100
+ return _tool_error(exc)
101
+
102
+
103
+ def _drop_none(params: dict[str, Any]) -> dict[str, Any]:
104
+ return {k: v for k, v in params.items() if v is not None}
105
+
106
+
107
+ def _encode_path_seg(value: str) -> str:
108
+ return quote(value.strip(), safe="")
109
+
110
+
111
+ # --- A. Assets ------------------------------------------------------------
112
+
113
+
114
+ @mcp.tool()
115
+ async def list_assets() -> Any:
116
+ """List whitelist assets, including disabled rows (tokens included per row)."""
117
+ page_size = 500
118
+ offset = 0
119
+ items: list[Any] = []
120
+ total = 0
121
+ while True:
122
+ page = await _request(
123
+ "GET",
124
+ "",
125
+ params={"offset": offset, "limit": page_size},
126
+ )
127
+ if isinstance(page, dict) and "error" in page:
128
+ return page
129
+ if not isinstance(page, dict):
130
+ return page
131
+ batch = page.get("items") or []
132
+ total = int(page.get("total") or 0)
133
+ items.extend(batch)
134
+ if len(items) >= total or not batch:
135
+ break
136
+ offset += len(batch)
137
+ return items
138
+
139
+
140
+ @mcp.tool()
141
+ async def get_asset(asset_id: str) -> Any:
142
+ """Get one asset by id (includes tokens[]). Lowercase slug such as btc or shib."""
143
+ return await _request("GET", f"/{asset_id}")
144
+
145
+
146
+ @mcp.tool()
147
+ async def catalog_diff(
148
+ venue: str | None = None,
149
+ include_orphans: bool = False,
150
+ ) -> Any:
151
+ """Diff spot/perp catalog bases against unique assets.display_symbol.
152
+
153
+ Omit venue to scan every seeded ticker venue (binance, okx, …).
154
+ Entries are missing bases, tickers mapped to a disabled asset, and
155
+ (when include_orphans) whitelist tickers absent from a fully read catalog.
156
+ """
157
+ params: dict[str, Any] = {"include_orphans": include_orphans}
158
+ if venue:
159
+ params["venue"] = venue
160
+ return await _request("GET", "/catalog-diffs", params=params)
161
+
162
+
163
+ @mcp.tool()
164
+ async def create_or_upsert_asset(
165
+ asset_id: str,
166
+ display_symbol: str,
167
+ kind: str = "spot_crypto",
168
+ oracle_feed_type: str = "market",
169
+ anchor_asset_id: str | None = None,
170
+ enabled: bool = False,
171
+ ) -> Any:
172
+ """Create an asset when missing (instrument links use unique display_symbol).
173
+
174
+ kind is one of: spot_crypto, stable, wrapped, leveraged_token, equity.
175
+ enabled is only the Radar scan whitelist (default false). Scalar fields
176
+ apply only when the row is created; a repeat call does not change kind,
177
+ oracle, display_symbol, or enabled — use update_asset / set_enabled.
178
+ """
179
+ payload: dict[str, Any] = {
180
+ "display_symbol": display_symbol,
181
+ "kind": kind,
182
+ "oracle_feed_type": oracle_feed_type,
183
+ "enabled": enabled,
184
+ }
185
+ if anchor_asset_id is not None:
186
+ payload["anchor_asset_id"] = anchor_asset_id
187
+ return await _request("PUT", f"/{asset_id}", json_body=payload)
188
+
189
+
190
+ @mcp.tool()
191
+ async def update_asset(
192
+ asset_id: str,
193
+ display_symbol: str | None = None,
194
+ kind: str | None = None,
195
+ oracle_feed_type: str | None = None,
196
+ anchor_asset_id: str | None = None,
197
+ clear_anchor: bool = False,
198
+ enabled: bool | None = None,
199
+ ) -> Any:
200
+ """PATCH scalar fields on an existing asset. Omitted fields stay unchanged.
201
+
202
+ kind is one of: spot_crypto, stable, wrapped, leveraged_token, equity.
203
+ Pass clear_anchor=true to send anchor_asset_id=null.
204
+ """
205
+ if clear_anchor and anchor_asset_id is not None:
206
+ return _fail("pass clear_anchor or anchor_asset_id, not both")
207
+ if (
208
+ display_symbol is None
209
+ and kind is None
210
+ and oracle_feed_type is None
211
+ and enabled is None
212
+ and not clear_anchor
213
+ and anchor_asset_id is None
214
+ ):
215
+ return _fail(
216
+ "pass at least one of display_symbol, kind, oracle_feed_type, "
217
+ "anchor_asset_id, clear_anchor, or enabled",
218
+ )
219
+ if kind is not None and kind not in {
220
+ "spot_crypto",
221
+ "stable",
222
+ "wrapped",
223
+ "leveraged_token",
224
+ "equity",
225
+ }:
226
+ return _fail(f"kind must be {_ASSET_KINDS}")
227
+ body = patch_asset_body(
228
+ display_symbol=display_symbol,
229
+ kind=kind,
230
+ oracle_feed_type=oracle_feed_type,
231
+ anchor_asset_id=anchor_asset_id,
232
+ enabled=enabled,
233
+ include_anchor=clear_anchor,
234
+ )
235
+ return await _request("PATCH", f"/{asset_id}", json_body=body)
236
+
237
+
238
+ @mcp.tool()
239
+ async def set_enabled(asset_id: str, enabled: bool) -> Any:
240
+ """Set whether the asset is in the Radar scan whitelist."""
241
+ return await _request(
242
+ "PATCH",
243
+ f"/{asset_id}",
244
+ json_body=patch_asset_body(enabled=enabled),
245
+ )
246
+
247
+
248
+ @mcp.tool()
249
+ async def soft_disable_asset(asset_id: str) -> Any:
250
+ """Soft-disable an asset (enabled=false); row and tokens stay."""
251
+ return await _request("DELETE", f"/{asset_id}")
252
+
253
+
254
+ # --- B. Instruments -------------------------------------------------------
255
+
256
+
257
+ @mcp.tool()
258
+ async def list_asset_instruments(
259
+ asset_id: str,
260
+ exchange: str | None = None,
261
+ ) -> Any:
262
+ """List catalog instruments linked to this whitelist asset (base_asset_id)."""
263
+ params = _drop_none({"exchange": exchange})
264
+ return await _request("GET", f"/{asset_id}/instruments", params=params or None)
265
+
266
+
267
+ @mcp.tool()
268
+ async def search_instruments(
269
+ q: str,
270
+ tradable_only: bool = True,
271
+ limit: int = 200,
272
+ ) -> Any:
273
+ """Trade Add-pair style keyword search across enabled CEX + DEX instruments."""
274
+ if not q.strip():
275
+ return _fail("q must be non-empty")
276
+ limit = max(1, min(int(limit), 500))
277
+ return await _request(
278
+ "GET",
279
+ f"{EXCHANGES_PREFIX}/instruments/search",
280
+ params={
281
+ "q": q.strip(),
282
+ "tradable_only": tradable_only,
283
+ "limit": limit,
284
+ },
285
+ )
286
+
287
+
288
+ @mcp.tool()
289
+ async def link_instrument(
290
+ instrument_id: int,
291
+ base_asset_id: str | None = None,
292
+ quote_asset_id: str | None = None,
293
+ enabled: bool | None = None,
294
+ ) -> Any:
295
+ """Manually attach (or reattach) an instrument to whitelist asset id(s).
296
+
297
+ PATCH /api/v1/exchanges/instruments/{id}/link. Pass at least one of
298
+ base_asset_id, quote_asset_id, or enabled.
299
+ """
300
+ if base_asset_id is None and quote_asset_id is None and enabled is None:
301
+ return _fail("pass at least one of base_asset_id, quote_asset_id, or enabled")
302
+ body = _drop_none(
303
+ {
304
+ "base_asset_id": base_asset_id,
305
+ "quote_asset_id": quote_asset_id,
306
+ "enabled": enabled,
307
+ },
308
+ )
309
+ return await _request(
310
+ "PATCH",
311
+ f"{EXCHANGES_PREFIX}/instruments/{int(instrument_id)}/link",
312
+ json_body=body,
313
+ )
314
+
315
+
316
+ @mcp.tool()
317
+ async def sync_instruments(
318
+ exchange: str | None = None,
319
+ code: str | None = None,
320
+ asset_id: str | None = None,
321
+ ) -> Any:
322
+ """Full catalog sync into instruments (hits upstream exchanges).
323
+
324
+ Heavy operation. Optional filters: exchange, code (display ticker), asset_id.
325
+ Also syncs Binance Alpha → asset_tokens when applicable.
326
+ """
327
+ params = _drop_none({"exchange": exchange, "code": code, "asset_id": asset_id})
328
+ return await _request(
329
+ "POST",
330
+ f"{EXCHANGES_PREFIX}/instruments/sync",
331
+ params=params or None,
332
+ )
333
+
334
+
335
+ # --- C. Tokens ------------------------------------------------------------
336
+
337
+
338
+ @mcp.tool()
339
+ async def create_asset_token(
340
+ asset_id: str,
341
+ chain_key: str,
342
+ address: str,
343
+ symbol: str,
344
+ decimals: int,
345
+ status: str = "trading",
346
+ enabled: bool = True,
347
+ ) -> Any:
348
+ """Add an on-chain contract row under a whitelist asset."""
349
+ if status not in _TOKEN_STATUSES:
350
+ return _fail("status must be trading or offline")
351
+ if decimals < 0 or decimals > 255:
352
+ return _fail("decimals must be 0..255")
353
+ body = {
354
+ "chain_key": chain_key.strip(),
355
+ "address": address.strip(),
356
+ "symbol": symbol.strip(),
357
+ "decimals": int(decimals),
358
+ "status": status,
359
+ "enabled": enabled,
360
+ }
361
+ return await _request("POST", f"/{asset_id}/tokens", json_body=body)
362
+
363
+
364
+ @mcp.tool()
365
+ async def update_asset_token(
366
+ asset_id: str,
367
+ chain_key: str,
368
+ address: str,
369
+ symbol: str | None = None,
370
+ decimals: int | None = None,
371
+ status: str | None = None,
372
+ enabled: bool | None = None,
373
+ ) -> Any:
374
+ """PATCH an existing asset_tokens row (identified by chain_key + address)."""
375
+ if status is not None and status not in _TOKEN_STATUSES:
376
+ return _fail("status must be trading or offline")
377
+ if decimals is not None and (decimals < 0 or decimals > 255):
378
+ return _fail("decimals must be 0..255")
379
+ if symbol is None and decimals is None and status is None and enabled is None:
380
+ return _fail("pass at least one of symbol, decimals, status, enabled")
381
+ body = _drop_none(
382
+ {
383
+ "symbol": symbol,
384
+ "decimals": decimals,
385
+ "status": status,
386
+ "enabled": enabled,
387
+ },
388
+ )
389
+ path = (
390
+ f"/{asset_id}/tokens/{_encode_path_seg(chain_key)}/{_encode_path_seg(address)}"
391
+ )
392
+ return await _request("PATCH", path, json_body=body)
393
+
394
+
395
+ @mcp.tool()
396
+ async def delete_asset_token(asset_id: str, chain_key: str, address: str) -> Any:
397
+ """Delete one asset_tokens row (204 → null)."""
398
+ path = (
399
+ f"/{asset_id}/tokens/{_encode_path_seg(chain_key)}/{_encode_path_seg(address)}"
400
+ )
401
+ return await _request("DELETE", path)
402
+
403
+
404
+ @mcp.tool()
405
+ async def reassign_asset_token(
406
+ chain_key: str,
407
+ address: str,
408
+ asset_id: str,
409
+ ) -> Any:
410
+ """Move a contract row to another whitelist asset."""
411
+ return await _request(
412
+ "POST",
413
+ "/tokens/reassign",
414
+ json_body={
415
+ "chain_key": chain_key.strip(),
416
+ "address": address.strip(),
417
+ "asset_id": asset_id.strip(),
418
+ },
419
+ )
420
+
421
+
422
+ @mcp.tool()
423
+ async def migrate_asset_token(
424
+ chain_key: str,
425
+ address: str,
426
+ new_address: str,
427
+ new_chain_key: str | None = None,
428
+ ) -> Any:
429
+ """Replace a contract address (and optionally chain); refresh on-chain metadata."""
430
+ body: dict[str, Any] = {
431
+ "chain_key": chain_key.strip(),
432
+ "address": address.strip(),
433
+ "new_address": new_address.strip(),
434
+ }
435
+ if new_chain_key is not None:
436
+ body["new_chain_key"] = new_chain_key.strip()
437
+ return await _request("POST", "/tokens/migrate", json_body=body)
438
+
439
+
440
+ @mcp.tool()
441
+ async def lookup_asset_tokens(
442
+ address: str,
443
+ chain_key: str | None = None,
444
+ ) -> Any:
445
+ """Resolve chain + decimals for a paste address without writing assets."""
446
+ body: dict[str, Any] = {"address": address.strip()}
447
+ if chain_key is not None:
448
+ body["chain_key"] = chain_key.strip()
449
+ return await _request("POST", "/token-lookups", json_body=body)
450
+
451
+
452
+ # --- D. Radar opportunities (read-only) -----------------------------------
453
+
454
+
455
+ @mcp.tool()
456
+ async def list_spreads(
457
+ kind: str | None = None,
458
+ q: str | None = None,
459
+ exclude_venues: str | None = None,
460
+ chains: str | None = None,
461
+ min_volume: str | None = None,
462
+ sort: str = "edge_long_desc",
463
+ offset: int = 0,
464
+ limit: int = 100,
465
+ ) -> Any:
466
+ """Query the live spread board (REST window; default limit 100, max 300).
467
+
468
+ kind examples: perp_perp, perp_spot, spot_spot, chain_perp, chain_spot, chain_chain.
469
+ exclude_venues / chains: comma-separated. sort: field_asc|field_desc.
470
+ """
471
+ limit = max(1, min(int(limit), 300))
472
+ offset = max(0, int(offset))
473
+ params = _drop_none(
474
+ {
475
+ "kind": kind,
476
+ "q": q,
477
+ "exclude_venues": exclude_venues,
478
+ "chains": chains,
479
+ "min_volume": min_volume,
480
+ "sort": sort,
481
+ "offset": offset,
482
+ "limit": limit,
483
+ },
484
+ )
485
+ return await _request("GET", f"{RADAR_PREFIX}/spreads", params=params)
486
+
487
+
488
+ @mcp.tool()
489
+ async def list_funding_opps(
490
+ mode: str | None = None,
491
+ fee: str = "taker",
492
+ q: str | None = None,
493
+ venues: str | None = None,
494
+ hedge_only: bool = False,
495
+ min_apr: str | None = None,
496
+ max_break_h: str | None = None,
497
+ min_oi_m: str | None = None,
498
+ intervals: str | None = None,
499
+ sort: str = "apr",
500
+ sort_dir: str = "desc",
501
+ offset: int = 0,
502
+ limit: int = 100,
503
+ ) -> Any:
504
+ """Query funding opportunity board (REST; default limit 100, max 300).
505
+
506
+ mode: perp_perp | perp_spot | spot_perp | perp_chain | chain_perp (omit = all).
507
+ venues: comma-separated venue buckets to EXCLUDE.
508
+ intervals: comma-separated settlement hours (1,2,4,8).
509
+ """
510
+ if fee not in {"taker", "maker", "zero"}:
511
+ return _fail("fee must be taker, maker, or zero")
512
+ if mode is not None and mode not in {
513
+ "perp_perp",
514
+ "perp_spot",
515
+ "spot_perp",
516
+ "perp_chain",
517
+ "chain_perp",
518
+ }:
519
+ return _fail(
520
+ "mode must be perp_perp, perp_spot, spot_perp, perp_chain, or chain_perp",
521
+ )
522
+ if sort_dir not in {"asc", "desc"}:
523
+ return _fail("sort_dir must be asc or desc")
524
+ limit = max(1, min(int(limit), 300))
525
+ offset = max(0, int(offset))
526
+ params = _drop_none(
527
+ {
528
+ "mode": mode,
529
+ "fee": fee,
530
+ "q": q,
531
+ "venues": venues,
532
+ "hedge_only": hedge_only,
533
+ "min_apr": min_apr,
534
+ "max_break_h": max_break_h,
535
+ "min_oi_m": min_oi_m,
536
+ "intervals": intervals,
537
+ "sort": sort,
538
+ "sort_dir": sort_dir,
539
+ "offset": offset,
540
+ "limit": limit,
541
+ },
542
+ )
543
+ return await _request("GET", f"{RADAR_PREFIX}/funding-opps", params=params)
544
+
545
+
546
+ def main() -> None:
547
+ get_client()
548
+ mcp.run()
549
+
550
+
551
+ if __name__ == "__main__":
552
+ main()
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.5
2
+ Name: iwym-mcp
3
+ Version: 0.2.0
4
+ Summary: MCP server for iwym catalog (assets/instruments/tokens) and radar opportunity queries
5
+ Author: cyetstar
6
+ License-Expression: MIT
7
+ Keywords: assets,iwym,mcp,radar
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: httpx>=0.27.0
10
+ Requires-Dist: mcp>=1.9.0
11
+ Description-Content-Type: text/markdown
12
+
13
+ # iwym-mcp
14
+
15
+ stdio MCP server for iwym **catalog maintenance** (assets / instruments / asset_tokens) and **radar opportunity queries** (spreads / funding_opps). Wraps the operator HTTP API. Does not place orders or touch `auto_exec`.
16
+
17
+ Migrated from `mcp/iwym-assets` (Cursor key `iwym-assets` → `iwym`).
18
+
19
+ ## Requirements
20
+
21
+ - Python 3.11+
22
+ - [uv](https://docs.astral.sh/uv/)
23
+ - Running iwym API (`IWYM_API_BASE_URL`)
24
+ - Operator API token from **Settings → System → OPERATOR API** → `IWYM_OPERATOR_TOKEN`
25
+
26
+ ## Connect (Cursor)
27
+
28
+ ```json
29
+ {
30
+ "mcpServers": {
31
+ "iwym": {
32
+ "command": "uv",
33
+ "args": [
34
+ "--directory",
35
+ "/ABS/PATH/iwym-next/mcp/iwym",
36
+ "run",
37
+ "iwym-mcp"
38
+ ],
39
+ "env": {
40
+ "IWYM_API_BASE_URL": "http://127.0.0.1:8000",
41
+ "IWYM_OPERATOR_TOKEN": "paste-from-settings-system-operator-api"
42
+ }
43
+ }
44
+ }
45
+ }
46
+ ```
47
+
48
+ `IWYM_API_BASE_URL` is the API origin only (no `/api/v1` suffix).
49
+
50
+ ```bash
51
+ cd mcp/iwym
52
+ uv sync
53
+ export IWYM_API_BASE_URL=http://127.0.0.1:8000
54
+ export IWYM_OPERATOR_TOKEN=paste-from-settings-system-operator-api
55
+ uv run iwym-mcp
56
+ ```
57
+
58
+ ## Tools
59
+
60
+ ### Assets
61
+
62
+ | Tool | HTTP | Notes |
63
+ |------|------|--------|
64
+ | `list_assets` | `GET /api/v1/assets` | Flat array; includes disabled; each row has `tokens[]` |
65
+ | `get_asset` | `GET /api/v1/assets/{id}` | Includes `tokens[]` — no separate list-tokens tool |
66
+ | `catalog_diff` | `GET /api/v1/assets/catalog-diffs` | `venue` optional; `include_orphans` default false |
67
+ | `create_or_upsert_asset` | `PUT /api/v1/assets/{id}` | Tool default `enabled=false`; does not rewrite existing scalars |
68
+ | `update_asset` | `PATCH /api/v1/assets/{id}` | kind / enabled / display_symbol / oracle / anchor |
69
+ | `set_enabled` | `PATCH /api/v1/assets/{id}` | Radar whitelist toggle only |
70
+ | `soft_disable_asset` | `DELETE /api/v1/assets/{id}` | `enabled=false`; keeps row |
71
+
72
+ Asset `kind`: `spot_crypto` · `stable` · `wrapped` · `leveraged_token` · `equity`.
73
+
74
+ ### Instruments
75
+
76
+ | Tool | HTTP |
77
+ |------|------|
78
+ | `list_asset_instruments` | `GET /api/v1/assets/{id}/instruments` |
79
+ | `search_instruments` | `GET /api/v1/exchanges/instruments/search` |
80
+ | `link_instrument` | `PATCH /api/v1/exchanges/instruments/{id}/link` |
81
+ | `sync_instruments` | `POST /api/v1/exchanges/instruments/sync` (hits upstream; heavy) |
82
+
83
+ ### Tokens
84
+
85
+ | Tool | HTTP |
86
+ |------|------|
87
+ | `create_asset_token` | `POST /api/v1/assets/{id}/tokens` |
88
+ | `update_asset_token` | `PATCH /api/v1/assets/{id}/tokens/{chain}/{address}` |
89
+ | `delete_asset_token` | `DELETE …` |
90
+ | `reassign_asset_token` | `POST /api/v1/assets/tokens/reassign` |
91
+ | `migrate_asset_token` | `POST /api/v1/assets/tokens/migrate` |
92
+ | `lookup_asset_tokens` | `POST /api/v1/assets/token-lookups` |
93
+
94
+ Token write fields: `chain_key` · `address` · `symbol` · `decimals` · `status` (`trading`\|`offline`) · `enabled`.
95
+
96
+ ### Radar opportunities (read-only)
97
+
98
+ | Tool | HTTP |
99
+ |------|------|
100
+ | `list_spreads` | `GET /api/v1/radar/spreads` |
101
+ | `list_funding_opps` | `GET /api/v1/radar/funding-opps` |
102
+
103
+ Default `limit=100`, max `300`. Filters mirror the Console Radar boards (kind/mode, q, venues, sort, …).
104
+
105
+ ## Suggested catalog loop
106
+
107
+ 1. `catalog_diff(venue="binance")`.
108
+ 2. For one `missing` entry: check aliases / leverage / equity before writing.
109
+ 3. `create_or_upsert_asset(..., enabled=false)`.
110
+ 4. Add chain contracts with `create_asset_token` when needed; link CEX rows via Sync or `link_instrument`.
111
+ 5. Enable with `set_enabled` only when the human wants it on the Radar scan set.
112
+
113
+ ## Security
114
+
115
+ - Never commit `IWYM_OPERATOR_TOKEN`.
116
+ - Token has operator powers (whitelist / instruments / radar reads); not a trading key.
@@ -0,0 +1,7 @@
1
+ iwym_mcp/__init__.py,sha256=eGnQ3U00UOhOnnt7IgeFsXL2BCJM3yZMtRM1-IUFz90,106
2
+ iwym_mcp/client.py,sha256=N0g0xtMrNBnN9TkbX2RZgV2kSegfOxnEgTEoARmY__0,3195
3
+ iwym_mcp/server.py,sha256=PezCyX9xkR-i-36c_fdKH52rjEJNXFa42Zk7Io9pUP8,16405
4
+ iwym_mcp-0.2.0.dist-info/METADATA,sha256=3EOnLSXNv-CnV-_pBeKz66kb-kPxxmNk0nCplfF_xGg,4003
5
+ iwym_mcp-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ iwym_mcp-0.2.0.dist-info/entry_points.txt,sha256=Fux7N8kW0pcYNqBO58ijGXVfOkW-d6lMJIoJAzrXMic,50
7
+ iwym_mcp-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ iwym-mcp = iwym_mcp.server:main