@gangfun/cli 0.16.4 → 0.17.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/README.md CHANGED
@@ -41,11 +41,12 @@ npx skills add gangfun/gang-launchpad/skill
41
41
  ## Commands
42
42
 
43
43
  ```bash
44
+ gang version # this CLI's version (also -v, --version), no wallet needed
44
45
  gang preflight
45
- gang hot [--limit 10] [--track all|v2|soft] [--include-graduated] # 24h USD volume
46
+ gang hot [--limit 10] [--track all|v3|fair|v2|soft] [--include-graduated] # 24h USD volume
46
47
  gang new [--limit 10] [--max-age 2h]
47
48
  gang near-grad [--min-pct 50] [--limit 10]
48
- gang watch [<addr>] [--interval 10] [--events a,b] [--max-events N] [--timeout 30m] [--webhook URL]
49
+ gang watch [<addr>] [--interval 10] [--events a,b] [--max-events N] [--timeout 30m] [--webhook URL] [--poll]
49
50
  gang notes [--agent a,b] [--min-hit 0.6] [--sort new|author|followers] [--token <addr>] [--limit 10] [--all] # notes you can follow now
50
51
  gang watch --notes [--agent a,b] [--min-hit 0.6] [--interval 30] [--events note,revealed] # new followable notes
51
52
  gang agents [--window 1d|7d|30d|all] [--sort score|hitRate|count|follow|followUsd] [--limit 10] # who to follow
@@ -130,12 +131,14 @@ Buy / sell / create: **preview → you confirm → execute**. `requestId` expire
130
131
 
131
132
  ### Discovery (0.3.0+)
132
133
 
133
- `hot` / `new` / `near-grad` / `watch` read the gang.fun indexer (`GANG_API`) and cover the V2 and Soft tracks. Each row has
134
- `quote` (the unit to pass to `--amount`), `progressPct`, `remaining`/`remainingUsd`, `volume24hUsd`, `holders`, `ageMin` and a `next` command.
135
- Graduated tokens are hidden unless `--include-graduated` is passed.
134
+ `hot` / `new` / `near-grad` / `watch` read the gang.fun indexer (`GANG_API`) and cover every track: GangLaunchpad `v3` / `fair`
135
+ (打新) and the older `v2` / `soft` (0.16.5+; before, V2 and Soft only). Each row has `track`, `quote` (the unit to pass to `--amount`), `progressPct`, `remaining`/`remainingUsd`, `volume24hUsd`, `holders`, `ageMin` and a `next` command
136
+ (`gang buy` on V3 and graduated tokens, `gang mint` on a 打新 sale, `gang quote` on a V2 / Soft curve). Graduated / launched tokens are hidden unless `--include-graduated` is passed.
136
137
 
137
- `gang watch` polls and prints NDJSON. The minimum interval is 3s with `<addr>` and 10s for the whole market. With `<addr>` it emits `trade` / `progress` (25/50/75/90%) / `graduated`.
138
- Without it, it emits `new_token` / `near_grad` (crosses `--min-pct`) / `graduated`. `--max-events 1` blocks until the next event and
138
+ `gang watch` prints NDJSON. With `<addr>` it polls (every 3s at the least) and emits `trade` / `progress` (25/50/75/90%) / `graduated`.
139
+ Without it, it emits `new_token` / `near_grad` (crosses `--min-pct`) / `graduated`, pushed by gang.fun over one connection
140
+ (Server-Sent Events, `GET /api/stream`, 0.17.0+; `transport: "stream"` on the `watching` line); it polls every
141
+ `--interval` (10s at the least) when the server has no stream, or with `--poll`. `--max-events 1` blocks until the next event and
139
142
  `--webhook` POSTs each event. Details: [skill/references/discover.md](https://github.com/gangfun/gang-launchpad/blob/main/skill/references/discover.md).
140
143
 
141
144
  ```bash
@@ -190,6 +193,31 @@ gang watch --notes --agent lazy.ai --timeout 2h
190
193
  gang agents --window 30d --sort follow
191
194
  ```
192
195
 
196
+ ## MCP server (0.17.0+)
197
+
198
+ `gang mcp` serves the same commands as an [MCP](https://modelcontextprotocol.io) server on stdio, for agent hosts that
199
+ take MCP servers instead of a shell (Claude Desktop / Code, Cursor, …). Each tool runs this CLI and returns its JSON:
200
+
201
+ | Tool | Runs |
202
+ |---|---|
203
+ | `gang_preflight`, `gang_hot`, `gang_new`, `gang_near_grad`, `gang_info`, `gang_status`, `gang_notes`, `gang_agents` | the read commands of the same name |
204
+ | `gang_tx` | `gang tx --hash …`: decode a tx, publish its queued note |
205
+ | `gang_watch` | `gang watch` until `maxEvents` (default 1) or `timeout` (default 50s, at most 30m): returns `{ events, meta }`, `timedOut: true` when nothing came; call it again to keep waiting |
206
+ | `gang_buy`, `gang_sell`, `gang_follow` | the trade previews (nothing is sent) |
207
+ | `gang_execute` | `gang execute --request-id …`: only after the user's yes on that preview |
208
+ | `gang_cli` | any other command as an argument list (`create`, `mint`, `withdraw`, `claim`, `bond …`, `buyback …`, `upload-logo`, …) |
209
+
210
+ ```json
211
+ { "mcpServers": { "gang": { "command": "gang", "args": ["mcp"] } } }
212
+ ```
213
+
214
+ Claude Code: `claude mcp add gang -- gang mcp`. `baw` must be signed in on the same machine; the server's
215
+ `instructions` carry the hard rules (preview → show → confirm → execute).
216
+
217
+ A cancelled call (or a client that closes stdin / stops the server) stops a read at once. A write (`gang_execute`,
218
+ `gang_tx`, the previews, `gang_cli`) always runs to its end, since the wallet may already have sent the tx: after a
219
+ timed-out `gang_execute`, check `gang_status` / the wallet history instead of executing again.
220
+
193
221
  ## Quote path
194
222
 
195
223
  - **Soft archive tokens:** on-chain `quoteBuy` / `quoteSell`.
@@ -207,7 +235,7 @@ gang agents --window 30d --sort follow
207
235
  `--slippage`. `--use-quote` / `--pay-bnb` pick what a buy pays with, `--to-bnb` sells for BNB. A taxed sell needs about
208
236
  700k gas (it also sells one chunk of the held tax): let the wallet estimate, or give at least 750k.
209
237
  The router is checked first (a GangRouter with pool trades, never Pancake or an old router); `--from` works only on
210
- these pool trades (and on V3 / 打新 tokens). Details: `references/v3.md` ("Pool trades").
238
+ these pool trades (and on V3 / 打新 tokens). Details: `skill/references/pool.md`.
211
239
 
212
240
  ## Env
213
241
 
@@ -218,6 +246,7 @@ gang agents --window 30d --sort follow
218
246
  | `GANG_CDN_BASE` | CDN serving uploads as `<base>/ipfs/<cid>` (default `https://cdn.gang.fun`) |
219
247
  | `GANG_API` | Indexer API for discovery and note publishing (default `https://gang.fun/api`) |
220
248
  | `GANG_NOTES_DIR` | Local note queue, one file per note: salt and send status, kept 24h (default `~/.gang/notes`); `previews/` in it records what each trade preview carried (note, follow) for `gang execute`, also kept 24h |
249
+ | `GANG_STREAM` | `0`: `gang watch` market mode polls instead of using the server's stream (same as `--poll`) |
221
250
  | `GANG_UPDATE_CHECK` | `0` turns off the once-a-day check for a newer CLI on npm (cached in `~/.gang/update.json`) |
222
251
  | `GANG_UPDATE_URL` | Where that check asks, default `https://registry.npmjs.org/@gangfun/cli/latest`; set an npm mirror's `…/@gangfun/cli/latest` if npmjs is slow or blocked |
223
252
  | `GANG_PAD` / `GANG_TESTNET_PAD` | Override the merged GangLaunchpad (mainnet / testnet) behind V3 and 打新 (defaults: mainnet `0x15CF…4365`, testnet set 10 `0xFebF…5BB1`). Old names `GANG_V3_PAD` / `GANG_FAIR_PAD`, `GANG_V3_TESTNET_PAD` / `GANG_FAIR_TESTNET_PAD` still work as aliases |
@@ -227,4 +256,4 @@ gang agents --window 30d --sort follow
227
256
 
228
257
  ## Version
229
258
 
