@vike-io/cli 0.23.0 → 0.24.0
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.
- package/CHANGELOG.md +6 -0
- package/README.md +21 -8
- package/package.json +1 -1
- package/skills/vike/SKILL.md +8 -5
- package/skills/vike-daily-brief/SKILL.md +2 -2
- package/skills/vike-hl-asset-briefing/SKILL.md +1 -1
- package/skills/vike-perp-carry/SKILL.md +71 -0
- package/skills/vike-perp-crowding/SKILL.md +4 -4
- package/skills/vike-perp-funding/SKILL.md +17 -0
- package/skills/vike-perp-overview/SKILL.md +7 -6
- package/skills.sh.json +3 -2
- package/src/commands/md.js +103 -0
- package/src/commands/tool-command.js +13 -10
- package/src/index.js +2 -0
- package/src/mcp-client.js +49 -22
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.24.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 8a211f4: `marketdata` (alias `md`): CEX perp market data from the REST API `/v1/marketdata`, one GET each with the same key (not an MCP tool; `--json` prints the route's body). `md funding <symbol>` (funding history, newest first: `--exchange`, `--start`, `--end`, `--limit` up to 5000), `md funding-now [symbol]` (each venue now; no symbol: the top 5 funding-arbitrage pairs), `md spreads [symbol]`, `md oi <symbol>` and `md long-short <symbol>` (`--exchange`, `--hours` 1-168), `md liquidations [symbol]` (forced liquidations on binance, bybit, okx, deribit and aster: `--exchange`, `--side long|short`, `--start`, `--end`, `--interval 1m|5m|15m|1h|4h|1d` for long/short totals per bucket, `--limit`), `md carry` (the carry screener: `--legs all|perp_perp|perp_spot`, `--direction funding|convergence`, `--costs none|fees|fees_slippage`, `--fee-bps`, `--slippage-bps`, `--horizon <hours>` sent as `horizon_h`, `--min-spread-pct` (default 0), `--sort net|gross`, `--limit` up to 500). In the table view of `md carry` and `md funding-now`, a rate at its venue's cap or floor prints as `<rate> capped`, and the funding interval as published (`8h assumed` where the venue publishes none); `--json` keeps the raw fields. `perp funding` and `perp spreads` are unchanged (MCP). New skill `vike-perp-carry`; the `vike`, `vike-perp-funding`, `vike-perp-overview`, `vike-perp-crowding`, `vike-daily-brief` and `vike-hl-asset-briefing` skills use `md oi` / `md long-short` where they used `vike-data call perp_open_interest` / `perp_long_short`.
|
|
8
|
+
|
|
3
9
|
## 0.23.0
|
|
4
10
|
|
|
5
11
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -18,7 +18,8 @@ for the wallet and token tools. The same data is served three ways: an **MCP ser
|
|
|
18
18
|
this CLI calls), a **REST API** at `https://data.vike.io/v1/`, and the **Parquet archive** at
|
|
19
19
|
`https://data.vike.io/archive/`. A key allows 20,000 requests an hour, and an account can hold up
|
|
20
20
|
to 5 keys; archive downloads are not counted. The archive manifest and a sample market need no key
|
|
21
|
-
at all.
|
|
21
|
+
at all. Perpetual-futures market data from centralised exchanges (funding, cross-venue spreads, open
|
|
22
|
+
interest, long/short, liquidations, a carry screener) is served at `https://data.vike.io/v1/marketdata/` (`vike-data md`).
|
|
22
23
|
|
|
23
24
|
## Install
|
|
24
25
|
|
|
@@ -135,8 +136,10 @@ not only the HTTP status. A rate-limited call gets HTTP 429 with `Retry-After: 6
|
|
|
135
136
|
|
|
136
137
|
## CLI commands
|
|
137
138
|
|
|
138
|
-
Every data command is one `tools/call` to the MCP server
|
|
139
|
-
`
|
|
139
|
+
Every data command is one `tools/call` to the MCP server, except `vike-data md`: one GET of the REST
|
|
140
|
+
API `/v1/marketdata` with the same key, whose `--json` output is the route's body as served.
|
|
141
|
+
`vike-data <group> --help` lists the flags; `vike-data schema --pretty` prints every tool the server
|
|
142
|
+
exposes, with its parameters.
|
|
140
143
|
|
|
141
144
|
| Command | Subcommands | MCP tool |
|
|
142
145
|
|---|---|---|
|
|
@@ -148,6 +151,7 @@ Every data command is one `tools/call` to the MCP server. `vike-data <group> --h
|
|
|
148
151
|
| `vike-data candles` | `hl <symbol>` (Hyperliquid perp or spot, from executed fills; `--view export`, or `--view latest` for the newest bar of every symbol), `polymarket <token_id>` (one outcome token); live bars: `stream hl --channel hl.candles` | `hl_ohlcv`, `polymarket_ohlcv` |
|
|
149
152
|
| `vike-data polymarket` (`pm`) | `markets`, `market <condition_id>`, `wallet <address>`, `smart-money`, `leaderboard`, `market-trades <condition_id>`, `tape`, `orderbook <token_id>`, `market-stats <token_id>`, `settlement <condition_id>`, `settlements`, `chainlink-prices <symbol>` (the Chainlink prices the crypto up/down markets resolve on), `archive` | `polymarket_markets`, `polymarket_market_detail`, `polymarket_wallet`, `polymarket_smart_money`, `polymarket_leaderboard`, `polymarket_market_trades`, `polymarket_tape`, `polymarket_orderbook`, `polymarket_market_stats`, `polymarket_settlement`, `polymarket_settlements_bulk`, `polymarket_chainlink_prices`, `polymarket_archive` |
|
|
150
153
|
| `vike-data predictfun` (`pf`) | `overview`, `markets`, `market <market_id>`, `orderbook <market_id>`, `market-trades <market_id>`, `wallet <address>` (positions and P&L), `wallet-trades <address>`, `wallet-flows <address>` (USDT deposits and withdrawals), `leaderboard` | `predictfun_overview`, `predictfun_markets`, `predictfun_market_detail`, `predictfun_market_book`, `predictfun_market_trades`, `predictfun_wallet_positions`, `predictfun_wallet_trades`, `predictfun_leaderboard` |
|
|
154
|
+
| `vike-data marketdata` (`md`) | CEX perps: `funding <symbol>` (history, newest first: `--exchange`, `--start`, `--end`, `--limit` up to 5000), `funding-now [symbol]` (each venue now; no symbol: the top 5 funding-arbitrage pairs), `spreads [symbol]` (the 10 widest cross-venue price gaps), `oi <symbol>` and `long-short <symbol>` (`--exchange`, `--hours` 1-168 for an hourly series), `liquidations [symbol]` (forced liquidations on binance, bybit, okx, deribit and aster, newest first: `--exchange`, `--side long\|short`, `--start`, `--end`, `--interval 1m\|5m\|15m\|1h\|4h\|1d` for long/short totals per bucket, `--limit`; `coverage` says which venues undercount), `carry` (the carry screener, by default the list on vike.io/perp/carry: `--legs all\|perp_perp\|perp_spot`, `--direction funding\|convergence`, `--costs none\|fees\|fees_slippage`, `--fee-bps`, `--slippage-bps`, `--horizon <hours>`, `--min-spread-pct` (default 0), `--sort net\|gross`, `--limit` up to 500; rows carry `gross_apr` and `net_apr` as fractions, `fees_usd` and `net_usd` per $1,000 a leg, `breakeven_h`). In the table view of `carry` and `funding-now`, a rate at its venue's cap or floor prints as `<rate> capped`, and the funding interval as published (`8h assumed` where the venue publishes none); `--json` keeps the raw `capped` and `interval_src`. An undeclared parameter is a 400. | REST, not MCP: `GET /v1/marketdata/perp/funding`, `/funding/current`, `/spreads`, `/oi`, `/long-short`, `/liquidations`, `/carry` |
|
|
151
155
|
| `vike-data alerts` | `list`, `channels`, `create`, `edit`, `delete`, `events`, `resend`, `register-webhook`, `test-webhook`, `rotate-secret`: transfer alerts (a token or one wallet, on eth, bsc, base, hyperevm) Hyperliquid alerts (`--type hl_wallet`, `hl_cohort_fill`, `hl_liquidation`, `hl_cohort_bias`, `hl_liq_proximity`, `hl_wallet_orders`: one wallet's orders placed or gone, `--side`, `--events placed gone`) and Polymarket alerts (`--type pm_wallet_trade`, `pm_market_trade`, `pm_price_move`, `pm_resolution`), by email or an HTTPS webhook, HMAC-signed; at most 200 active alerts per account; `events` pages by `--cursor` while `has_more` is true (a page ends at about 2 MB) | `alerts_*` |
|
|
152
156
|
| `vike-data stream <path>` | live events from `wss://stream.vike.io/v1/stream/<path>` (`hl`, `hl-cohorts`, `onchain`, `polymarket`) as NDJSON: `--channel` (one or more), `--filter key=value`, `--cursor` | WebSocket, not MCP |
|
|
153
157
|
| `vike-data stream` | `info`, `check <channel>` (the server's validator), `events <channel>` (stored events, 3 days), `connections` (yours) | `stream_info`, `stream_check_filter`, `stream_events`, `stream_connections` |
|
|
@@ -155,6 +159,12 @@ Every data command is one `tools/call` to the MCP server. `vike-data <group> --h
|
|
|
155
159
|
| `vike-data call <tool>` | any MCP tool by name: `--args '{json}'` or `--args-file`, `--timeout`; prints the raw result | any |
|
|
156
160
|
| setup | `init`, `login`, `logout`, `whoami`, `doctor`, `schema`, `install` | — |
|
|
157
161
|
|
|
162
|
+
The `md` series (CEX perp market data, [vike.io/data/marketdata](https://vike.io/data/marketdata)): These series may
|
|
163
|
+
be published (charts, tables, screenshots, aggregated results and up to 100 rows per publication) with the credit
|
|
164
|
+
“© Vike (vike.io)”, under the same rules as the other sources: [Licensing](https://vike.io/data/licensing). Bulk
|
|
165
|
+
data and full datasets may not, and commercial use needs a written agreement. Plans and limits:
|
|
166
|
+
[Pricing](https://vike.io/pricing); an API key: [API](https://vike.io/data/api).
|
|
167
|
+
|
|
158
168
|
Output is a table on a terminal and JSON with `--json` or whenever stdout is piped. A tool that refuses its input
|
|
159
169
|
exits 1 in every mode:
|
|
160
170
|
|
|
@@ -193,7 +203,7 @@ Downloads go to `./vike-archive/`.
|
|
|
193
203
|
|
|
194
204
|
## For AI agents
|
|
195
205
|
|
|
196
|
-
This package ships **
|
|
206
|
+
This package ships **52 skill playbooks** under [`skills/`](skills/): markdown files an AI coding
|
|
197
207
|
agent loads so it knows when and how to call each command. [`skills.sh.json`](skills.sh.json) groups
|
|
198
208
|
them by domain (Quick start, Tokens, Wallets, CEX perps, Hyperliquid perps, Candles, Polymarket, Predict.fun, Alerts, Live streams). The
|
|
199
209
|
entry point is the umbrella skill `vike`, which routes a question to the specialised skill. Per-tool
|
|
@@ -222,7 +232,7 @@ block in files it does not own.
|
|
|
222
232
|
| Variable | Default | Purpose |
|
|
223
233
|
|---|---|---|
|
|
224
234
|
| `VIKE_API_KEY` | — | API key; wins over the saved config |
|
|
225
|
-
| `VIKE_MCP_URL` | `https://data.vike.io/mcp` | MCP endpoint override |
|
|
235
|
+
| `VIKE_MCP_URL` | `https://data.vike.io/mcp` | MCP endpoint override; `md` sends its REST calls to the same origin |
|
|
226
236
|
| `VIKE_NO_TELEMETRY=1` or `DO_NOT_TRACK=1` | telemetry on | Turns off anonymous usage telemetry |
|
|
227
237
|
| `VIKE_NO_UPDATE_CHECK=1` or `NO_UPDATE_NOTIFIER=1` | check on | Turns off the background npm update check |
|
|
228
238
|
|
|
@@ -238,9 +248,12 @@ The CLI is MIT, see [LICENSE](LICENSE). Everything you get from Vike through it
|
|
|
238
248
|
server, the CLI and the Parquet files) is covered by the [Terms of Service](https://vike.io/terms), section 7:
|
|
239
249
|
|
|
240
250
|
- you can research and trade your own capital, keep the data on your own machine, run private backtests,
|
|
241
|
-
and publish charts, tables, screenshots, backtest and research results and up to 100 rows per publication
|
|
242
|
-
from on-chain, Hyperliquid, Polymarket and Predict.fun data
|
|
243
|
-
|
|
251
|
+
and publish charts, tables, screenshots, backtest and research results, and up to 100 rows per publication,
|
|
252
|
+
from our on-chain, Hyperliquid, Polymarket and Predict.fun data and our CEX derivatives market data (funding
|
|
253
|
+
rates, price spreads, open interest, long/short ratios and the carry screener, from the exchanges listed on
|
|
254
|
+
[vike.io/data/marketdata](https://vike.io/data/marketdata)), credited "© Vike (vike.io)";
|
|
255
|
+
- you cannot publish bulk data or full datasets, or publish candles, trades, ticks or order books of exchanges
|
|
256
|
+
shown on the Service;
|
|
244
257
|
- commercial use (signals or a service for others, use on behalf of a company, fund or prop firm, resale)
|
|
245
258
|
needs a written agreement: info@vike.io.
|
|
246
259
|
Details: [vike.io/data/licensing](https://vike.io/data/licensing).
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "0.
|
|
6
|
+
"version": "0.24.0",
|
|
7
7
|
"description": "CLI, agent skills and MCP client for the free Vike Data API: a Polymarket full-L2 order-book archive in Parquet, Hyperliquid positions, fills and cohorts, and labelled Ethereum/BNB wallets",
|
|
8
8
|
"type": "module",
|
|
9
9
|
"main": "src/index.js",
|
package/skills/vike/SKILL.md
CHANGED
|
@@ -97,8 +97,9 @@ Pick by the question, then read the named skill for the recipe and the traps. If
|
|
|
97
97
|
| Label many addresses (up to 100) | `vike-data wallet batch` / `wallet_batch_labels` | `vike-wallet-batch` |
|
|
98
98
|
| Why is this wallet labelled X (sources) | `vike-data labels <address>` / `wallet_label_provenance` | `vike-wallet-label-provenance` |
|
|
99
99
|
| Funding rates, funding arb, one symbol across venues | `vike-data perp funding` / `perp_funding` | `vike-perp-funding` |
|
|
100
|
-
| Cross-venue price
|
|
101
|
-
|
|
|
100
|
+
| Cross-venue carry after fees and slippage (price gap plus funding, net APR, break-even); funding history of one symbol | `vike-data md carry`, `md funding <symbol>` (REST `/v1/marketdata`) | `vike-perp-carry` |
|
|
101
|
+
| Cross-venue price spread, "perp market overview"; CEX open interest or long/short of one symbol | `vike-data perp spreads` + `perp funding` + `perp top-traders`; `md oi`, `md long-short` | `vike-perp-overview` |
|
|
102
|
+
| Is X crowded: funding, open interest net of price, long/short per venue | `perp funding` + `md oi` + `md long-short` + `candles hl` | `vike-perp-crowding` |
|
|
102
103
|
| Top Hyperliquid traders; the full leaderboard | `vike-data perp top-traders` / `hl_perp_top_traders`; `vike-data hl leaderboard` | `vike-hl-top-traders` |
|
|
103
104
|
| HL share card → which wallet holds it | `vike-data perp find-position` / `hl_position_match` | `vike-hl-position-match` |
|
|
104
105
|
| One HL wallet: equity, positions, cohorts, risk, closed trades, funding, ledger, orders, liquidations | `vike-data hl wallet`, `hl wallet-trades`, `hl wallet-activity` | `vike-hl-trader-profile` |
|
|
@@ -206,10 +207,12 @@ Chains: every token and wallet tool takes `chain` = `ethereum` | `bsc` | `base`
|
|
|
206
207
|
|---|---|
|
|
207
208
|
| `perp_funding` | with `symbol`: raw per-venue `funding_rate` + `interval_h` (daily % = rate × 24 / interval_h × 100); without: up to 5 pre-ranked arb rows (`long_exchange`, `short_exchange`, `spread_daily_pct`) |
|
|
208
209
|
| `perp_spreads` | up to 10 cross-venue price-gap rows (≥ 0.5%); `symbol` only filters that global top 10, so it is often empty |
|
|
209
|
-
| `perp_open_interest` (`
|
|
210
|
-
| `perp_long_short` (`
|
|
210
|
+
| `perp_open_interest` (`md oi`) | `oi_usd` per venue (USD notional, moves with price), newest print or an hourly series (`hours` 1-168); `stale_venues` are never in a total |
|
|
211
|
+
| `perp_long_short` (`md long-short`) | `long_share`, `short_share` (fractions), `long_short_ratio` per venue, each with its `basis` (what the venue counts); about 40 major symbols |
|
|
211
212
|
|
|
212
|
-
|
|
213
|
+
Open interest and long/short: `vike-data md oi BTC --hours 24`, `md long-short BTC` (`--exchange`, `--hours` 1-168). None returns bid/ask per venue. "Spread" here is perp vs perp across venues, not spot vs perp.
|
|
214
|
+
|
|
215
|
+
`vike-data md` is the REST API `/v1/marketdata`, one GET each (`--json` is the route's body). `md funding-now [symbol]`, `md spreads [symbol]`, `md oi` and `md long-short` give the same answer as the four tools above. `md liquidations [symbol]` lists forced liquidations on binance, bybit, okx, deribit and aster, newest first. `side` is the LIQUIDATED position, `notional_usd` = price x qty. `--interval 1h` (or 1m to 1d) gives long and short totals per bucket. Read `coverage`: binance and aster publish at most one per symbol per second, so their totals undercount, and nothing exists before recording started. Two more have no tool row here: `md funding <symbol>` is the funding history, newest first (`--exchange`, `--start`, `--end`, `--limit` up to 5000), each row with `rate`, `interval_h`, `rate_8h` and `apr` (a fraction: 0.11 = 11 % a year). `md carry` is the carry screener. By default it pairs perp-perp and spot-perp legs (`--legs`), longs the lower funding rate and shorts the higher (`--direction funding`; `convergence` longs the cheaper price instead), and applies no minimum gap. Rows carry `gross_apr` and `net_apr` (fractions), `fees_usd` and `net_usd` for $1,000 a leg, and `breakeven_h`. Each leg carries `market`, `interval_src` and `capped` (the rate is at the venue's cap or floor). See `vike-perp-carry`.
|
|
213
216
|
|
|
214
217
|
### Hyperliquid
|
|
215
218
|
| Tool | Returns |
|
|
@@ -12,8 +12,8 @@ About 15 credits for all four sections; run only the ones the user wants and say
|
|
|
12
12
|
|
|
13
13
|
```bash
|
|
14
14
|
vike-data perp funding --json & # top cross-venue funding arbs (daily %, spread >= 0.3%)
|
|
15
|
-
vike-data
|
|
16
|
-
vike-data
|
|
15
|
+
vike-data md oi BTC --json & # repeat for ETH; oi_usd is USD notional
|
|
16
|
+
vike-data md long-short BTC --json & # repeat for ETH; read each venue's `basis`
|
|
17
17
|
wait
|
|
18
18
|
```
|
|
19
19
|
|
|
@@ -15,7 +15,7 @@ S=ETH
|
|
|
15
15
|
vike-data candles hl $S --interval 1h --limit 24 --json # price: 24 hourly bars
|
|
16
16
|
vike-data hl market --view hourly --symbols $S --days 7 --json # Hyperliquid close, open interest, funding rate, premium per hour
|
|
17
17
|
vike-data perp funding --symbol $S --json # funding on every venue now (normalise it yourself)
|
|
18
|
-
vike-data
|
|
18
|
+
vike-data md oi ETH --json # open interest per venue, USD notional
|
|
19
19
|
vike-data hl cohort-metrics $S --axis size --hours 1 --json # whales' long/short
|
|
20
20
|
vike-data hl cohort-metrics $S --axis pnl --hours 1 --json # profitable vs losing wallets
|
|
21
21
|
vike-data hl liquidations --view heatmap --symbol $S --bins 20 --json # where liquidations would cluster
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: vike-perp-carry
|
|
3
|
+
description: Cross-venue perp carry after costs. Long one leg on one venue and short the other on another (two perps, or spot bought against a perp shorted); each pair is scored by the funding it earns plus the price gap it captures, as gross and net APR, with fees, net dollars and break-even hours. Also the funding history that shows whether a funding gap lasts. Use when the user asks "is this funding arb worth it after fees" / "best carry trade right now" / "net APR of a cross-exchange perp trade" / "spot-perp carry" / "how long until it breaks even" / "has BTC funding on Binance been positive all week".
|
|
4
|
+
allowed-tools: Bash(vike-data:*)
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# vike-perp-carry
|
|
8
|
+
|
|
9
|
+
`vike-data md` reads the REST API `/v1/marketdata` (CEX perps, 1 credit a call). `md carry` is the carry screener, and its defaults return the list on vike.io/perp/carry. `md funding` is one symbol's funding history, for checking that a funding gap is more than one print. Pass the base asset (`BTC`, not `BTCUSDT`); venues are lower case.
|
|
10
|
+
|
|
11
|
+
## Commands
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
vike-data md carry --json # defaults: --legs all --direction funding --costs fees_slippage --horizon 48 --min-spread-pct 0 --sort net --limit 50
|
|
15
|
+
vike-data md carry --legs perp_spot --json # spot bought, perp shorted: earns the perp's funding
|
|
16
|
+
vike-data md carry --direction convergence --min-spread-pct 0.5 --json # long the cheaper price, short the dearer
|
|
17
|
+
vike-data md carry --costs fees --fee-bps 5 --horizon 24 --json
|
|
18
|
+
vike-data md funding BTC --exchange binance --start 2026-11-23 --json # one venue's settled funding since a date, newest first
|
|
19
|
+
vike-data md funding-now BTC --json # every venue's funding now
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
- `--legs`: `all` (the default), `perp_perp` (a perpetual on each of two venues) or `perp_spot` (spot bought and a perpetual shorted; spot is never shorted).
|
|
23
|
+
- `--direction`: `funding` (the default: long the lower funding rate, short the higher) or `convergence` (long the cheaper price, short the dearer).
|
|
24
|
+
- `--costs`: `none` (net equals gross), `fees` (taker fees, entry and exit on both legs) or `fees_slippage` (fees plus slippage on all four fills, the default).
|
|
25
|
+
- `--fee-bps` (0-100) replaces every venue's own taker fee. It is refused with `--costs none`.
|
|
26
|
+
- `--slippage-bps` (0-100, default 2) is accepted only with `--costs fees_slippage`.
|
|
27
|
+
- `--horizon` is the holding period in hours (1-720, sent as `horizon_h`): funding accrues over it, and both APRs are annualised from it.
|
|
28
|
+
- `--min-spread-pct` (0-25, default 0) is the smallest PRICE gap between the two legs, in percent, of either sign. It is not a funding spread.
|
|
29
|
+
- Any flag the route does not take is a 400. A refusal exits 1 with the server's message.
|
|
30
|
+
|
|
31
|
+
## Reading the answer
|
|
32
|
+
|
|
33
|
+
The envelope has `as_of` (unix seconds of the prices), the inputs as applied (`legs` and `direction` among them), `notional_usd` (1000) and `rows`. Each row has:
|
|
34
|
+
|
|
35
|
+
- `symbol`, and for `long_` and `short_`:
|
|
36
|
+
- `venue` and `market` (`perp` or `spot`), `price` (mid);
|
|
37
|
+
- `funding_rate` (one settlement), `interval_h` and `interval_src`, `rate_8h`, `apr`, `capped`, `next_funding_ts`. Every funding field is `null` on a spot leg.
|
|
38
|
+
- `spread_pct`: the short leg's price over the long leg's, in percent. It is negative when the long leg is the dearer, which is common with `--direction funding`.
|
|
39
|
+
- `funding_spread_24h_pct`: what the pair's funding earns in 24 hours.
|
|
40
|
+
- `spread_capture_usd` (the gap, captured when prices meet; negative when it costs), `net_funding_usd` (over the horizon), `fees_usd` (the costs) and `net_usd`. All are for $1,000 on EACH leg.
|
|
41
|
+
- `gross_apr` and `net_apr`, both **fractions of the capital on both legs** (0.25 = 25 % a year; 3.19 = 319 %).
|
|
42
|
+
- `breakeven_h`: hours of funding needed to pay the costs the gap does not. 0 means the gap alone pays them; `null` means funding never does.
|
|
43
|
+
- `min_leg_vol_usd`: only legs with $1M+ of 24-hour volume are listed. A pair whose perp leg has no current funding rate is left out.
|
|
44
|
+
|
|
45
|
+
What the funding-leg fields mean:
|
|
46
|
+
|
|
47
|
+
- **`capped: true`** means that leg's rate sits at its venue's published cap or floor. The real pressure may be larger, and the rate can stay pinned there. `null` means the venue publishes no cap.
|
|
48
|
+
- **`interval_src`** says where `interval_h` comes from: `venue` (the venue publishes it for the symbol), `fixed` (the venue settles hourly for every market) or `default` (nothing published, 8 h assumed). Treat a `default` leg's `rate_8h` and `apr` as an estimate.
|
|
49
|
+
- In the table view (no `--json`), a capped rate prints as `0.002 capped` and the interval as published, e.g. `4h`, or `8h assumed` for `default`. `--json` keeps the raw `capped` and `interval_src` fields.
|
|
50
|
+
|
|
51
|
+
How to read it:
|
|
52
|
+
|
|
53
|
+
- **Lead with `net_usd` for the horizon and `net_apr`, not `gross_apr`.** Say which `--legs`, `--direction`, `--costs` and `--horizon` you used.
|
|
54
|
+
- A large APR on a short horizon is mostly a one-off gap capture annualised: a 2.6 % gap over 48 hours reads as hundreds of percent a year. It is not repeatable. Quote `net_usd` per $1,000 a leg next to it.
|
|
55
|
+
- `spread_capture_usd` assumes the two prices meet within the horizon. If they do not, only `net_funding_usd` is earned, and the exit pays the costs.
|
|
56
|
+
- Funding is the rate now, not a forecast. Run `md funding <SYM> --exchange <venue>` for each perp leg and check that the sign held over recent days. In those rows `apr` is also a fraction, and `rate_8h` puts 1h, 4h and 8h venues on one scale.
|
|
57
|
+
|
|
58
|
+
## Anti-patterns
|
|
59
|
+
|
|
60
|
+
- Don't present `gross_apr` as the return, and don't read an APR fraction as percent (0.25 is 25 %, not 0.25 %).
|
|
61
|
+
- Don't compare rows fetched with different `--legs`, `--direction`, `--costs` or `--horizon`.
|
|
62
|
+
- Don't extrapolate a `capped` leg's rate, or a leg with `interval_src: default`, without saying so.
|
|
63
|
+
- Don't call a wide gap free money. Gaps above 25 % are dropped as ticker collisions, and a 2-25 % gap on a thin pair can be a different contract or a stale venue. Check `min_leg_vol_usd` and both prices.
|
|
64
|
+
- Don't treat a row as risk-free: the two legs sit on two venues, each with its own margin, liquidation and transfer risk.
|
|
65
|
+
- Don't extrapolate one funding print to a year without the history check above.
|
|
66
|
+
|
|
67
|
+
## Pairs well with
|
|
68
|
+
|
|
69
|
+
- `vike-perp-funding` for each venue's funding of one symbol and the pre-ranked funding-arbitrage list
|
|
70
|
+
- `vike-perp-overview` for the widest price gaps, open interest and long/short
|
|
71
|
+
- `vike-perp-crowding` to see whether the side you would short is crowded
|
|
@@ -6,7 +6,7 @@ allowed-tools: Bash(vike-data:*)
|
|
|
6
6
|
|
|
7
7
|
# vike-perp-crowding
|
|
8
8
|
|
|
9
|
-
Three lenses on one symbol, about 6 credits. No lens has a validated threshold: judge each against the symbol's OWN last week and report what agrees, never a score. Base asset only (`BTC`, not `BTCUSDT`). Open interest and long/short
|
|
9
|
+
Three lenses on one symbol, about 6 credits. No lens has a validated threshold: judge each against the symbol's OWN last week and report what agrees, never a score. Base asset only (`BTC`, not `BTCUSDT`). Open interest and long/short are `vike-data md oi` and `md long-short` (REST `/v1/marketdata`, the same answer as the MCP tools `perp_open_interest` and `perp_long_short`).
|
|
10
10
|
|
|
11
11
|
## Chain
|
|
12
12
|
|
|
@@ -14,13 +14,13 @@ Three lenses on one symbol, about 6 credits. No lens has a validated threshold:
|
|
|
14
14
|
S=BTC
|
|
15
15
|
vike-data perp funding --symbol $S --json # funding on every venue now
|
|
16
16
|
vike-data hl market --view hourly --symbols $S --days 7 --json # Hyperliquid funding, open interest and close per hour
|
|
17
|
-
vike-data
|
|
18
|
-
vike-data
|
|
17
|
+
vike-data md oi $S --hours 168 --json # hourly oi_usd per venue
|
|
18
|
+
vike-data md long-short $S --hours 168 --json # hourly long_short_ratio per venue, with `basis`
|
|
19
19
|
vike-data candles hl $S --interval 1h --limit 169 --json # price over the same hours, to net it out of OI
|
|
20
20
|
vike-data hl cohort-metrics $S --axis size --hours 1 --json # optional: whales on Hyperliquid
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
-
Without
|
|
23
|
+
Without `--hours` both return the newest print per venue; `--exchange binance` narrows to one venue.
|
|
24
24
|
|
|
25
25
|
## Lens 1: funding
|
|
26
26
|
|
|
@@ -41,6 +41,22 @@ annualised_pct = daily_pct × 365
|
|
|
41
41
|
|
|
42
42
|
`vol_24h_usd` is the venue's 24h perp notional: use it as the liquidity check.
|
|
43
43
|
|
|
44
|
+
### C. History, and the arb after costs
|
|
45
|
+
|
|
46
|
+
Both modes above are a snapshot. The REST API `/v1/marketdata` (`vike-data md`, one GET each) adds the history and the costs. `md funding-now` gives the same answer as `perp funding`.
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
vike-data md funding BTC --exchange bybit --start 2026-11-23 --json # settled funding since a date, newest first, one venue or all
|
|
50
|
+
vike-data md funding-now BTC --json # every venue now (no symbol: the top-5 arb list)
|
|
51
|
+
vike-data md carry --costs fees_slippage --horizon 48 --json # cross-venue pairs: gross_apr vs net_apr, breakeven_h
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`md funding` rows carry `rate` (one settlement), `interval_h`, `rate_8h` (the rate scaled to 8 hours, so 1h and 8h venues compare) and `apr` (a fraction: 0.11 = 11 % a year). `md funding-now BTC` rows carry `rate_8h` and `apr` too. Arbitrage rows (no symbol) carry `long_`/`short_` versions of the last two fields below. Two more fields on each venue's rate:
|
|
55
|
+
- `capped: true`: the rate sits at the venue's published cap or floor, so the real pressure may be larger. `null` means the venue publishes no cap.
|
|
56
|
+
- `interval_src`: `venue` (published for the symbol), `fixed` (the venue settles hourly for every market) or `default` (nothing published, 8 h assumed, so `rate_8h` and `apr` are an estimate).
|
|
57
|
+
|
|
58
|
+
The table view prints a capped rate as `0.0075 capped` and the interval as `4h`, or `8h assumed`. Whether a pair pays after fees: `vike-perp-carry`.
|
|
59
|
+
|
|
44
60
|
## Venue comparison (one symbol)
|
|
45
61
|
|
|
46
62
|
Run B, normalise, then report:
|
|
@@ -81,5 +97,6 @@ A funding arb at 0.4–1% daily is real. Anything much higher on a liquid pair i
|
|
|
81
97
|
## Pairs well with
|
|
82
98
|
|
|
83
99
|
- `vike-perp-overview` for cross-venue price gaps, open interest, long/short and the market snapshot
|
|
100
|
+
- `vike-perp-carry` for a cross-venue pair's net APR after fees and slippage, and the funding history of each leg
|
|
84
101
|
- `vike-perp-crowding` to put a funding number next to open interest and positioning; `vike-hl-asset-briefing` for one Hyperliquid symbol
|
|
85
102
|
- `vike-hl-top-traders` to see how Hyperliquid's best traders are doing
|
|
@@ -10,16 +10,16 @@ One-shot market overview for perpetuals, plus the cross-venue price-gap, open-in
|
|
|
10
10
|
|
|
11
11
|
## Open interest and long/short (one symbol, per venue)
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
`vike-data md` reads them from the REST API `/v1/marketdata` (1 credit each; the same answer as the MCP tools `perp_open_interest` and `perp_long_short`):
|
|
14
14
|
|
|
15
15
|
```bash
|
|
16
|
-
vike-data
|
|
17
|
-
vike-data
|
|
18
|
-
vike-data
|
|
19
|
-
vike-data
|
|
16
|
+
vike-data md oi BTC --json # newest print per venue
|
|
17
|
+
vike-data md oi BTC --exchange binance --hours 48 --json # hourly series, 1-168
|
|
18
|
+
vike-data md long-short ETH --json
|
|
19
|
+
vike-data md long-short ETH --exchange okx --hours 24 --json
|
|
20
20
|
```
|
|
21
21
|
|
|
22
|
-
Pass the base asset (`BTC`, not `BTCUSDT`);
|
|
22
|
+
Pass the base asset (`BTC`, not `BTCUSDT`); `--exchange` is lower case.
|
|
23
23
|
|
|
24
24
|
- **`oi_usd` is USD notional** (open contracts x mark price when polled): not a contract count, so venues add up, and it moves with price even when no position opens or closes. Venues: aster, binance, bitget, bybit, hyperliquid, kucoin, okx. A venue silent for over an hour is under `stale_venues` and NOT in `venues`: never add it into a total.
|
|
25
25
|
- **`long_share` / `short_share` are fractions of 1**; `long_short_ratio` = long / short, above 1 = long-heavy. **Each venue counts something different, named in the row's `basis`**: binance top traders by positions; okx and gate top traders by accounts; bybit all accounts. Never average across venues; compare a venue with its own history.
|
|
@@ -31,6 +31,7 @@ Pass the base asset (`BTC`, not `BTCUSDT`); `exchange` is lower case.
|
|
|
31
31
|
```bash
|
|
32
32
|
vike-data perp spreads --json # up to 10 symbols with a cross-venue price gap >= 0.5%
|
|
33
33
|
vike-data perp spreads --symbol BTC --json # the same list, filtered to one symbol
|
|
34
|
+
vike-data md spreads --json # the same answer from the REST API /v1/marketdata
|
|
34
35
|
```
|
|
35
36
|
|
|
36
37
|
Rows: `symbol`, `buy_exchange`, `buy_price`, `sell_exchange`, `sell_price`, `spread_pct`. Pre-ranked: cite the rows directly.
|
package/skills.sh.json
CHANGED
|
@@ -48,11 +48,12 @@
|
|
|
48
48
|
},
|
|
49
49
|
{
|
|
50
50
|
"title": "CEX perps",
|
|
51
|
-
"description": "Funding-rate arb and per-symbol venue comparison, cross-venue perp price gaps, open interest and long/short lean per venue,
|
|
51
|
+
"description": "Funding-rate arb and per-symbol venue comparison, cross-venue perp price gaps, open interest and long/short lean per venue, a crowding read that nets open interest against price, and funding carry after costs with the funding history.",
|
|
52
52
|
"skills": [
|
|
53
53
|
"vike-perp-funding",
|
|
54
54
|
"vike-perp-overview",
|
|
55
|
-
"vike-perp-crowding"
|
|
55
|
+
"vike-perp-crowding",
|
|
56
|
+
"vike-perp-carry"
|
|
56
57
|
]
|
|
57
58
|
},
|
|
58
59
|
{
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { addTool } from './tool-command.js';
|
|
2
|
+
|
|
3
|
+
// Each subcommand is one GET of the REST namespace /v1/marketdata (not an MCP tool): the flags are
|
|
4
|
+
// exactly its query parameters (the server refuses any other with a 400), and --json prints the
|
|
5
|
+
// route's body as served.
|
|
6
|
+
export function registerMarketdata(program) {
|
|
7
|
+
const cmd = program
|
|
8
|
+
.command('marketdata')
|
|
9
|
+
.alias('md')
|
|
10
|
+
.description('CEX perp market data from the REST API /v1/marketdata: funding history and now, spreads, open interest, long/short, liquidations, carry screener');
|
|
11
|
+
|
|
12
|
+
const P = '/v1/marketdata/perp';
|
|
13
|
+
const EXCHANGE = ['--exchange <venue>', 'Only this venue, lower case (e.g. binance); omit for every venue'];
|
|
14
|
+
const HOURS = ['--hours <n>', '1-168: an hourly series, the last print in each UTC hour; omit for the newest print per venue'];
|
|
15
|
+
|
|
16
|
+
addTool(cmd, 'funding <symbol>', {
|
|
17
|
+
path: `${P}/funding`,
|
|
18
|
+
args: ['symbol'],
|
|
19
|
+
desc: 'Funding-rate history of one perp symbol (e.g. BTC), newest first, every venue or one: rate, interval_h, rate_8h, apr, mark_price',
|
|
20
|
+
options: [
|
|
21
|
+
EXCHANGE,
|
|
22
|
+
['--start <time>', 'From this time, inclusive: ISO-8601 (2026-11-01, 2026-11-01T08:00:00Z) or unix seconds'],
|
|
23
|
+
['--end <time>', 'Before this time, exclusive; same forms as --start'],
|
|
24
|
+
['--limit <n>', 'Rows, 1-5000 (default 500)'],
|
|
25
|
+
],
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
addTool(cmd, 'funding-now [symbol]', {
|
|
29
|
+
path: `${P}/funding/current`,
|
|
30
|
+
args: ['symbol'],
|
|
31
|
+
desc: 'Current funding rate of one symbol on each venue; without a symbol, the top 5 cross-venue funding-arbitrage pairs. A rate at its venue\'s cap or floor is marked "capped"',
|
|
32
|
+
human: (r) => (Array.isArray(r) ? r.map(markLegs) : r),
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
addTool(cmd, 'spreads [symbol]', {
|
|
36
|
+
path: `${P}/spreads`,
|
|
37
|
+
args: ['symbol'],
|
|
38
|
+
desc: 'The 10 widest cross-venue price gaps (>= 0.5%): buy on one venue, sell the dearer perp; a symbol filters those 10',
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
addTool(cmd, 'oi <symbol>', {
|
|
42
|
+
path: `${P}/oi`,
|
|
43
|
+
args: ['symbol'],
|
|
44
|
+
desc: 'Open interest of one perp symbol on each venue, USD notional (stale_venues are never summed in)',
|
|
45
|
+
options: [EXCHANGE, HOURS],
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
addTool(cmd, 'long-short <symbol>', {
|
|
49
|
+
path: `${P}/long-short`,
|
|
50
|
+
args: ['symbol'],
|
|
51
|
+
desc: 'Long/short split of one perp symbol on each venue; each venue counts something different (basis): compare a venue with itself',
|
|
52
|
+
options: [EXCHANGE, HOURS],
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
addTool(cmd, 'liquidations [symbol]', {
|
|
56
|
+
path: `${P}/liquidations`,
|
|
57
|
+
args: ['symbol'],
|
|
58
|
+
desc: 'Forced liquidations on CEX perps, newest first, one row each (side = the liquidated position) or long/short totals per --interval bucket; binance and aster undercount (see coverage)',
|
|
59
|
+
options: [
|
|
60
|
+
['--exchange <venue>', 'Only this venue: binance, bybit, okx, deribit or aster; omit for every venue'],
|
|
61
|
+
['--side <s>', 'long | short: only liquidations of this position side'],
|
|
62
|
+
['--start <time>', 'From this time, inclusive: ISO-8601 or unix seconds'],
|
|
63
|
+
['--end <time>', 'Before this time, exclusive; same forms as --start'],
|
|
64
|
+
['--interval <i>', '1m | 5m | 15m | 1h | 4h | 1d: long and short totals per UTC bucket instead of one row each'],
|
|
65
|
+
['--limit <n>', 'Rows or buckets, 1-5000 (default 500)'],
|
|
66
|
+
],
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
addTool(cmd, 'carry', {
|
|
70
|
+
path: `${P}/carry`,
|
|
71
|
+
desc: 'Carry screener: long one leg, short the other on another venue; price gap plus funding over the horizon as gross_apr and net_apr (fractions), fees_usd, breakeven_h. A rate at its venue\'s cap or floor is marked "capped"',
|
|
72
|
+
options: [
|
|
73
|
+
['--legs <l>', 'all (default) | perp_perp (a perp on each venue) | perp_spot (spot bought, a perp shorted)'],
|
|
74
|
+
['--direction <d>', 'funding (default: long the lower funding rate, short the higher) | convergence (long the cheaper price, short the dearer)'],
|
|
75
|
+
['--costs <c>', 'What net_apr subtracts: none | fees | fees_slippage (default)'],
|
|
76
|
+
['--fee-bps <bps>', 'Taker fee per fill for every venue, 0-100 (default: each venue\'s own); refused with --costs none'],
|
|
77
|
+
['--slippage-bps <bps>', 'Slippage per fill, 0-100 (default 2); only with --costs fees_slippage'],
|
|
78
|
+
['--horizon <hours>', 'Hours the pair is held, 1-720 (default 48); sent as horizon_h'],
|
|
79
|
+
['--min-spread-pct <p>', 'Smallest price gap between the two legs, percent, either sign, 0-25 (default 0)'],
|
|
80
|
+
['--sort <s>', 'net (default) | gross'],
|
|
81
|
+
['--limit <n>', 'Rows, 1-500 (default 50)'],
|
|
82
|
+
],
|
|
83
|
+
names: { horizon: 'horizon_h' },
|
|
84
|
+
human: (r) => (Array.isArray(r?.rows) ? r.rows.map(markLegs) : r),
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Table view of a funding leg: "capped" after a rate at the venue's published cap or floor, and the
|
|
89
|
+
// interval as published ("8h assumed" when the venue publishes none). --json keeps the raw fields.
|
|
90
|
+
export function markLegs(row) {
|
|
91
|
+
const out = { ...row };
|
|
92
|
+
for (const p of ['', 'long_', 'short_']) {
|
|
93
|
+
const rate = [`${p}funding_rate`, `${p}daily_pct`].find((k) => k in out);
|
|
94
|
+
if (out[`${p}capped`] === true && rate) out[rate] = `${out[rate]} capped`;
|
|
95
|
+
delete out[`${p}capped`];
|
|
96
|
+
if (`${p}interval_src` in out) {
|
|
97
|
+
const h = out[`${p}interval_h`];
|
|
98
|
+
out[`${p}interval_h`] = h == null ? null : `${h}h${out[`${p}interval_src`] === 'default' ? ' assumed' : ''}`;
|
|
99
|
+
delete out[`${p}interval_src`];
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
import { callTool } from '../mcp-client.js';
|
|
2
|
-
import { emit, emitError } from '../format.js';
|
|
1
|
+
import { callTool, getRest } from '../mcp-client.js';
|
|
2
|
+
import { emit, emitError, isJsonMode } from '../format.js';
|
|
3
3
|
|
|
4
|
-
// Register `<group> <spec>` as one call to one MCP tool
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
|
|
4
|
+
// Register `<group> <spec>` as one call to one MCP tool, or with `path` one GET of that REST route
|
|
5
|
+
// (the parameters go as its query string). `args` names the tool parameters the positional
|
|
6
|
+
// arguments of `spec` fill, in order. Each flag is forwarded under its snake_case parameter name
|
|
7
|
+
// (--from-ms -> from_ms), or the name `names` gives it, and an unset flag is not sent: a view-based
|
|
8
|
+
// tool refuses a parameter its view does not take, and the server's defaults stay the defaults.
|
|
9
|
+
// Values go as typed; the server casts them and names the fix when one is wrong. `human` reshapes the
|
|
10
|
+
// answer for the table only; --json and a pipe get it as served.
|
|
11
|
+
export function addTool(group, spec, { tool, path, desc, args = [], options = [], names = {}, human }) {
|
|
10
12
|
const cmd = group.command(spec).description(desc);
|
|
11
13
|
for (const [flags, text] of options) cmd.option(flags, text);
|
|
12
14
|
cmd.option('--json', 'Emit JSON');
|
|
@@ -17,10 +19,11 @@ export function addTool(group, spec, { tool, desc, args = [], options = [] }) {
|
|
|
17
19
|
args.forEach((name, i) => { payload[name] = received[i]; });
|
|
18
20
|
for (const [key, value] of Object.entries(opts)) {
|
|
19
21
|
if (value === undefined || key === 'json') continue;
|
|
20
|
-
payload[key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)] = value;
|
|
22
|
+
payload[names[key] ?? key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)] = value;
|
|
21
23
|
}
|
|
22
24
|
try {
|
|
23
|
-
|
|
25
|
+
const result = await (path ? getRest(path, payload) : callTool(tool, payload));
|
|
26
|
+
emit(human && !isJsonMode(opts) ? human(result) : result, opts);
|
|
24
27
|
} catch (err) { emitError(err, opts); }
|
|
25
28
|
});
|
|
26
29
|
return cmd;
|
package/src/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import { registerPerp } from './commands/perp.js';
|
|
|
6
6
|
import { registerAlerts } from './commands/alerts.js';
|
|
7
7
|
import { registerPolymarket } from './commands/polymarket.js';
|
|
8
8
|
import { registerPredictfun } from './commands/predictfun.js';
|
|
9
|
+
import { registerMarketdata } from './commands/md.js';
|
|
9
10
|
import { registerLabels } from './commands/labels.js';
|
|
10
11
|
import { registerCandles } from './commands/candles.js';
|
|
11
12
|
// New wallet subcommands (counterparties, pnl-history, balances, ens) are
|
|
@@ -69,6 +70,7 @@ registerPerp(program);
|
|
|
69
70
|
registerAlerts(program);
|
|
70
71
|
registerPolymarket(program);
|
|
71
72
|
registerPredictfun(program);
|
|
73
|
+
registerMarketdata(program);
|
|
72
74
|
registerLabels(program);
|
|
73
75
|
registerCandles(program);
|
|
74
76
|
registerHl(program);
|
package/src/mcp-client.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { URL } from 'node:url';
|
|
1
2
|
import { requireApiKey, getEndpoint } from './auth.js';
|
|
2
3
|
import { readPackageVersion } from './util.js';
|
|
3
4
|
|
|
@@ -21,31 +22,12 @@ async function post(endpoint, apiKey, init) {
|
|
|
21
22
|
}
|
|
22
23
|
}
|
|
23
24
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
const endpoint = opts.endpoint ?? getEndpoint();
|
|
27
|
-
const timeoutMs = opts.timeoutMs ?? 60_000;
|
|
28
|
-
|
|
29
|
-
// argsText: the caller's own JSON object text, sent byte for byte (a 77-digit number is not rounded).
|
|
30
|
-
const envelope = JSON.stringify({ jsonrpc: '2.0', id: nextId(), method: 'tools/call' });
|
|
31
|
-
const body = `${envelope.slice(0, -1)},"params":{"name":${JSON.stringify(toolName)},`
|
|
32
|
-
+ `"arguments":${opts.argsText ?? JSON.stringify(args)}}}`;
|
|
33
|
-
|
|
25
|
+
// post() with a deadline on the response headers; a failure says which, timeout or network.
|
|
26
|
+
async function send(endpoint, apiKey, init, timeoutMs) {
|
|
34
27
|
const ctrl = new AbortController();
|
|
35
28
|
const t = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
36
|
-
|
|
37
|
-
let resp;
|
|
38
29
|
try {
|
|
39
|
-
|
|
40
|
-
method: 'POST',
|
|
41
|
-
headers: {
|
|
42
|
-
'Content-Type': 'application/json',
|
|
43
|
-
'X-API-KEY': apiKey,
|
|
44
|
-
'User-Agent': USER_AGENT,
|
|
45
|
-
},
|
|
46
|
-
body,
|
|
47
|
-
signal: ctrl.signal,
|
|
48
|
-
});
|
|
30
|
+
return await post(endpoint, apiKey, { ...init, signal: ctrl.signal });
|
|
49
31
|
} catch (err) {
|
|
50
32
|
if (err.name === 'AbortError') {
|
|
51
33
|
throw new Error(`Request timed out after ${timeoutMs}ms`);
|
|
@@ -54,6 +36,27 @@ export async function callTool(toolName, args = {}, opts = {}) {
|
|
|
54
36
|
} finally {
|
|
55
37
|
clearTimeout(t);
|
|
56
38
|
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function callTool(toolName, args = {}, opts = {}) {
|
|
42
|
+
const apiKey = opts.apiKey ?? requireApiKey();
|
|
43
|
+
const endpoint = opts.endpoint ?? getEndpoint();
|
|
44
|
+
const timeoutMs = opts.timeoutMs ?? 60_000;
|
|
45
|
+
|
|
46
|
+
// argsText: the caller's own JSON object text, sent byte for byte (a 77-digit number is not rounded).
|
|
47
|
+
const envelope = JSON.stringify({ jsonrpc: '2.0', id: nextId(), method: 'tools/call' });
|
|
48
|
+
const body = `${envelope.slice(0, -1)},"params":{"name":${JSON.stringify(toolName)},`
|
|
49
|
+
+ `"arguments":${opts.argsText ?? JSON.stringify(args)}}}`;
|
|
50
|
+
|
|
51
|
+
const resp = await send(endpoint, apiKey, {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
headers: {
|
|
54
|
+
'Content-Type': 'application/json',
|
|
55
|
+
'X-API-KEY': apiKey,
|
|
56
|
+
'User-Agent': USER_AGENT,
|
|
57
|
+
},
|
|
58
|
+
body,
|
|
59
|
+
}, timeoutMs);
|
|
57
60
|
|
|
58
61
|
const text = await resp.text();
|
|
59
62
|
let json;
|
|
@@ -79,6 +82,30 @@ export async function callTool(toolName, args = {}, opts = {}) {
|
|
|
79
82
|
return opts.raw ? content : parsed;
|
|
80
83
|
}
|
|
81
84
|
|
|
85
|
+
// GET one REST route (`/v1/...`) on the MCP endpoint's origin with the same key; an unset param is not sent.
|
|
86
|
+
export async function getRest(path, params = {}, opts = {}) {
|
|
87
|
+
const apiKey = opts.apiKey ?? requireApiKey();
|
|
88
|
+
const url = new URL(path, opts.endpoint ?? getEndpoint());
|
|
89
|
+
for (const [k, v] of Object.entries(params)) {
|
|
90
|
+
if (v !== undefined) url.searchParams.set(k, v);
|
|
91
|
+
}
|
|
92
|
+
const resp = await send(url.href, apiKey, {
|
|
93
|
+
headers: { 'X-API-KEY': apiKey, 'User-Agent': USER_AGENT },
|
|
94
|
+
}, opts.timeoutMs ?? 60_000);
|
|
95
|
+
|
|
96
|
+
const text = await resp.text();
|
|
97
|
+
let json;
|
|
98
|
+
try { json = JSON.parse(text); } catch {
|
|
99
|
+
throw new Error(`Bad response (HTTP ${resp.status}): ${text.slice(0, 200)}`);
|
|
100
|
+
}
|
|
101
|
+
if (!resp.ok) {
|
|
102
|
+
// 429 {"error": {"message"}}, 422 {"error": "<readable>"}, any other refusal {"detail": ...}
|
|
103
|
+
const e = json?.error?.message ?? json?.error ?? json?.detail ?? text.slice(0, 200);
|
|
104
|
+
throw new Error(`HTTP ${resp.status}: ${typeof e === 'string' ? e : JSON.stringify(e)}`);
|
|
105
|
+
}
|
|
106
|
+
return json;
|
|
107
|
+
}
|
|
108
|
+
|
|
82
109
|
export async function listTools(opts = {}) {
|
|
83
110
|
const apiKey = opts.apiKey ?? requireApiKey();
|
|
84
111
|
const endpoint = opts.endpoint ?? getEndpoint();
|