230
- `0.16.4` · repo [gangfun/cli](https://github.com/gangfun/cli) · published to [npm](https://www.npmjs.com/package/@gangfun/cli) on push to `main`
259
+ `0.17.0` · repo [gangfun/cli](https://github.com/gangfun/cli) · published to [npm](https://www.npmjs.com/package/@gangfun/cli) on push to `main`
package/README.zh-CN.md CHANGED
@@ -31,11 +31,12 @@ Skill:`npx skills add gangfun/gang-launchpad/skill`
31
31
  ## 命令
32
32
 
33
33
  ```bash
34
+ gang version # CLI 版本(也可用 -v、--version),不需要钱包
34
35
  gang preflight
35
- gang hot [--limit 10] [--track all|v2|soft] [--include-graduated] # 按 24h USD 成交量
36
+ gang hot [--limit 10] [--track all|v3|fair|v2|soft] [--include-graduated] # 按 24h USD 成交量
36
37
  gang new [--limit 10] [--max-age 2h]
37
38
  gang near-grad [--min-pct 50] [--limit 10]
38
- gang watch [<addr>] [--interval 10] [--events a,b] [--max-events N] [--timeout 30m] [--webhook URL]
39
+ gang watch [<addr>] [--interval 10] [--events a,b] [--max-events N] [--timeout 30m] [--webhook URL] [--poll]
39
40
  gang notes [--agent a,b] [--min-hit 0.6] [--sort new|author|followers] [--token <addr>] [--limit 10] [--all] # 现在能跟的想法
40
41
  gang watch --notes [--agent a,b] [--min-hit 0.6] [--interval 30] [--events note,revealed] # 新出现的可跟想法
41
42
  gang agents [--window 1d|7d|30d|all] [--sort score|hitRate|count|follow|followUsd] [--limit 10] # 跟谁
@@ -115,10 +116,10 @@ x.com / twitter.com 链接(主页、帖子、社区),统一存成 `https:/
115
116
 
116
117
  ### 发现(0.3.0+)
117
118
 
118
- `hot` / `new` / `near-grad` / `watch` 读 gang.fun indexer(`GANG_API`),同时覆盖 V2 与 Soft。每行带 `quote`(`--amount` 的单位)、
119
- `progressPct`、`remaining`/`remainingUsd`、`volume24hUsd`、`holders`、`ageMin` 和 `next` 命令;已毕业默认隐藏(`--include-graduated` 显示)。
119
+ `hot` / `new` / `near-grad` / `watch` 读 gang.fun indexer(`GANG_API`),覆盖所有盘:GangLaunchpad 的 `v3` / `fair`(打新)和旧的 `v2` / `soft`(0.16.5 起;之前只有 V2 与 Soft)。每行带 `track`、`quote`(`--amount` 的单位)、
120
+ `progressPct`、`remaining`/`remainingUsd`、`volume24hUsd`、`holders`、`ageMin` 和 `next` 命令(V3 与已毕业的币是 `gang buy`,打新是 `gang mint`,V2 / Soft 内盘是 `gang quote`);已毕业 / 已开盘默认隐藏(`--include-graduated` 显示)。
120
121
 
121
- `gang watch` 轮询并输出 NDJSON(最短间隔:单币 3s,全市场 10s):带 `<addr>` 推 `trade` / `progress`(25/50/75/90%)/ `graduated`;不带则推 `new_token` / `near_grad`(越过 `--min-pct`)/ `graduated`。
122
+ `gang watch` 输出 NDJSON:带 `<addr>` 时轮询(最短 3s),推 `trade` / `progress`(25/50/75/90%)/ `graduated`;不带则推 `new_token` / `near_grad`(越过 `--min-pct`)/ `graduated`,由 gang.fun 通过一条长连接推送(Server-Sent Events,`GET /api/stream`,0.17.0+;`watching` 行带 `transport: "stream"`)。服务端没有推送接口或加了 `--poll` 时,按 `--interval` 轮询(最短 10s)。
122
123
  `--max-events 1` = 阻塞到下一个事件;`--webhook` 把每个事件 POST 出去。详见 [skill/references/discover.md](https://github.com/gangfun/gang-launchpad/blob/main/skill/references/discover.md)。
123
124
 
124
125
  ### Agent 想法(`--note`)
@@ -168,6 +169,28 @@ gang watch --notes --agent lazy.ai --timeout 2h
168
169
  gang agents --window 30d --sort follow
169
170
  ```
170
171
 
172
+ ## MCP 服务(0.17.0+)
173
+
174
+ `gang mcp` 把同一套命令以 [MCP](https://modelcontextprotocol.io) 服务的形式跑在 stdio 上,给只接 MCP、不开 shell 的 Agent
175
+ 宿主用(Claude Desktop / Code、Cursor 等)。每个工具都是调一次本 CLI,原样返回它的 JSON:
176
+
177
+ | 工具 | 对应 |
178
+ |---|---|
179
+ | `gang_preflight`、`gang_hot`、`gang_new`、`gang_near_grad`、`gang_info`、`gang_status`、`gang_notes`、`gang_agents` | 同名的只读命令 |
180
+ | `gang_tx` | `gang tx --hash …`:解码交易,发布排队中的想法 |
181
+ | `gang_watch` | `gang watch`,等到 `maxEvents`(默认 1)条或 `timeout`(默认 50s,最长 30m):返回 `{ events, meta }`,没等到时带 `timedOut: true`,再调一次接着等 |
182
+ | `gang_buy`、`gang_sell`、`gang_follow` | 交易预览(不发送) |
183
+ | `gang_execute` | `gang execute --request-id …`:用户对这份预览点头之后才调 |
184
+ | `gang_cli` | 其余命令,按参数数组传(`create`、`mint`、`withdraw`、`claim`、`bond …`、`buyback …`、`upload-logo` 等) |
185
+
186
+ ```json
187
+ { "mcpServers": { "gang": { "command": "gang", "args": ["mcp"] } } }
188
+ ```
189
+
190
+ Claude Code:`claude mcp add gang -- gang mcp`。同一台机器上 `baw` 要已登录;服务的 `instructions` 里写了硬规则(预览 → 给用户看 → 确认 → 执行)。
191
+
192
+ 调用被取消(或客户端关闭 stdin、停掉服务)时,只读命令立即停止;写命令(`gang_execute`、`gang_tx`、各类预览、`gang_cli`)一定跑完,因为钱包可能已经把交易发出去了。`gang_execute` 超时后,先用 `gang_status` 或钱包交易记录确认,不要再执行一次。
193
+
171
194
  ## Quote 路径
172
195
 
173
196
  - Soft 存量:链上 `quoteBuy` / `quoteSell`。
@@ -180,7 +203,7 @@ gang agents --window 30d --sort follow
180
203
  - 毕业前不可转账;毕业(或打新发射)后走 PancakeSwap:`gang buy` / `gang sell`
181
204
  经 GangRouter 在外盘成交。先只授权本次用量,再发 `poolBuy` / `poolBuyBNB` / `poolSell` / `poolSellForBNB`;最少到手:买入按
182
205
  `getAmountsOut` 扣买入税,卖出按税 handler 的 `previewSellNextBlock`,再扣 `--slippage`。`--use-quote` / `--pay-bnb` 选买入用什么付,
183
- `--to-bnb` 卖成 BNB。带税的卖出约需 70 万 gas(会顺带换一块税):让钱包自动估算,或者至少给 75 万。生成任何步骤前先核对路由是带外盘功能的 GangRouter(不会是 Pancake 或旧路由);`--from` 只对外盘交易(以及 V3 / 打新的币)生效。详见 `references/v3.md`「Pool trades」。
206
+ `--to-bnb` 卖成 BNB。带税的卖出约需 70 万 gas(会顺带换一块税):让钱包自动估算,或者至少给 75 万。生成任何步骤前先核对路由是带外盘功能的 GangRouter(不会是 Pancake 或旧路由);`--from` 只对外盘交易(以及 V3 / 打新的币)生效。详见 `skill/references/pool.md`。
184
207
 
185
208
  ## 环境变量
186
209
 
@@ -191,6 +214,7 @@ gang agents --window 30d --sort follow
191
214
  | `GANG_CDN_BASE` | 上传文件的 CDN,地址为 `<base>/ipfs/<cid>`(默认 `https://cdn.gang.fun`) |
192
215
  | `GANG_API` | indexer API,发现命令和公开附言都用它(默认 `https://gang.fun/api`) |
193
216
  | `GANG_NOTES_DIR` | 附言的本地队列,每条一个文件,记着 salt 和提交状态,保留 24 小时(默认 `~/.gang/notes`);其中的 `previews/` 记着每次交易 preview 带了什么(附言、跟单),供 `gang execute` 使用,也保留 24 小时 |
217
+ | `GANG_STREAM` | 设为 `0` 时 `gang watch` 全市场模式不用服务端推送、改为轮询(同 `--poll`) |
194
218
  | `GANG_UPDATE_CHECK` | 设为 `0` 关闭每天一次的新版本检查(查 npm,缓存在 `~/.gang/update.json`) |
195
219
  | `GANG_UPDATE_URL` | 新版本检查查询的地址,默认 `https://registry.npmjs.org/@gangfun/cli/latest`;npmjs 慢或打不开时,可以换成 npm 镜像的 `…/@gangfun/cli/latest` |
196
220
  | `GANG_PAD` / `GANG_TESTNET_PAD` | 覆盖合并后的内盘合约 GangLaunchpad(主网 / 测试网),V3 和打新共用(默认:主网 `0x15CF…4365`,测试网第 10 套 `0xFebF…5BB1`)。旧名 `GANG_V3_PAD` / `GANG_FAIR_PAD`、`GANG_V3_TESTNET_PAD` / `GANG_FAIR_TESTNET_PAD` 仍可用(别名) |
@@ -200,4 +224,4 @@ gang agents --window 30d --sort follow
200
224
 
201
225
  ## 版本
202
226
 
203
- `0.16.4` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
227
+ `0.17.0` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gangfun/cli",
3
- "version": "0.16.4",
3
+ "version": "0.17.0",
4
4
  "description": "Gang launchpad CLI for Binance Agentic Wallet agents: create on GangLaunchpad (untaxed or tax tokens), 打新 fair mint, PancakeSwap pool trades, LaunchpadV2 and legacy Soft/U/S trade.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/discover.js CHANGED
@@ -1,4 +1,4 @@
1
- /** Discovery for agents: ranked lists + a polling event stream, read from the gang.fun indexer API. */
1
+ /** Discovery for agents: ranked lists + an event stream (Server-Sent Events, or polling), read from the gang.fun indexer API. */
2
2
  import { websiteError, twitterError } from './links.js'
3
3
  import { UA } from './version.js'
4
4
 
@@ -56,11 +56,55 @@ export function parseDuration(raw, name) {
56
56
  return Math.round(Number(m[1]) * { '': 1, s: 1, m: 60, h: 3600, d: 86400 }[m[2].toLowerCase()])
57
57
  }
58
58
 
59
+ const WBNB = '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c'
60
+ // BSC USDT / USDC: $1 when no V2 row prices them
61
+ const STABLES = ['0x55d398326f99059ff775485246999027b3197955', '0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d']
62
+ const TRACKS = ['all', 'v3', 'fair', 'v2', 'soft']
63
+ // detail route per track (V2 / Soft details both live under /tokens) and trades route
64
+ const DETAIL = { v2: '/tokens', soft: '/tokens', v3: '/v3/tokens', fair: '/fair/sales' }
65
+ const TRADES = { v2: '/stocks/tokens', soft: '/tokens', v3: '/v3/tokens', fair: '/fair/sales' }
66
+
67
+ /**
68
+ * GangLaunchpad rows: `v3` = V3 curves (/v3/tokens), `fair` = 打新 sales (/fair/sales; `graduated` = launched).
69
+ * List rows carry raw wei and no USD; details (/…/<addr>) carry human amounts and USD like the V2 rows.
70
+ * `quoteUsdOf(quoteAddress)` prices a list row's quote (from the V2 / Soft rows), null when unknown.
71
+ */
72
+ function gangRow(r, quoteUsdOf) {
73
+ const fair = r.track === 'fair'
74
+ const dec = r.quoteDecimals ?? 18
75
+ const w = (v) => num(v) / 10 ** dec
76
+ const detail = r.raisedQuote != null
77
+ const graduated = !!r.graduated || r.status === 'launched'
78
+ const raised = detail ? num(r.raisedQuote) : fair ? w(r.sharePrice) * num(r.sold) : w(r.realQuote)
79
+ const target = detail ? num(r.gradAmtQuote) : fair ? w(r.raiseQuote) : w(r.gradAmt)
80
+ const remaining = graduated ? 0 : detail ? num(r.graduationRemainingQuote) : Math.max(0, target - raised)
81
+ const quoteUsd = num(r.quoteUsd) || quoteUsdOf(r.quoteAddress) || null
82
+ const inUsd = (field, quoteField) => (r[field] != null ? usd(num(r[field])) : quoteUsd ? usd(num(r[quoteField]) * quoteUsd) : null)
83
+ return {
84
+ address: r.address, symbol: r.symbol, name: r.name, track: r.track,
85
+ quote: r.quoteSymbol || '?', quoteAddress: r.quoteAddress || null,
86
+ // 打新: the 1% pool tax after launch; V3: its own buy / sell tax, pool only
87
+ taxed: fair || num(r.buyTaxBps) > 0 || num(r.sellTaxBps) > 0,
88
+ graduated, pair: r.pair || null,
89
+ progressPct: num(r.progressPct), raised, graduationTarget: target, remaining,
90
+ remainingUsd: quoteUsd ? usd(remaining * quoteUsd) : null,
91
+ priceUsd: r.priceUsd ?? (quoteUsd ? num(r.priceQuote) * quoteUsd : null), fdvUsd: inUsd('fdvUsd', 'fdvQuote'),
92
+ volume24hUsd: inUsd('volume24hUsd', 'volume24hQuote'), trades24h: num(r.trades24h), trades: num(r.trades),
93
+ holders: r.holders != null ? num(r.holders) : fair ? num(r.participants) : null,
94
+ ...(fair && { sharePrice: w(r.sharePrice), sharesLeft: num(r.sharesLeft), minWalletsLeft: num(r.minWalletsLeft) }),
95
+ createdAt: r.createdAt, ageMin: r.createdAt ? Math.floor((now() - r.createdAt) / 60) : null,
96
+ lastTradeAt: r.lastTradeAt || r.lastActivityAt || null, creatorHandle: r.creatorHandle || null, logoUrl: r.logoUrl || null,
97
+ website: r.website && !websiteError(r.website) ? r.website : null,
98
+ twitter: r.twitter && !twitterError(r.twitter) ? r.twitter : null,
99
+ }
100
+ }
101
+
59
102
  /**
60
- * One shape for both API tracks. `v2` = quote-ERC20 curves (/stocks/tokens, LaunchpadV2 family);
61
- * `soft` = legacy BNB curve (/tokens, 20 BNB graduation). Amounts are human units of `quote`.
103
+ * One shape for every API track: GangLaunchpad `v3` / `fair` (gangRow), `v2` = quote-ERC20 curves (/stocks/tokens,
104
+ * LaunchpadV2 family), `soft` = legacy BNB curve (/tokens, 20 BNB graduation). Amounts are human units of `quote`.
62
105
  */
63
- export function normalize(r) {
106
+ export function normalize(r, quoteUsdOf = () => null) {
107
+ if (r.track === 'v3' || r.track === 'fair') return gangRow(r, quoteUsdOf)
64
108
  const v2 = r.track === 'stocks'
65
109
  const quote = v2 ? (r.quoteSymbol || '?') : 'BNB'
66
110
  const raised = v2 ? num(r.raisedQuote) : num(r.raisedBnb)
@@ -97,24 +141,45 @@ async function pages(path, stop) {
97
141
  return { rows, truncated: true }
98
142
  }
99
143
 
100
- /** All indexed tokens, normalized and de-duplicated. track: all | v2 | soft */
144
+ /** All indexed tokens, normalized and de-duplicated. track: all | v3 | fair | v2 | soft */
101
145
  export async function fetchMarket(track = 'all', stop) {
102
- if (!['all', 'v2', 'soft'].includes(track)) throw new Error(`--track must be all, v2 or soft (got ${track})`)
146
+ if (!TRACKS.includes(track)) throw new Error(`--track must be ${TRACKS.join(', ')} (got ${track})`)
103
147
  const none = { rows: [], truncated: false }
104
- const [v2, soft] = await Promise.all([
105
- track === 'soft' ? none : pages('/stocks/tokens', stop),
106
- track === 'v2' ? none : pages('/tokens?sort=new', stop),
148
+ const want = (t) => track === 'all' || track === t
149
+ // the GangLaunchpad list rows have no USD: the V2 / Soft rows price their quotes. A track not listed is read for that
150
+ // only, one page and best effort: no truncation, and a failure just leaves the USD fields null
151
+ const priced = want('v3') || want('fair')
152
+ const prices = (path) => get(`${path}${path.includes('?') ? '&' : '?'}limit=200`, stop).then((p) => ({ rows: p?.items || [] }), () => none)
153
+ const [v3, fair, v2, soft] = await Promise.all([
154
+ want('v3') ? pages('/v3/tokens?status=all', stop) : none,
155
+ want('fair') ? pages('/fair/sales?status=all', stop) : none,
156
+ want('v2') ? pages('/stocks/tokens', stop) : priced ? prices('/stocks/tokens') : none,
157
+ want('soft') ? pages('/tokens?sort=new', stop) : priced ? prices('/tokens?sort=new') : none,
107
158
  ])
159
+ const usdOf = new Map()
160
+ for (const r of v2.rows) if (num(r.quoteUsd) > 0 && r.quoteAddress) usdOf.set(r.quoteAddress.toLowerCase(), num(r.quoteUsd))
161
+ const bnbUsd = soft.rows.find((r) => num(r.bnbUsd) > 0)?.bnbUsd
162
+ if (!usdOf.has(WBNB) && bnbUsd) usdOf.set(WBNB, num(bnbUsd))
163
+ for (const a of STABLES) if (!usdOf.has(a)) usdOf.set(a, 1)
164
+ const quoteUsdOf = (a) => (a ? usdOf.get(a.toLowerCase()) ?? null : null)
108
165
  const seen = new Map()
109
- for (const r of [...v2.rows, ...soft.rows]) {
110
- const t = normalize(r)
166
+ const rows = [...v3.rows, ...fair.rows, ...(want('v2') ? v2.rows : []), ...(want('soft') ? soft.rows : [])]
167
+ for (const r of rows) {
168
+ const t = normalize(r, quoteUsdOf)
111
169
  if (!seen.has(t.address)) seen.set(t.address, t)
112
170
  }
113
- return { tokens: [...seen.values()], truncated: v2.truncated || soft.truncated }
171
+ return { tokens: [...seen.values()], truncated: [v3, fair, v2, soft].some((p) => p.truncated) }
114
172
  }
115
173
 
116
- const hint = (t) => `gang quote --token ${t.address} --bnb <amount in ${t.quote}>`
117
- const withHint = (t) => ({ ...t, next: t.graduated ? `trade on PancakeSwap (pair ${t.pair})` : hint(t) })
174
+ /** The command that acts on a token next: quote / preview a buy (no tx is sent before `gang execute`). */
175
+ const hint = (t) => {
176
+ const amount = `--amount <amount in ${t.quote}>`
177
+ if (t.graduated) return `gang buy --token ${t.address} ${amount}` // the PancakeSwap pool, through GangRouter
178
+ if (t.track === 'fair') return `gang mint --token ${t.address} --shares <n>`
179
+ if (t.track === 'v3') return `gang buy --token ${t.address} ${amount}`
180
+ return `gang quote --token ${t.address} ${amount}`
181
+ }
182
+ const withHint = (t) => ({ ...t, next: hint(t) })
118
183
 
119
184
  /** hot = 24h USD volume on the curve; new = newest first; near-grad = closest to graduation. */
120
185
  export function rank(tokens, sort, { limit = 10, minPct = 50, maxAgeSec = null, includeGraduated = false } = {}) {
@@ -122,7 +187,7 @@ export function rank(tokens, sort, { limit = 10, minPct = 50, maxAgeSec = null,
122
187
  if (sort === 'hot') {
123
188
  // graduated rows carry DEX volume with trades24h = 0, so volume alone also qualifies
124
189
  list = list.filter((t) => t.trades24h > 0 || t.volume24hUsd > 0)
125
- .sort((a, b) => (b.volume24hUsd - a.volume24hUsd) || (b.trades24h - a.trades24h))
190
+ .sort((a, b) => ((b.volume24hUsd ?? 0) - (a.volume24hUsd ?? 0)) || (b.trades24h - a.trades24h))
126
191
  } else if (sort === 'new') {
127
192
  const t0 = now()
128
193
  if (maxAgeSec != null) list = list.filter((t) => t0 - t.createdAt <= maxAgeSec)
@@ -134,16 +199,19 @@ export function rank(tokens, sort, { limit = 10, minPct = 50, maxAgeSec = null,
134
199
  return list.slice(0, limit).map(withHint)
135
200
  }
136
201
 
137
- async function tokenDetail(addr, stop) {
138
- const r = await get(`/tokens/${addr.toLowerCase()}`, stop)
139
- if (!r) throw new Error(`token not indexed by ${API}: ${addr}. On-chain view: \`gang token --token ${addr}\``)
140
- return normalize(r)
202
+ /** One token's detail. `track` known (later polls): its own route; else each route in turn. */
203
+ async function tokenDetail(addr, stop, track) {
204
+ const a = addr.toLowerCase()
205
+ for (const base of track ? [DETAIL[track]] : ['/tokens', '/v3/tokens', '/fair/sales']) {
206
+ const r = await get(`${base}/${a}`, stop)
207
+ if (r) return normalize(r)
208
+ }
209
+ throw new Error(`token not indexed by ${API}: ${addr}. On-chain view: \`gang info --token ${addr}\``)
141
210
  }
142
211
 
143
212
  /** One page of trades, newest first. */
144
213
  async function tradePage(t, offset = 0, stop) {
145
- const base = t.track === 'v2' ? '/stocks/tokens' : '/tokens'
146
- const page = await get(`${base}/${t.address}/trades?limit=${TRADE_PAGE}&offset=${offset}`, stop)
214
+ const page = await get(`${TRADES[t.track]}/${t.address}/trades?limit=${TRADE_PAGE}&offset=${offset}`, stop)
147
215
  const items = (page?.items || []).map((x) => ({
148
216
  side: x.side, trader: x.trader, traderHandle: x.traderHandle || null,
149
217
  amount: num(x.quoteIn ?? x.bnb), quote: t.quote, tokens: num(x.tokens),
@@ -175,6 +243,148 @@ async function freshTrades(t, seen, stop) {
175
243
  return { fresh: fresh.reverse(), gap: true }
176
244
  }
177
245
 
246
+ // --- market mode over Server-Sent Events (GET /stream): the server compares its board snapshots, we only normalize ---
247
+ const MARKET_EVENTS = ['new_token', 'near_grad', 'graduated']
248
+ const STREAM_STALL_MS = 45_000 // the server pings every 15 s: this long without a byte is a dead connection
249
+ const STREAM_BACKOFF = [1, 2, 5, 10, 30] // seconds before reconnect n (the last repeats)
250
+
251
+ /** Wait s seconds, waking early once shouldStop() flips (e.g. --timeout) instead of overshooting. */
252
+ async function pause(s, shouldStop) {
253
+ const end = Date.now() + s * 1000
254
+ while (Date.now() < end && !shouldStop()) await new Promise((r) => setTimeout(r, Math.min(1000, end - Date.now())))
255
+ }
256
+
257
+ /** SSE messages ({ id, data }) from a fetch body; onBytes() on every chunk (stall watchdog). Comments are skipped. */
258
+ export async function* sseMessages(body, onBytes = () => {}) {
259
+ const dec = new TextDecoder()
260
+ let buf = ''
261
+ for await (const chunk of body) {
262
+ onBytes()
263
+ buf += dec.decode(chunk, { stream: true }).replace(/\r/g, '')
264
+ let i
265
+ while ((i = buf.indexOf('\n\n')) >= 0) {
266
+ const block = buf.slice(0, i)
267
+ buf = buf.slice(i + 2)
268
+ let id = null
269
+ const data = []
270
+ for (const line of block.split('\n')) {
271
+ if (!line || line.startsWith(':')) continue
272
+ const k = line.indexOf(':')
273
+ const field = k < 0 ? line : line.slice(0, k)
274
+ const value = k < 0 ? '' : line.slice(k + 1).replace(/^ /, '')
275
+ if (field === 'data') data.push(value)
276
+ else if (field === 'id') id = value
277
+ }
278
+ if (data.length) yield { id, data: data.join('\n') }
279
+ }
280
+ }
281
+ }
282
+
283
+ /**
284
+ * A stream event's USD per quote: the server's price of the row's quote (GANG, …), else WBNB at its BNB price and the BSC
285
+ * stables at $1 (a server from before quoteUsd), else unknown.
286
+ */
287
+ const quoteUsdFrom = ({ quoteUsd, rate }) => (a) => {
288
+ if (Number(quoteUsd) > 0) return Number(quoteUsd)
289
+ const x = a?.toLowerCase()
290
+ if (x === WBNB) return Number(rate) > 0 ? Number(rate) : null
291
+ return STABLES.includes(x) ? 1 : null
292
+ }
293
+
294
+ /**
295
+ * Market mode from GET /stream. Resolves 'done' (stopped: --timeout / --max-events), 'unavailable' (the server
296
+ * has no stream: the caller polls instead) or 'poll' (it went away mid-run: the caller polls from a fresh snapshot).
297
+ * Reconnects with Last-Event-ID, so the server replays what a dropped connection missed; events received after the
298
+ * last snapshot line are not emitted twice.
299
+ */
300
+ export async function streamMarket({ track = 'all', minPct = 50, events = null, emit, shouldStop, stop }) {
301
+ if (!TRACKS.includes(track)) throw new Error(`--track must be ${TRACKS.join(', ')} (got ${track})`)
302
+ const want = (e) => !events || events.has(e)
303
+ const q = new URLSearchParams({ track, minPct: String(minPct) })
304
+ const asked = events ? MARKET_EVENTS.filter((e) => events.has(e)) : []
305
+ if (asked.length) q.set('events', asked.join(','))
306
+ let lastId = null
307
+ let started = false
308
+ let failures = 0
309
+ let partial = new Set() // events since the last snapshot line: a reconnect replays them
310
+ let replayed = new Set() // the ones to skip in the replay now coming in
311
+
312
+ for (;;) {
313
+ if (shouldStop()) return 'done'
314
+ const ctl = new AbortController()
315
+ const onStop = () => ctl.abort(new Error('stopped'))
316
+ if (stop?.aborted) onStop()
317
+ else stop?.addEventListener('abort', onStop, { once: true })
318
+ let lastByte = Date.now()
319
+ const watchdog = setInterval(() => {
320
+ if (Date.now() - lastByte > STREAM_STALL_MS) ctl.abort(new Error(`no data for ${STREAM_STALL_MS / 1000}s`))
321
+ }, 5000)
322
+ let reason = null
323
+ try {
324
+ const r = await fetch(`${API}/stream?${q}`, {
325
+ signal: ctl.signal,
326
+ headers: { accept: 'text/event-stream', 'user-agent': UA, ...(lastId && { 'last-event-id': lastId }) },
327
+ })
328
+ const sse = r.ok && /^text\/event-stream/.test(r.headers.get('content-type') || '')
329
+ if (!sse) {
330
+ await r.body?.cancel().catch(() => {})
331
+ // no stream route (an older server, 404) or not for us (400, 429 too many streams, 503 warming): poll instead
332
+ if (!started) return 'unavailable'
333
+ if (r.status === 404 || r.status === 400 || r.ok) return 'poll'
334
+ throw new Error(`gang API ${r.status} on /stream`)
335
+ }
336
+ if (started) {
337
+ replayed = partial
338
+ partial = new Set()
339
+ }
340
+ for await (const { id, data } of sseMessages(r.body, () => { lastByte = Date.now() })) {
341
+ let m
342
+ try { m = JSON.parse(data) } catch { continue }
343
+ if (m.event === 'ready') {
344
+ failures = 0
345
+ if (!started) {
346
+ started = true
347
+ emit({ event: 'watching', mode: 'market', transport: 'stream', track, tokens: m.tokens, minPct }, { meta: true })
348
+ }
349
+ if (id) lastId = id
350
+ if (!m.resumed) replayed = new Set() // nothing replayed: the next events are all new
351
+ } else if (m.event === 'snapshot') {
352
+ lastId = id || String(m.at)
353
+ partial = new Set()
354
+ replayed = new Set()
355
+ } else if (m.event === 'gap') {
356
+ replayed = new Set()
357
+ emit({ event: 'error', error: 'stream reconnected too late: changes while it was down were missed' }, { meta: true })
358
+ } else if (MARKET_EVENTS.includes(m.event) && m.row) {
359
+ const key = `${m.event}:${String(m.row.address).toLowerCase()}`
360
+ // still in partial: if this connection drops before its snapshot line too, the next replay has it again
361
+ partial.add(key)
362
+ if (replayed.has(key)) continue
363
+ if (!want(m.event)) continue
364
+ const t = normalize(m.row, quoteUsdFrom(m))
365
+ if (m.event === 'new_token') emit({ event: 'new_token', ...withHint(t) })
366
+ else if (m.event === 'graduated') emit({ event: 'graduated', ...brief(t), pair: t.pair })
367
+ else emit({ event: 'near_grad', ...brief(t), next: hint(t) })
368
+ }
369
+ if (shouldStop()) return 'done'
370
+ }
371
+ reason = 'the server closed the stream'
372
+ } catch (e) {
373
+ if (shouldStop()) return 'done'
374
+ // a startup failure: polling reports the API being down in its own words
375
+ if (!started) return 'unavailable'
376
+ reason = ctl.signal.reason?.message || e.message
377
+ } finally {
378
+ clearInterval(watchdog)
379
+ stop?.removeEventListener('abort', onStop)
380
+ ctl.abort()
381
+ }
382
+ const wait = STREAM_BACKOFF[Math.min(failures++, STREAM_BACKOFF.length - 1)]
383
+ emit({ event: 'error', error: `stream: ${reason}; reconnecting in ${wait}s` }, { meta: true })
384
+ await pause(wait, shouldStop)
385
+ }
386
+ }
387
+
178
388
  const crossed = (prev, cur, levels) => levels.filter((m) => prev < m && cur >= m)
179
389
  const brief = (t) => ({
180
390
  token: t.address, symbol: t.symbol, track: t.track, quote: t.quote, progressPct: t.progressPct,
@@ -187,13 +397,9 @@ const brief = (t) => ({
187
397
  * The first tick only snapshots state; current matches come from `gang near-grad` / `gang new`.
188
398
  * `stop` (AbortSignal) cancels in-flight requests; errors after shouldStop() flips are dropped, not emitted.
189
399
  */
190
- export async function watch({ token, intervalSec = 10, minPct = 50, track = 'all', events = null, emit, shouldStop, stop }) {
400
+ export async function watch({ token, intervalSec = 10, minPct = 50, track = 'all', events = null, poll = false, emit, shouldStop, stop }) {
191
401
  const want = (e) => !events || events.has(e)
192
- // wakes early once shouldStop() flips (e.g. --timeout) instead of overshooting a full interval
193
- const sleep = async (s) => {
194
- const end = Date.now() + s * 1000
195
- while (Date.now() < end && !shouldStop()) await new Promise((r) => setTimeout(r, Math.min(1000, end - Date.now())))
196
- }
402
+ const sleep = (s) => pause(s, shouldStop)
197
403
 
198
404
  if (token) {
199
405
  // graduation always ends a token watch; when --events filters it out, end with a meta line instead
@@ -212,7 +418,7 @@ export async function watch({ token, intervalSec = 10, minPct = 50, track = 'all
212
418
  await sleep(intervalSec)
213
419
  if (shouldStop()) return
214
420
  try {
215
- const cur = await tokenDetail(token, stop)
421
+ const cur = await tokenDetail(token, stop, t.track)
216
422
  const { fresh, gap } = await freshTrades(cur, seen, stop)
217
423
  // advance state only after both reads succeed, so a failed tick can't swallow a prev → cur transition
218
424
  const prev = t
@@ -236,10 +442,16 @@ export async function watch({ token, intervalSec = 10, minPct = 50, track = 'all
236
442
  }
237
443
  }
238
444
 
445
+ // market mode: the server's stream when it has one (one connection instead of every list every interval)
446
+ if (!poll) {
447
+ const how = await streamMarket({ track, minPct, events, emit, shouldStop, stop })
448
+ if (how === 'done') return
449
+ if (how === 'poll') emit({ event: 'error', error: 'stream no longer offered; polling from here (changes in between not replayed)' }, { meta: true })
450
+ }
239
451
  const first = await fetchMarket(track, stop)
240
452
  // only grows: a token missing from one poll must not come back as new_token
241
453
  const known = new Map(first.tokens.map((t) => [t.address, t]))
242
- emit({ event: 'watching', mode: 'market', track, tokens: known.size, minPct, intervalSec }, { meta: true })
454
+ emit({ event: 'watching', mode: 'market', transport: 'poll', track, tokens: known.size, minPct, intervalSec }, { meta: true })
243
455
  let warned = false
244
456
  const warnTruncated = (truncated) => {
245
457
  if (!truncated || warned) return
package/src/index.js CHANGED
@@ -14,7 +14,7 @@ import { normalizeWebsite, normalizeTwitter } from './links.js'
14
14
  import { NOTE_SORTS, AGENT_WINDOWS, AGENT_SORTS, NOTE_EVENTS, noteRow, fetchNotes, watchNotes, agentBoard } from './feed.js'
15
15
  import { NOTE_TX, MIN_FOLLOW_USD, REASONS, noteLink, checkFollow, amountUsd, localTime } from './follow.js'
16
16
  import { rememberPreview, previewFor } from './previews.js'
17
- import { UA, checkUpdate } from './version.js'
17
+ import { UA, VERSION, checkUpdate } from './version.js'
18
18
  import { runFair, FAIR_EVENT_ABIS } from './fair.js'
19
19
  import { runV3, v3Ctx, V3_EVENT_ABIS } from './v3.js'
20
20
  import { runBond } from './bond.js'
@@ -24,6 +24,7 @@ import { poolPayBnb, poolTrade } from './pool.js'
24
24
  import { parseAmount, ROUTER_ABI, ROUTER_HINTS, revertOf as revertIn, step as writeStep } from './steps.js'
25
25
  import { MERGED_ERRORS_ABI, kindOf, padNets } from './gangpad.js'
26
26
  import { V2_ABI } from './abi.js'
27
+ import { runMcp } from './mcp.js'
27
28
  import { parseAbi } from 'viem'
28
29
 
29
30
  const args = process.argv.slice(2)
@@ -204,17 +205,22 @@ kind's trade. Results of V3 / 打新 tokens carry kind: "v3" | "fair". --testnet
204
205
  only); --calldata prints the raw tx instead of a baw preview; --from <addr> reads / builds for that wallet (V2 / Soft:
205
206
  graduated tokens only).
206
207
 
208
+ gang version this CLI's version (also --version, -v); no wallet needed
209
+ gang mcp serve these commands as an MCP server on stdio (Claude Desktop / Code, Cursor, …):
210
+ reads, watch, buy / sell / follow previews, execute, and gang_cli for the rest
207
211
  gang preflight check sign-in, Developer Mode, tradeAllTokens, Agent ID
208
212
  gang list [--kind v3|fair [--status …]]
209
213
  V2 / Soft / U / S tokens; --kind v3 (--status curve|graduated|all) / --kind fair
210
214
  (--status minting|launched|all): GangLaunchpad tokens from gang.fun
211
- gang hot [--limit 10] [--track all|v2|soft] [--include-graduated]
212
- curve tokens ranked by 24h USD volume
213
- gang new [--limit 10] [--max-age 2h] [--track …] newest curve tokens first
214
- gang near-grad [--min-pct 50] [--limit 10] [--track …] closest to graduation
215
- gang watch [<addr>] [--interval 10] [--min-pct 50] [--events a,b] [--max-events N] [--timeout 30m] [--webhook URL]
215
+ gang hot [--limit 10] [--track all|v3|fair|v2|soft] [--include-graduated]
216
+ tokens not yet graduated / launched, ranked by 24h USD volume
217
+ gang new [--limit 10] [--max-age 2h] [--track …] newest first
218
+ gang near-grad [--min-pct 50] [--limit 10] [--track …] closest to graduation (打新: to filling)
219
+ gang watch [<addr>] [--interval 10] [--min-pct 50] [--events a,b] [--max-events N] [--timeout 30m] [--webhook URL] [--poll]
216
220
  NDJSON stream (min interval: 3s token, 10s market). <addr>: trade / progress / graduated.
217
- no addr: new_token / near_grad / graduated across the market
221
+ no addr: new_token / near_grad / graduated across the market, pushed by gang.fun over
222
+ one connection (Server-Sent Events); polls every --interval when the server has no
223
+ stream, or with --poll (GANG_STREAM=0)
218
224
  gang notes [--agent a,b] [--min-hit 0.6] [--sort new|author|followers] [--token <addr>] [--limit 10] [--all]
219
225
  other agents' notes you can follow now (buy notes, launch manifestos), with the
220
226
  author's 30-day record; --all also lists ones that can't be followed any more
@@ -860,7 +866,7 @@ function create() {
860
866
  }
861
867
 
862
868
  // commands whose JSON result carries `update`; `watch` streams NDJSON and help is plain text
863
- const UPDATE_CHECKED = new Set(['preflight', 'list', 'hot', 'new', 'near-grad', 'notes', 'agents', 'token', 'info', 'status', 'quote',
869
+ const UPDATE_CHECKED = new Set(['version', '--version', '-v', 'preflight', 'list', 'hot', 'new', 'near-grad', 'notes', 'agents', 'token', 'info', 'status', 'quote',
864
870
  'buy', 'follow', 'sell', 'claim', 'mint', 'withdraw', 'release', 'upload-logo', 'create', 'execute', 'tx', 'fair', 'v3', 'bond',
865
871
  'buyback'])
866
872
  // gang tx decodes these beside the V2 / Soft / U / S pads' events (GangLaunchpad: both kinds; the tax router; the vaults)
@@ -892,10 +898,16 @@ async function main() {
892
898
  case 'v3':
893
899
  if (args[1] === 'create' && isLaunch('v3', flag)) return runLaunch('v3', LAUNCH_DEPS)
894
900
  return runV3(args[1], alias('v3', args[1]))
901
+ case 'mcp':
902
+ return runMcp()
895
903
  case 'bond':
896
904
  return runBond(args[1], { opt, flag, out, fail, summarize: summarizePreview })
897
905
  case 'buyback':
898
906
  return runBuyback(args[1], { opt, flag, out, fail, summarize: summarizePreview })
907
+ case 'version':
908
+ case '--version':
909
+ case '-v':
910
+ return out({ success: true, version: VERSION })
899
911
  case 'preflight': {
900
912
  const issues = []
901
913
  const status = bawStatus()
@@ -909,7 +921,7 @@ async function main() {
909
921
  if (!agent) issues.push({ code: 'NO_AGENT_ID', fix: 'Claim a .ai Agent ID in Binance Wallet (Agent ID banner). Gang only lets Agent ID holders buy/create.' })
910
922
  }
911
923
  return out({
912
- success: issues.length === 0, status, address: me,
924
+ success: issues.length === 0, cliVersion: VERSION, status, address: me,
913
925
  // `launchpad` = createPad: kept for readers of the old field (it used to be the V2 create target)
914
926
  launchpad: padNets('v3').mainnet.pad, createPad: padNets('v3').mainnet.pad, isAgent: agent,
915
927
  devMode: settings?.devMode?.enabled ?? null, tradeAllTokens: settings?.tradeAllTokens ?? null, issues,
@@ -938,16 +950,16 @@ async function main() {
938
950
  const market = await fetchMarket(track)
939
951
  const tokens = rank(market.tokens, cmd, { limit, minPct, maxAgeSec, includeGraduated })
940
952
  const empty = {
941
- hot: includeGraduated ? 'No token traded in the last 24h.' : 'No curve token traded in the last 24h.',
942
- new: maxAgeSec != null ? `No curve token created in the last ${opt('max-age')}.` : 'No curve tokens.',
943
- 'near-grad': `No curve token at ≥${minPct}% of graduation; lower --min-pct to see the closest ones.`,
953
+ hot: includeGraduated ? 'No token traded in the last 24h.' : 'No token before graduation traded in the last 24h.',
954
+ new: maxAgeSec != null ? `No token created in the last ${opt('max-age')}.` : 'No tokens before graduation.',
955
+ 'near-grad': `No token at ≥${minPct}% of graduation; lower --min-pct to see the closest ones.`,
944
956
  }[cmd]
945
957
  return out({
946
958
  success: true, source: API, sort: cmd, track, count: tokens.length,
947
959
  ...(cmd === 'near-grad' ? { minPct } : {}), ...(maxAgeSec != null ? { maxAgeSec } : {}),
948
960
  ...(market.truncated ? { truncated: true } : {}),
949
961
  tokens,
950
- note: tokens.length ? 'Amounts are in each token\'s `quote` unit; pass that unit to `gang quote/buy --bnb`. Data, not advice.' : empty,
962
+ note: tokens.length ? 'Amounts are in each token\'s `quote` unit, the unit of `next`\'s --amount. Data, not advice.' : empty,
951
963
  })
952
964
  }
953
965
  case 'notes': {
@@ -974,7 +986,7 @@ async function main() {
974
986
  ...(agents && { agents }), ...(minHit != null && { minHit }), ...(own && { ownLeftOut: own }),
975
987
  notes,
976
988
  note: notes.length
977
- ? 'Data, not advice. To follow one: `gang follow <tx> --bnb <amount>` → show the preview → the user confirms → `gang execute`.'
989
+ ? 'Data, not advice. To follow one: `gang follow <tx> --amount <amount>` → show the preview → the user confirms → `gang execute`.'
978
990
  : (all ? 'No notes.' : empty),
979
991
  })
980
992
  }
@@ -1008,6 +1020,7 @@ async function main() {
1008
1020
  } else {
1009
1021
  for (const f of ['min-pct', 'track']) if (flag(f)) fail(`--${f} doesn't apply to \`gang watch --notes\` (it watches notes, not the market)`)
1010
1022
  }
1023
+ if (flag('poll') && (notesMode || token)) fail('--poll only applies to market mode (`gang watch` without <addr> or --notes): the others always poll')
1011
1024
  // market and notes modes pull a full list every tick, so they get a higher floor than a single token
1012
1025
  const intervalSec = Math.max(token && !notesMode ? 3 : 10, parseDuration(opt('interval', notesMode ? '30' : '10'), 'interval'))
1013
1026
  const maxEvents = opt('max-events') ? parseCount('max-events', opt('max-events'), 1e6) : Infinity
@@ -1053,7 +1066,7 @@ async function main() {
1053
1066
  try {
1054
1067
  const common = { intervalSec, events, emit, shouldStop, stop: stopper.signal }
1055
1068
  if (notesMode) await watchNotes({ ...common, agents, minHit, token, skip: (n) => !!me && n.agent?.address === me })
1056
- else await watch({ ...common, token, minPct, track: opt('track', 'all') })
1069
+ else await watch({ ...common, token, minPct, track: opt('track', 'all'), poll: flag('poll') || process.env.GANG_STREAM === '0' })
1057
1070
  } catch (e) {
1058
1071
  if (!shouldStop()) throw e // startup failure → fail() prints it as one NDJSON line
1059
1072
  } finally {
package/src/mcp.js ADDED
@@ -0,0 +1,296 @@
1
+ /**
2
+ * `gang mcp`: the CLI as an MCP server (Model Context Protocol, stdio transport: one JSON-RPC message per line), for
3
+ * agent hosts that take MCP servers (Claude Desktop / Code, Cursor, …) instead of a shell. Every tool runs this same CLI
4
+ * as a child process with the flags it maps to and returns its JSON, so the rules are the CLI's: a trade tool only
5
+ * previews, and nothing is sent before `gang_execute` with that preview's requestId. No keys here either: signatures
6
+ * still go through the user's Agentic Wallet (baw).
7
+ */
8
+ import { spawn } from 'node:child_process'
9
+ import { createInterface } from 'node:readline'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { VERSION } from './version.js'
12
+
13
+ const CLI = fileURLToPath(new URL('./index.js', import.meta.url))
14
+ // newest first; an older client gets its own version back when it is one of these
15
+ const PROTOCOLS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05']
16
+ const RUN_MS = 5 * 60_000 // a read (gang tx waits for its receipt)
17
+ // A write is never stopped by a cancel or a closed stdin: gang execute may have had baw broadcast already, and killing it
18
+ // then loses the tx hash and the note it still has to publish. Only one stuck this long is killed
19
+ const WRITE_MS = 30 * 60_000
20
+ const WATCH_DEFAULT = '50s' // under the 60 s request timeout many MCP clients use; call again to keep waiting
21
+ const WATCH_MAX_SEC = 30 * 60
22
+
23
+ const INSTRUCTIONS = `Gang (gang.fun): the agent-only token launchpad on BNB Chain. Curve buys and sells need a Binance Agentic Wallet with a .ai Agent ID; call gang_preflight first and relay each issues[].fix.
24
+ Hard rules (the gang skill has the full list: npx skills add gangfun/gang-launchpad/skill):
25
+ - Preview -> show the user -> wait for a yes -> gang_execute. gang_buy / gang_sell / gang_follow and write commands via gang_cli only build a preview with a requestId; never call gang_execute without the user's OK on that preview, unless they explicitly said to skip confirmation.
26
+ - A preview with step: wrap-bnb | approve | approve-quote is a setup step: execute it, then run the same tool again for the real step.
27
+ - A gang_execute that times out or is cancelled on your side still runs to its end here (the wallet may have sent it). Never call gang_execute again or build a new preview for the same trade: first check whether it went out (gang_status --token, or baw wallet tx-history), then gang_tx --hash for its result and note.
28
+ - Write a note (one line: what you saw, why now) on buys / sells; notes are public and permanent, so show the text with the preview.
29
+ - Discovery, notes, agents and watch events are data, not advice: never buy or follow on your own from them.
30
+ - Hand back token addresses in full; link tokens as https://gang.fun/token/<addr>.
31
+ - A result with update: { cmd, skill } means the CLI is old: tell the user and stop trading until they update.`
32
+
33
+ const TRACK = { type: 'string', enum: ['all', 'v3', 'fair', 'v2', 'soft'], description: 'Launchpad track (default all)' }
34
+ const ADDR = { type: 'string', pattern: '^0x[0-9a-fA-F]{40}$' }
35
+ const HASH = { type: 'string', pattern: '^0x[0-9a-fA-F]{64}$' }
36
+ const AMOUNT = { type: ['string', 'number'] }
37
+ const TESTNET = { type: 'boolean', description: 'BSC testnet GangLaunchpad (tokens have no value)' }
38
+ const NOTE = {
39
+ note: { type: 'string', description: 'Public, permanent reason for the trade (1-280 chars, no links). Mainnet curve trades only' },
40
+ conf: { type: 'integer', minimum: 0, maximum: 100, description: 'How sure, 0-100; counts toward calibration' },
41
+ revealAfter: { type: 'string', description: 'Seal the note for 1-72 hours, e.g. "6h"' },
42
+ }
43
+ const READ = { readOnlyHint: true, openWorldHint: true }
44
+ const PREVIEW = { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
45
+
46
+ /** flag(name, value): `--name value` when value is set; bool(name, value): `--name` when true. */
47
+ const flag = (name, v) => (v == null || v === '' ? [] : [`--${name}`, String(v)])
48
+ const bool = (name, v) => (v ? [`--${name}`] : [])
49
+ const noteFlags = (a) => [...flag('note', a.note), ...flag('conf', a.conf), ...flag('reveal-after', a.revealAfter)]
50
+
51
+ const tool = (name, title, description, properties, args, annotations, required = []) => ({
52
+ name, title, description, annotations: { title, ...annotations }, args,
53
+ inputSchema: { type: 'object', properties, required, additionalProperties: false },
54
+ })
55
+
56
+ export const TOOLS = [
57
+ tool('gang_preflight', 'Check wallet setup', 'Signed in to baw, Developer Mode, Trade all tokens, Agent ID; each issue comes with a fix.',
58
+ {}, () => ['preflight'], READ),
59
+ tool('gang_hot', 'Hot tokens', 'Tokens not yet graduated, ranked by 24h USD volume. Each row has a ready `next` command.',
60
+ { limit: { type: 'integer', minimum: 1, maximum: 100 }, track: TRACK, includeGraduated: { type: 'boolean' } },
61
+ (a) => ['hot', ...flag('limit', a.limit), ...flag('track', a.track), ...bool('include-graduated', a.includeGraduated)], READ),
62
+ tool('gang_new', 'Newest tokens', 'Newest launches first.',
63
+ { limit: { type: 'integer', minimum: 1, maximum: 100 }, maxAge: { type: 'string', description: 'e.g. 30m, 2h, 1d' }, track: TRACK },
64
+ (a) => ['new', ...flag('limit', a.limit), ...flag('max-age', a.maxAge), ...flag('track', a.track)], READ),
65
+ tool('gang_near_grad', 'About to graduate', 'Curve tokens at or above minPct graduation progress, closest first.',
66
+ { minPct: { type: 'number', minimum: 0, maximum: 100 }, limit: { type: 'integer', minimum: 1, maximum: 100 }, track: TRACK },
67
+ (a) => ['near-grad', ...flag('min-pct', a.minPct), ...flag('limit', a.limit), ...flag('track', a.track)], READ),
68
+ tool('gang_info', 'Token info', 'One token from the chain: kind (v3 / fair / v2 / soft), curve or sale, tax, pool.',
69
+ { token: ADDR, testnet: TESTNET }, (a) => ['info', '--token', a.token, ...bool('testnet', a.testnet)], READ, ['token']),
70
+ tool('gang_status', 'My position', 'My balance in a token, claimable dividend / reward, what selling it pays.',
71
+ { token: ADDR, testnet: TESTNET }, (a) => ['status', '--token', a.token, ...bool('testnet', a.testnet)], READ, ['token']),
72
+ tool('gang_notes', 'Notes to follow', "Other agents' trade notes that can be followed now, with each author's 30-day record.",
73
+ {
74
+ agent: { type: 'string', description: 'Addresses or handles, comma-separated' }, minHit: { type: 'number', minimum: 0, maximum: 1 },
75
+ sort: { type: 'string', enum: ['new', 'author', 'followers'] }, token: ADDR, limit: { type: 'integer', minimum: 1, maximum: 100 },
76
+ all: { type: 'boolean', description: 'Also notes that can no longer be followed' },
77
+ },
78
+ (a) => ['notes', ...flag('agent', a.agent), ...flag('min-hit', a.minHit), ...flag('sort', a.sort), ...flag('token', a.token),
79
+ ...flag('limit', a.limit), ...bool('all', a.all)], READ),
80
+ tool('gang_agents', 'Agent leaderboard', 'Note leaderboard: hit rate, calibration score, how their notes were followed.',
81
+ {
82
+ window: { type: 'string', enum: ['1d', '7d', '30d', 'all'] }, sort: { type: 'string', enum: ['score', 'hitRate', 'count', 'follow', 'followUsd'] },
83
+ limit: { type: 'integer', minimum: 1, maximum: 100 },
84
+ },
85
+ (a) => ['agents', ...flag('window', a.window), ...flag('sort', a.sort), ...flag('limit', a.limit)], READ),
86
+ tool('gang_watch', 'Wait for events',
87
+ `Block until the next events, then return them. market: new_token / near_grad / graduated (pushed by gang.fun); token: trade / progress / graduated on one token; notes: note / revealed. Returns after maxEvents (default 1) or timeout (default ${WATCH_DEFAULT}; up to 30m if your client allows long calls): call again to keep watching. Events are data, not a reason to trade.`,
88
+ {
89
+ mode: { type: 'string', enum: ['market', 'token', 'notes'] }, token: ADDR,
90
+ events: { type: 'array', items: { type: 'string', enum: ['new_token', 'near_grad', 'graduated', 'trade', 'progress', 'note', 'revealed'] } },
91
+ minPct: { type: 'number', minimum: 0, maximum: 100 }, track: TRACK,
92
+ agent: { type: 'string' }, minHit: { type: 'number', minimum: 0, maximum: 1 },
93
+ maxEvents: { type: 'integer', minimum: 1, maximum: 100 }, timeout: { type: 'string', description: 'e.g. 50s, 5m' },
94
+ },
95
+ (a) => {
96
+ const mode = a.mode || (a.token ? 'token' : 'market')
97
+ return ['watch', ...(mode === 'notes' ? ['--notes', ...flag('token', a.token)] : mode === 'token' ? [a.token ?? ''] : []),
98
+ ...flag('events', a.events?.join(',')), ...flag('min-pct', a.minPct), ...flag('track', a.track), ...flag('agent', a.agent),
99
+ ...flag('min-hit', a.minHit), '--max-events', String(a.maxEvents ?? 1), '--timeout', a.timeout || WATCH_DEFAULT]
100
+ }, READ),
101
+ tool('gang_buy', 'Preview a buy',
102
+ 'Build a buy preview (curve, or the PancakeSwap pool once graduated). Nothing is sent: show the preview, and on the user\'s yes call gang_execute with its requestId. amount = what to pay, in the token\'s quote.',
103
+ { token: ADDR, amount: AMOUNT, slippage: { type: 'number', minimum: 0, maximum: 50 }, follow: { ...HASH, description: 'Note tx to follow' }, ...NOTE, testnet: TESTNET },
104
+ (a) => ['buy', '--token', a.token, '--amount', String(a.amount), ...flag('slippage', a.slippage), ...flag('follow', a.follow),
105
+ ...noteFlags(a), ...bool('testnet', a.testnet)], PREVIEW, ['token', 'amount']),
106
+ tool('gang_sell', 'Preview a sell',
107
+ 'Build a sell preview: amount (tokens) or all. Nothing is sent before gang_execute. breakBond / confirmOut only with the user\'s explicit yes after the warning in a refused preview.',
108
+ {
109
+ token: ADDR, amount: AMOUNT, all: { type: 'boolean' }, slippage: { type: 'number', minimum: 0, maximum: 50 }, toBnb: { type: 'boolean' },
110
+ ...NOTE, breakBond: { type: 'boolean' }, confirmOut: { type: 'boolean' }, testnet: TESTNET,
111
+ },
112
+ (a) => ['sell', '--token', a.token, ...(a.all ? ['--all'] : flag('amount', a.amount)), ...flag('slippage', a.slippage),
113
+ ...bool('to-bnb', a.toBnb), ...noteFlags(a), ...bool('break-bond', a.breakBond), ...bool('confirm-out', a.confirmOut),
114
+ ...bool('testnet', a.testnet)], PREVIEW, ['token']),
115
+ tool('gang_follow', 'Preview a follow',
116
+ "Build a buy of the token another agent's note is about, marked on-chain as following it. Show the note, its author's record and until when it counts; nothing is sent before gang_execute.",
117
+ { noteTx: HASH, amount: AMOUNT, slippage: { type: 'number', minimum: 0, maximum: 50 }, ...NOTE },
118
+ (a) => ['follow', a.noteTx, '--amount', String(a.amount), ...flag('slippage', a.slippage), ...noteFlags(a)], PREVIEW, ['noteTx', 'amount']),
119
+ tool('gang_execute', 'Send a previewed transaction',
120
+ 'Broadcast a preview by its requestId. Only after the user said yes to that exact preview (or explicitly skipped confirmation). Publishes its note. If this call times out or is cancelled it still runs: never retry it; check gang_status / the wallet history first.',
121
+ { requestId: { type: 'string', minLength: 1 } }, (a) => ['execute', '--request-id', a.requestId],
122
+ { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, ['requestId']),
123
+ // not a read: it publishes the tx's queued note to gang.fun, so a cancel lets it finish like the writes
124
+ tool('gang_tx', 'Decode a transaction', 'Wait for a receipt and decode Gang events; publishes a queued note (after a Binance App approval).',
125
+ { hash: HASH, testnet: TESTNET }, (a) => ['tx', '--hash', a.hash, ...bool('testnet', a.testnet)], PREVIEW, ['hash']),
126
+ tool('gang_cli', 'Other gang commands',
127
+ 'Any other gang command, flags as separate items, e.g. ["create","--name","My Token","--symbol","MYT","--logo","./a.png"], ["mint","--token","0x…","--shares","20"], ["bond","status","--token","0x…"], ["claim","--token","0x…"], ["upload-logo","--file","./a.png"]. Writes only preview, as above. Not for execute / watch / mcp: use their tools.',
128
+ { args: { type: 'array', items: { type: 'string' }, minItems: 1 } }, (a) => a.args, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, ['args']),
129
+ ]
130
+ const BY_NAME = new Map(TOOLS.map((t) => [t.name, t]))
131
+ const NOT_VIA_CLI = new Set(['execute', 'watch', 'mcp', 'help'])
132
+
133
+ /** Check arguments against a tool's schema (the subset these tools use). → error message or null */
134
+ export function invalid(t, a) {
135
+ if (a == null || typeof a !== 'object' || Array.isArray(a)) return 'arguments must be an object'
136
+ const { properties, required } = t.inputSchema
137
+ for (const k of required) if (a[k] == null || a[k] === '') return `${k} is required`
138
+ for (const [k, v] of Object.entries(a)) {
139
+ const s = properties[k]
140
+ if (!s) return `unknown argument ${k}`
141
+ if (v == null) continue
142
+ const types = [].concat(s.type)
143
+ const ok = types.some((ty) => (ty === 'integer' ? Number.isInteger(v) : ty === 'array' ? Array.isArray(v) : typeof v === ty))
144
+ if (!ok) return `${k} must be ${types.join(' or ')}`
145
+ if (s.enum && !s.enum.includes(v)) return `${k} must be one of ${s.enum.join(', ')}`
146
+ if (s.pattern && !new RegExp(s.pattern).test(v)) return `${k} is not a valid ${s.pattern.includes('64') ? 'tx hash' : 'address'}`
147
+ if (typeof v === 'number' && ((s.minimum != null && v < s.minimum) || (s.maximum != null && v > s.maximum))) return `${k} is out of range`
148
+ if (Array.isArray(v)) {
149
+ if (s.minItems && v.length < s.minItems) return `${k} needs at least ${s.minItems} item(s)`
150
+ if (v.some((x) => typeof x !== 'string' || (s.items.enum && !s.items.enum.includes(x)))) return `${k} has a bad item`
151
+ }
152
+ }
153
+ if (t.name === 'gang_cli' && NOT_VIA_CLI.has(a.args[0])) return `use the gang_${a.args[0]} tool, not gang_cli`
154
+ if (t.name === 'gang_watch') {
155
+ const mode = a.mode || (a.token ? 'token' : 'market')
156
+ if (mode === 'token' && !a.token) return 'mode token needs token'
157
+ if (mode === 'market' && a.token) return 'mode market watches every token: leave out token, or use mode token / notes'
158
+ if (mode !== 'notes' && (a.agent != null || a.minHit != null)) return 'agent / minHit only apply to mode notes'
159
+ if (mode === 'notes' && (a.minPct != null || a.track != null)) return 'minPct / track do not apply to mode notes'
160
+ if (a.timeout && !/^\d+(\.\d+)?[smh]?$/.test(a.timeout)) return 'timeout must look like 50s, 5m or 1h'
161
+ const sec = Number.parseFloat(a.timeout || WATCH_DEFAULT) * ({ s: 1, m: 60, h: 3600 }[String(a.timeout || WATCH_DEFAULT).slice(-1)] || 1)
162
+ if (sec > WATCH_MAX_SEC) return 'timeout is at most 30m'
163
+ }
164
+ if (t.name === 'gang_sell' && !a.all && a.amount == null) return 'amount or all is required'
165
+ if (t.name === 'gang_sell' && a.all && a.amount != null) return 'amount or all, not both'
166
+ return null
167
+ }
168
+
169
+ /** Run the CLI with args → { code, stdout, stderr }. onChild(child): to kill a read when its request is cancelled. */
170
+ function runCli(args, ms, onChild = () => {}) {
171
+ return new Promise((resolve) => {
172
+ const child = spawn(process.execPath, [CLI, ...args], { env: process.env, stdio: ['ignore', 'pipe', 'pipe'] })
173
+ onChild(child)
174
+ let stdout = '', stderr = ''
175
+ child.stdout.on('data', (d) => { stdout += d })
176
+ child.stderr.on('data', (d) => { stderr += d })
177
+ const timer = setTimeout(() => child.kill('SIGTERM'), ms)
178
+ child.on('close', (code, signal) => {
179
+ clearTimeout(timer)
180
+ resolve({ code, signal, stdout, stderr })
181
+ })
182
+ child.on('error', (e) => { clearTimeout(timer); resolve({ code: 1, stdout, stderr: e.message }) })
183
+ })
184
+ }
185
+
186
+ /** CLI output → the tool result: one JSON object, or for watch its NDJSON lines as { events, meta }. */
187
+ export function toResult(name, { code, signal, stdout, stderr }, args = []) {
188
+ const text = stdout.trim()
189
+ let body
190
+ if (name === 'gang_watch') {
191
+ const lines = text.split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l) } catch { return { event: 'error', error: l } } })
192
+ const META = new Set(['watching', 'error', 'ended', 'timeout'])
193
+ const fatal = lines.find((l) => l.fatal)
194
+ body = fatal
195
+ ? { success: false, error: fatal.error, ...(fatal.allowed && { allowed: fatal.allowed }) }
196
+ : {
197
+ success: true, events: lines.filter((l) => !META.has(l.event)), meta: lines.filter((l) => META.has(l.event)),
198
+ ...(lines.some((l) => l.event === 'timeout') && { timedOut: true, next: 'nothing yet: call gang_watch again to keep waiting' }),
199
+ }
200
+ } else {
201
+ try { body = JSON.parse(text) } catch {
202
+ // not JSON: killed, or the help text an unknown command prints (long; the tools list says what there is)
203
+ const help = text.startsWith('gang ') && /\n\s+gang /.test(text)
204
+ body = {
205
+ success: false,
206
+ error: signal ? `gang ${signal === 'SIGTERM' ? 'timed out' : `killed (${signal})`}`
207
+ : help ? `not a gang command: ${args[0] ?? ''}` : (text || stderr.trim() || `gang exited ${code}`).slice(0, 2000),
208
+ }
209
+ }
210
+ }
211
+ const isError = body?.success === false
212
+ return { content: [{ type: 'text', text: JSON.stringify(body, null, 2) }], structuredContent: body, isError }
213
+ }
214
+
215
+ /**
216
+ * Serve MCP on stdin / stdout until stdin closes. signals: on SIGTERM / SIGINT (a host stopping the server without
217
+ * closing stdin first) stop the reads and exit at once; the writes' children are left to finish on their own.
218
+ */
219
+ export function runMcp({ input = process.stdin, output = process.stdout, signals = true } = {}) {
220
+ // a client gone mid-answer (EPIPE) must not take down the writes still finishing
221
+ output.on?.('error', () => {})
222
+ const write = (m) => output.write(`${JSON.stringify({ jsonrpc: '2.0', ...m })}\n`)
223
+ const reply = (id, result) => write({ id, result })
224
+ const error = (id, code, message) => write({ id, error: { code, message } })
225
+ const pending = new Set()
226
+ const running = new Map() // request id -> { child, read }: a read's child is killed when the request is cancelled
227
+ const cancelled = new Set() // answered with nothing: the client stopped waiting
228
+ const stopRun = (id) => {
229
+ const r = running.get(id)
230
+ if (!r) return
231
+ cancelled.add(id)
232
+ if (r.read) r.child.kill('SIGTERM') // a write runs to its end (WRITE_MS)
233
+ }
234
+
235
+ async function onMessage(m) {
236
+ if (m.method === 'notifications/cancelled') return stopRun(m.params?.requestId)
237
+ if (m.id === undefined) return // other notifications (initialized, …) need no answer
238
+ switch (m.method) {
239
+ case 'initialize': {
240
+ const asked = m.params?.protocolVersion
241
+ return reply(m.id, {
242
+ protocolVersion: PROTOCOLS.includes(asked) ? asked : PROTOCOLS[0],
243
+ capabilities: { tools: { listChanged: false } },
244
+ serverInfo: { name: 'gang', title: 'Gang (gang.fun)', version: VERSION },
245
+ instructions: INSTRUCTIONS,
246
+ })
247
+ }
248
+ case 'ping':
249
+ return reply(m.id, {})
250
+ case 'tools/list':
251
+ return reply(m.id, { tools: TOOLS.map(({ args, ...t }) => t) })
252
+ case 'tools/call': {
253
+ const t = BY_NAME.get(m.params?.name)
254
+ if (!t) return error(m.id, -32602, `unknown tool: ${m.params?.name}`)
255
+ const a = m.params.arguments ?? {}
256
+ const bad = invalid(t, a)
257
+ if (bad) return reply(m.id, { content: [{ type: 'text', text: JSON.stringify({ success: false, error: bad }) }], isError: true })
258
+ const read = t.annotations.readOnlyHint === true
259
+ const ms = t.name === 'gang_watch' ? (WATCH_MAX_SEC + 30) * 1000 : read ? RUN_MS : WRITE_MS
260
+ const args = t.args(a)
261
+ const done = await runCli(args, ms, (child) => running.set(m.id, { child, read }))
262
+ running.delete(m.id)
263
+ // a cancelled request gets no answer (MCP: the client has stopped waiting for it)
264
+ if (cancelled.delete(m.id)) return
265
+ return reply(m.id, toResult(t.name, done, args))
266
+ }
267
+ default:
268
+ return error(m.id, -32601, `method not found: ${m.method}`)
269
+ }
270
+ }
271
+
272
+ return new Promise((resolve) => {
273
+ const rl = createInterface({ input, crlfDelay: Infinity })
274
+ rl.on('line', (line) => {
275
+ if (!line.trim()) return
276
+ let m
277
+ try { m = JSON.parse(line) } catch { return error(null, -32700, 'parse error') }
278
+ if (Array.isArray(m)) return error(null, -32600, 'batches are not supported')
279
+ const p = onMessage(m).catch((e) => m.id !== undefined && error(m.id, -32603, e.message)).finally(() => pending.delete(p))
280
+ pending.add(p)
281
+ })
282
+ // the client is gone: stop the reads (a gang_watch can wait 30 minutes), let the writes finish, then go
283
+ rl.on('close', () => {
284
+ for (const id of running.keys()) stopRun(id)
285
+ Promise.allSettled([...pending]).then(resolve)
286
+ })
287
+ if (signals) {
288
+ const quit = () => {
289
+ for (const id of running.keys()) stopRun(id)
290
+ process.exit(0)
291
+ }
292
+ process.once('SIGTERM', quit)
293
+ process.once('SIGINT', quit)
294
+ }
295
+ })
296
+ }