taoswap-mcp 0.4.1 → 0.5.1

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
@@ -1,10 +1,10 @@
1
1
  # taoswap-mcp
2
2
 
3
- MCP server for the [Taoswap API](https://api.taoswap.org/llms.txt): free Bittensor data for AI assistants and coding agents, with no API key. Ask about subnets, alpha prices, validators and their yields, metagraphs, a coldkey's portfolio, PnL and ledger, or recent trades; every answer states the exact API URL it called, so the assistant can then write your code against the API directly. Ask it to stake, trade, set a limit order or send TAO, and it prepares a taoswap.org link that you open, review and sign in your own wallet: it never sees a key and never signs.
3
+ MCP server for the [Taoswap API](https://api.taoswap.org/llms.txt): free Bittensor data for AI assistants and coding agents, with no API key. Ask about subnets, alpha prices, validators and their yields, metagraphs, a coldkey's portfolio, PnL and ledger, or recent trades; every answer states the exact API URL it called, so the assistant can then write your code against the API directly. Ask it to stake, trade, set a limit order or send TAO, and it prepares a taoswap.org link that you open, review and sign in your own wallet: it never sees a key and never signs. A trade also comes back as an unsigned chain call with a price limit, for a wallet on your own machine such as btcli or [`taoswap-signer`](https://www.npmjs.com/package/taoswap-signer).
4
4
 
5
5
  ```sh
6
6
  npx -y taoswap-mcp@latest # follows releases
7
- npx -y taoswap-mcp@0.4.1 # pins this version
7
+ npx -y taoswap-mcp@0.5.1 # pins this version
8
8
  ```
9
9
 
10
10
  It speaks MCP over stdio, or over Streamable HTTP with `--http` (see [Remote (HTTP)](#remote-http)), and needs Node 20.3 or later. The package ships an `npm-shrinkwrap.json`, so `npx` installs exactly the dependency tree reviewed for that version: `@modelcontextprotocol/server`, its `@modelcontextprotocol/core`, `zod` and the [`taoswap`](https://www.npmjs.com/package/taoswap) client, which has no dependency. Pin the version where you want to review each update.
@@ -77,10 +77,10 @@ All tools are read-only and call `https://api.taoswap.org` only; the four `prepa
77
77
  | `get_network_stats` | How the network's TAO splits between root, pools and free balances | `GET /network-stats/` |
78
78
  | `list_api_operations` | Every GET operation, or one with its parameters and each field's unit | the bundled schema, no request |
79
79
  | `call_api` | Any other GET operation of the schema, on the pinned host | the path you pass |
80
- | `prepare_trade` | A taoswap.org link to stake, unstake or swap between subnets | the subnets and validators, to check |
80
+ | `prepare_trade` | A taoswap.org link to stake, unstake or swap between subnets, and the same trade as an unsigned chain call with a price limit | the subnets and validators, to check |
81
81
  | `prepare_limit_order` | A taoswap.org link to place a limit buy, take-profit or stop-loss | `GET /v2/subnets/{netuid}/`, to check |
82
82
  | `prepare_transfer` | A taoswap.org link to send TAO | no request |
83
- | `prepare_new_wallet` | The taoswap.org link that creates a wallet in the user's browser | no request |
83
+ | `prepare_new_wallet` | The taoswap.org link that creates a wallet in the user's browser, and the ways to create one on their machine | no request |
84
84
 
85
85
  The named tools call operations Taoswap keeps stable, with at least 180 days of notice before a removal. Large lists (`/v2/subnets/` is about 160 KB compressed) are cut down here with `fields`, `sort_by` and `max_items`, and the answer says so, since the API itself returns the whole list. A field or a `sort_by` that no row has is an error listing the fields the rows carry, and an argument a tool does not take is refused before any request. Answers stay under 40,000 characters, their URL and notes included; set `TAOSWAP_MCP_MAX_CHARS` to change that, 2,000 at least.
86
86
 
@@ -101,6 +101,27 @@ The `prepare_` tools never take or return a seed phrase, a private key or a pass
101
101
 
102
102
  Amounts are in the sold asset: TAO to stake or to buy with a limit order, alpha of the sold subnet to unstake, swap or sell. A trade's hotkey names the validator to stake to, or the position sold: on a swap between subnets, the position on the subnet sold, and the app picks the validator on the subnet bought. A stake's hotkey must be a validator of the subnet bought. A position can outlive its validator's permit or registration, so on an unstake or a swap a hotkey missing from the sold subnet's validators is reported in `checks` and the text, not refused: taoswap.org checks that the user holds a position with it. A limit order names no validator. A trade's estimate follows taoswap.org's own swap math on the subnet's price and pool reserves as the API last read them, the pool fee taken off the input; a limit order's says whether it takes profit or stops a loss, how far the limit sits from the price, and whether the price already meets it. Both are indicative: the app shows the live quote, slippage and fees before the user signs.
103
103
 
104
+ ### Without the web
105
+
106
+ `prepare_trade` also returns the trade as `call`, the unsigned call of the chain's `SubtensorModule`, for a Bittensor wallet on the user's machine. The Bittensor SDK or polkadot.js signs it as written. btcli and the [`taoswap-signer`](https://github.com/kusanagi-ventures/taoswap-sdk/tree/main/packages/signer) server, which keeps a wallet locally and trades under caps the user sets, place the same trade from its figures. The text tells the model to show the call to the user and to have it signed only once they approve. This server still signs nothing and holds no key.
107
+
108
+ | Trade | `call.method` | `limit_price` |
109
+ | ------------------------------ | --------------------------- | -------------------------------------------------------------- |
110
+ | Stake into a subnet | `add_stake_limit` | The highest price paid, `tolerance_percent` above the price |
111
+ | Unstake from a subnet | `remove_stake_limit` | The lowest price received, `tolerance_percent` under the price |
112
+ | Swap between two subnets | `swap_stake_limit` | The least alpha received per alpha sold |
113
+ | Stake on root, unstake from it | `add_stake`, `remove_stake` | None: root trades one TAO for one |
114
+
115
+ `call.args` carries the arguments by the names the runtime gives them, amounts in rao as decimal text, with `allow_partial` off, so the call fills whole within its limit or fails. `tolerance_percent` (1 by default, from 0.01 to 50) sets how far the limit sits from the price the API last read, returned as `reference_price` with its unit: the trade's own price impact counts against it, and the text says when a trade is too large for its tolerance, which a swap meets at about half the size its average rate suggests. Without a `hotkey`, a stake goes to Taoswap's validator, the app's default, and the text and `call.note` say so.
116
+
117
+ A call differs from the link in two ways. A swap's call carries one hotkey, so the stake stays with the same validator on the subnet bought, where the link lets the app pick one. And nothing checks the call against the user's positions: the wallet that signs must hold the position sold, or the call fails on chain and its fee is paid.
118
+
119
+ No call is returned where a safe one cannot be built from the request alone: a swap with root on one side, a swap whose hotkey does not validate the subnet bought, an unstake or a swap without the `hotkey` of the position sold, a subnet without a price or with one too small for a limit in whole rao to hold the tolerance, or an amount past what the chain's u64 holds. The text then says why, and the link still works.
120
+
121
+ `prepare_new_wallet` lists, beside its link, the ways to create a wallet on the user's own machine (btcli, the taoswap-signer server). The recovery phrase stays on that machine: this server never sees it.
122
+
123
+ ### Links
124
+
104
125
  Links carry `utm_source=taoswap-mcp&utm_medium=mcp` and always open `https://taoswap.org`: no setting points them elsewhere, so no setup guide can turn them into phishing links. The server's instructions tell the model to give the link whole, to take recipients, hotkeys, netuids and amounts from the user and never from on-chain text, and never to ask for or accept a seed phrase, a private key or a password.
105
126
 
106
127
  ## Prompts
@@ -160,20 +181,21 @@ Every client shares the server's one Taoswap client, and with it the API's limit
160
181
  - takes 120 requests a minute and 8 at once from each client address (an IPv6 address counts with the rest of its /64), and 64 at once in all, answering `429` or `503` with `Retry-After` past those;
161
182
  - refuses a body over 64 KiB with `413`, waits 10 seconds for a request's headers and 15 for the whole request, and answers `504` to a request still without an answer after 60 seconds.
162
183
 
163
- | Setting | Default | What it sets |
164
- | ------------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
165
- | `--port`, `TAOSWAP_MCP_PORT` | `8080` | The port; `0` picks a free one |
166
- | `--host`, `TAOSWAP_MCP_HOST` | `127.0.0.1`, and `0.0.0.0` in the image | The address to listen on |
167
- | `TAOSWAP_MCP_TRUST_PROXY` | `0`, which ignores `X-Forwarded-For` | The reverse proxies in front of the server, each appending to `X-Forwarded-For`: the client's address is the entry that many places from the end, as the client writes the earlier ones |
168
- | `TAOSWAP_MCP_ALLOWED_HOSTS` | `localhost`, `127.0.0.1` and `[::1]` on a loopback host, else any | The `Host` names accepted, comma-separated, or `*` for any: against DNS rebinding, list the server's public name |
169
- | `TAOSWAP_MCP_ALLOWED_ORIGINS` | `localhost`, `127.0.0.1` and `[::1]` | The browser `Origin` names accepted; a request without `Origin`, as clients other than browsers send, passes |
170
- | `TAOSWAP_MCP_RATE_PER_IP` | `120` | Requests a minute per client address, which may all come at once |
171
- | `TAOSWAP_MCP_CONCURRENT_PER_IP` | `8` | Requests at once per client address |
172
- | `TAOSWAP_MCP_CONCURRENT` | `64` | Requests at once in all |
173
- | `TAOSWAP_MCP_TIMEOUT` | `60` | Seconds before a request still without an answer gets a `504` |
174
- | `TAOSWAP_MCP_MAX_QUEUE` | `40` | Requests to the API that may wait their turn, 60 at most, so that each starts within its 20-second timeout |
175
- | `TAOSWAP_MCP_CACHE_MB` | `64` | Megabytes of API answers kept in memory, 2,000 answers at most |
176
- | `TAOSWAP_MCP_METRICS` | `0` | `1` serves Prometheus counters at `GET /metrics`: requests by method and status, conversations started (`initialize` or `server/discover`) by client name, tool calls by outcome and duration, and the API requests answered from the cache, joined, sent or refused as busy. Keep that path private: forward `/mcp` alone through the proxy |
184
+ | Setting | Default | What it sets |
185
+ | ------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
186
+ | `--port`, `TAOSWAP_MCP_PORT` | `8080` | The port; `0` picks a free one |
187
+ | `--host`, `TAOSWAP_MCP_HOST` | `127.0.0.1`, and `0.0.0.0` in the image | The address to listen on |
188
+ | `TAOSWAP_MCP_TRUST_PROXY` | `0`, which ignores `X-Forwarded-For` | The reverse proxies in front of the server, each appending to `X-Forwarded-For`: the client's address is the entry that many places from the end, as the client writes the earlier ones |
189
+ | `TAOSWAP_MCP_ALLOWED_HOSTS` | `localhost`, `127.0.0.1` and `[::1]` on a loopback host, else any | The `Host` names accepted, comma-separated, or `*` for any: against DNS rebinding, list the server's public name |
190
+ | `TAOSWAP_MCP_ALLOWED_ORIGINS` | `localhost`, `127.0.0.1` and `[::1]` | The browser `Origin` names accepted; a request without `Origin`, as clients other than browsers send, passes |
191
+ | `TAOSWAP_MCP_RATE_PER_IP` | `120` | Requests a minute per client address, which may all come at once |
192
+ | `TAOSWAP_MCP_CONCURRENT_PER_IP` | `8` | Requests at once per client address |
193
+ | `TAOSWAP_MCP_CONCURRENT` | `64` | Requests at once in all |
194
+ | `TAOSWAP_MCP_TIMEOUT` | `60` | Seconds before a request still without an answer gets a `504` |
195
+ | `TAOSWAP_MCP_MAX_QUEUE` | `40` | Requests to the API that may wait their turn, 60 at most, so that each starts within its 20-second timeout |
196
+ | `TAOSWAP_MCP_CACHE_MB` | `64` | Megabytes of API answers kept in memory, 2,000 answers at most |
197
+ | `TAOSWAP_MCP_METRICS` | `0` | `1` serves Prometheus counters at `GET /metrics`: requests by method and status, conversations started (`initialize` or `server/discover`) by client name, tool calls by outcome and duration, the tool calls each client asks for, and the API requests answered from the cache, joined, sent or refused as busy. Keep that path private: forward `/mcp` alone through the proxy |
198
+ | `TAOSWAP_MCP_METRICS_CLIENTS` | none | Client names, comma-separated, counted like `anthropic`, `claude-ai`, `claude-code`, `codex-mcp-client` and `openai-mcp`: under their own label from the start, at zero, so that a rate shows their first conversation, together with the names that add a suffix to them (`Anthropic/ClaudeAI` counts as `anthropic`). Of the other names, the first 32 seen get a label and the rest count as `other`: name your own bot here. A tool call counts for the name its request carries, else for the one its address last gave |
177
199
 
178
200
  `TAOSWAP_MCP_MAX_CHARS` applies too, and `taoswap-mcp --help` lists them all. A value out of range stops the server with a message and exit code 2. A platform such as claude.ai calls from addresses of its own, so one address may carry many of its users: raise the per-address limits for those.
179
201
 
package/dist/actions.d.ts CHANGED
@@ -17,6 +17,7 @@ export interface Prepared {
17
17
  url: string;
18
18
  action: Record<string, unknown>;
19
19
  estimate?: Record<string, unknown>;
20
+ call?: Record<string, unknown>;
20
21
  checks: Check[];
21
22
  };
22
23
  text: string;
package/dist/actions.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { limitOrderLink, TaoswapError, tradeLink, transferLink, walletCreationLink } from "taoswap";
2
2
  import { z } from "zod";
3
- import { estimateLimit, estimateTrade } from "./estimate.js";
3
+ import { callLine, DEFAULT_TOLERANCE_PERCENT, tradeCall } from "./call.js";
4
+ import { estimateLimit, estimateTrade, priceMovePercent } from "./estimate.js";
4
5
  import { addressProblem } from "./ss58.js";
5
6
  /** A check an action failed: the tool answers with the reason as an error, and prepares no link. */
6
7
  export class ActionRefused extends Error {
@@ -11,10 +12,26 @@ const SUBNET_QUERY = { omit: "neurons,conviction,hyperparameters" };
11
12
  const VALIDATOR_QUERY = { page_size: 500 };
12
13
  const APP_SHOWS = "The app shows the live quote, slippage and fees before the user signs.";
13
14
  const OPEN = "Link for the user to open, review and sign in their own wallet";
15
+ const SIGNERS = "the Bittensor SDK or polkadot.js signs it as written, btcli and the taoswap-signer server place the same trade from its figures";
16
+ const HOUSE = "No hotkey was named: the call stakes with Taoswap's validator (Kusanagi), the app's default.";
17
+ /** Wallets a user creates on their own machine, where the recovery phrase stays. */
18
+ const LOCAL_WALLETS = [
19
+ { with: "btcli", how: "the user runs `btcli wallet create` in their own terminal" },
20
+ {
21
+ with: "taoswap-signer",
22
+ how: "an MCP server the user adds with `npx -y taoswap-signer@latest`, whose create_wallet keeps the phrase in a file and returns the address alone",
23
+ },
24
+ ];
14
25
  const asset = z.union([z.literal("tao"), z.number().int().min(0).max(65535)]);
15
26
  const decimalInput = z.union([z.number(), z.string()]);
16
27
  const checks = z.array(z.object({ check: z.string(), url: z.string().optional() }));
17
- const output = (action, estimate) => z.object({ url: z.string(), action, ...(estimate ? { estimate: estimate.optional() } : {}), checks });
28
+ const output = (action, estimate, call) => z.object({
29
+ url: z.string(),
30
+ action,
31
+ ...(estimate ? { estimate: estimate.optional() } : {}),
32
+ ...(call ? { call: call.optional() } : {}),
33
+ checks,
34
+ });
18
35
  const unitOf = (side) => (side === "tao" ? "TAO" : side === 0 ? "TAO staked on root" : `alpha of subnet ${side}`);
19
36
  const round = (value) => Number(value.toPrecision(6));
20
37
  const percent = (value) => `${Number(value.toPrecision(3))}%`;
@@ -54,11 +71,7 @@ async function readSubnet(client, netuid) {
54
71
  const pool = price !== undefined && tao !== undefined && alpha !== undefined ? { price, tao, alpha } : undefined;
55
72
  return { price, pool, check: { check: `subnet ${netuid} exists`, url } };
56
73
  }
57
- /**
58
- * A stake's hotkey must be among the validators of the subnet bought. A position sold can outlive its validator's permit or
59
- * registration, and taoswap.org refuses a hotkey that holds none, so an unstake or a swap only reports one missing from the list.
60
- */
61
- async function checkValidator(client, netuid, hotkey, stake) {
74
+ async function validates(client, netuid, hotkey) {
62
75
  const url = client.url(`/v2/subnets/${netuid}/validators/`, VALIDATOR_QUERY);
63
76
  const listed = await refusingMissingSubnet(netuid, url, async () => {
64
77
  const rows = client.paginate("/v2/subnets/{netuid}/validators/", { path: { netuid }, query: VALIDATOR_QUERY }, { maxPages: 4 });
@@ -67,6 +80,14 @@ async function checkValidator(client, netuid, hotkey, stake) {
67
80
  return true;
68
81
  return false;
69
82
  });
83
+ return { listed, url };
84
+ }
85
+ /**
86
+ * A stake's hotkey must be among the validators of the subnet bought. A position sold can outlive its validator's permit or
87
+ * registration, and taoswap.org refuses a hotkey that holds none, so an unstake or a swap only reports one missing from the list.
88
+ */
89
+ async function checkValidator(client, netuid, hotkey, stake) {
90
+ const { listed, url } = await validates(client, netuid, hotkey);
70
91
  if (!listed && stake)
71
92
  throw new ActionRefused(`hotkey ${hotkey} is not a validator of subnet ${netuid} (GET ${url}). Ask the user for a validator listed there, or leave hotkey out to let the app pick. No link was prepared.`);
72
93
  const check = listed
@@ -78,7 +99,7 @@ const prepareTrade = {
78
99
  name: "prepare_trade",
79
100
  title: "Prepare a trade",
80
101
  operations: ["/v2/subnets/{netuid}/", "/v2/subnets/{netuid}/validators/"],
81
- description: 'Prepares a stake, an unstake or a swap between two subnets as a taoswap.org link that the user opens, reviews and signs in their own wallet; it signs and sends nothing. sell "tao" and buy a netuid stakes, sell a netuid and buy "tao" unstakes, two netuids swap; root is netuid 0, which the link writes root. The amount is in the sold asset. The hotkey names the validator to stake to on a stake, else the position sold: on a swap, the position on the subnet sold, the app picking the validator on the subnet bought. Checks that each subnet exists and, on a stake, that the hotkey is a validator of the subnet bought; on an unstake or a swap, a hotkey missing from the validators of the subnet sold is reported, not refused, since taoswap.org checks that the user holds a position with it. Then estimates what the trade receives from the subnet\'s price and pool reserves; the app shows the live quote.',
102
+ description: `Prepares a stake, an unstake or a swap between two subnets as a taoswap.org link that the user opens, reviews and signs in their own wallet; it signs and sends nothing. sell "tao" and buy a netuid stakes, sell a netuid and buy "tao" unstakes, two netuids swap; root is netuid 0, which the link writes root. The amount is in the sold asset. The hotkey names the validator to stake to on a stake, else the position sold: on a swap, the position on the subnet sold, the app picking the validator on the subnet bought. Checks that each subnet exists and, on a stake, that the hotkey is a validator of the subnet bought; on an unstake or a swap, a hotkey missing from the validators of the subnet sold is reported, not refused, since taoswap.org checks that the user holds a position with it. Then estimates what the trade receives from the subnet's price and pool reserves; the app shows the live quote. For a user whose Bittensor wallet is on the machine the assistant runs on, the answer also carries \`call\`, the same trade as an unsigned chain call with a price limit: ${SIGNERS}, once the user has seen the call and approves. A swap's call leaves the stake with the same validator on the subnet bought, so it comes only where that hotkey validates there too. This server signs nothing and takes no key.`,
82
103
  input: z.strictObject({
83
104
  sell: asset.describe('What the user pays: "tao" for free TAO, or the netuid whose alpha they sell (0 for TAO staked on root).'),
84
105
  buy: asset.describe('What the user gets: "tao" for free TAO, or the netuid whose alpha they buy (0 for TAO staked on root).'),
@@ -86,7 +107,13 @@ const prepareTrade = {
86
107
  hotkey: z
87
108
  .string()
88
109
  .optional()
89
- .describe("The validator's SS58 hotkey. On a stake, the one to stake to; on an unstake or a swap, the one whose position on the sold subnet is sold, and on a swap the app picks the validator on the bought subnet. Leave it out to let the app pick its preferred validator or the largest position."),
110
+ .describe("The validator's SS58 hotkey. On a stake, the one to stake to; on an unstake or a swap, the one whose position on the sold subnet is sold, and on a swap the app picks the validator on the bought subnet. Leave it out to let the app pick its preferred validator or the largest position: `call` then stakes with Taoswap's validator, and needs the hotkey to unstake or to swap."),
111
+ tolerance_percent: z
112
+ .number()
113
+ .min(0.01)
114
+ .max(50)
115
+ .optional()
116
+ .describe(`For \`call\` only: how far, in percent, the price may sit from the API's last price before the call fails rather than fill, the trade's own price impact included. ${DEFAULT_TOLERANCE_PERCENT} by default. The link leaves slippage to the app.`),
90
117
  }),
91
118
  output: output(z.object({
92
119
  type: z.enum(["stake", "unstake", "swap"]),
@@ -102,9 +129,17 @@ const prepareTrade = {
102
129
  fee_percent: z.number(),
103
130
  prices: z.record(z.string(), z.number()),
104
131
  note: z.string(),
132
+ }), z.object({
133
+ pallet: z.literal("SubtensorModule"),
134
+ method: z.enum(["add_stake", "add_stake_limit", "remove_stake", "remove_stake_limit", "swap_stake_limit"]),
135
+ args: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])),
136
+ tolerance_percent: z.number().optional(),
137
+ reference_price: z.number().optional(),
138
+ reference_price_unit: z.string().optional(),
139
+ note: z.string(),
105
140
  })),
106
141
  async run(args, { client }) {
107
- const { sell, buy, amount, hotkey } = args;
142
+ const { sell, buy, amount, hotkey, tolerance_percent } = args;
108
143
  const url = linkOrRefuse(() => tradeLink({ sell, buy, amount, ...(hotkey === undefined ? {} : { hotkey }) }, { utm: UTM }));
109
144
  const linkAmount = new URL(url).searchParams.get("amount") ?? "";
110
145
  const type = sell === "tao" ? "stake" : buy === "tao" ? "unstake" : "swap";
@@ -112,11 +147,20 @@ const prepareTrade = {
112
147
  const netuids = [sell, buy].filter((side) => side !== "tao");
113
148
  // The hotkey names the validator staked to on a stake, and the position sold otherwise.
114
149
  const hotkeyNetuid = type === "stake" ? buy : sell;
115
- const [subnets, validator] = await Promise.all([
150
+ const [subnets, validator, kept] = await Promise.all([
116
151
  Promise.all(netuids.map((netuid) => readSubnet(client, netuid))),
117
152
  hotkey === undefined || typeof hotkeyNetuid !== "number" ? undefined : checkValidator(client, hotkeyNetuid, hotkey, type === "stake"),
153
+ // swap_stake_limit carries one hotkey: the call leaves the stake with it on the subnet bought, where it must validate too.
154
+ hotkey !== undefined && typeof sell === "number" && typeof buy === "number" && sell > 0 && buy > 0
155
+ ? validates(client, buy, hotkey)
156
+ : undefined,
118
157
  ]);
119
- const confirmed = [...local, ...subnets.map((subnet) => subnet.check), ...(validator?.listed ? [validator.check] : [])];
158
+ const confirmed = [
159
+ ...local,
160
+ ...subnets.map((subnet) => subnet.check),
161
+ ...(validator?.listed ? [validator.check] : []),
162
+ ...(kept?.listed ? [{ check: `hotkey ${hotkey} is a validator of subnet ${buy}`, url: kept.url }] : []),
163
+ ];
120
164
  const found = [...confirmed, ...(validator && !validator.listed ? [validator.check] : [])];
121
165
  const pools = new Map(netuids.flatMap((netuid, i) => (subnets[i]?.pool ? [[netuid, subnets[i].pool]] : [])));
122
166
  const figures = estimateTrade(sell, buy, Number(linkAmount), pools);
@@ -152,11 +196,55 @@ const prepareTrade = {
152
196
  : estimate.fee_percent === 0
153
197
  ? `Receives ${estimate.receive} ${estimate.receive_unit}, one for one. ${APP_SHOWS}`
154
198
  : `Indicative estimate: about ${estimate.receive} ${estimate.receive_unit} (price impact ${percent(estimate.price_impact_percent)}, fee included), from the subnet's price and pool reserves as the API last read them. ${APP_SHOWS}`;
199
+ const tolerance = tolerance_percent ?? DEFAULT_TOLERANCE_PERCENT;
200
+ const prices = new Map(netuids.flatMap((netuid, i) => (subnets[i]?.price ? [[netuid, subnets[i].price]] : [])));
201
+ const signable = kept && !kept.listed
202
+ ? {
203
+ call: undefined,
204
+ reason: `hotkey ${hotkey} is not among subnet ${buy}'s validators (GET ${kept.url}), where a swap's call would leave the stake with it: use the link, or unstake then stake`,
205
+ }
206
+ : tradeCall({ sell, buy, amount: linkAmount, hotkey, tolerancePercent: tolerance, prices });
207
+ const move = priceMovePercent(sell, buy, Number(linkAmount), pools);
208
+ const bound = !signable.call || signable.referencePrice === undefined
209
+ ? "Amounts are in rao. Free TAO and root trade one for one, so the call carries no price limit."
210
+ : type === "swap"
211
+ ? `Amounts are in rao. limit_price is the least alpha of subnet ${buy} received per alpha of subnet ${sell} sold, times 1e9: ${percent(tolerance)} under the ${round(signable.referencePrice)} that the API's last prices give. The call fails rather than fill below it.`
212
+ : `Amounts are in rao, limit_price in rao per alpha: ${percent(tolerance)} ${type === "stake" ? "above" : "below"} the API's last price of ${signable.referencePrice} TAO per alpha. The call fails rather than fill once the pool's price passes it, the trade's own impact included.`;
213
+ const call = signable.call && {
214
+ ...signable.call,
215
+ ...(signable.referencePrice === undefined
216
+ ? {}
217
+ : {
218
+ tolerance_percent: tolerance,
219
+ reference_price: signable.referencePrice,
220
+ reference_price_unit: type === "swap" ? `alpha of subnet ${buy} per alpha of subnet ${sell}` : "TAO per alpha",
221
+ }),
222
+ note: `${bound}${signable.houseHotkey ? ` ${HOUSE}` : ""} A Bittensor wallet on the user's machine signs it, once the user approves; this server signs nothing.`,
223
+ };
224
+ const signing = signable.call
225
+ ? [
226
+ `Call to sign without the web, once the user has seen it and approves, with a Bittensor wallet on their machine (${SIGNERS}): ${callLine(signable.call)}`,
227
+ bound,
228
+ ...(signable.houseHotkey ? [HOUSE] : []),
229
+ ...(type === "swap"
230
+ ? [`The call leaves the stake with validator ${hotkey} on subnet ${buy}; the link lets the app pick one.`]
231
+ : []),
232
+ ...(type === "stake"
233
+ ? []
234
+ : ["The wallet that signs must hold this position: a call for stake it does not hold fails on chain, and its fee is paid."]),
235
+ ...(signable.referencePrice !== undefined && move !== undefined && move > tolerance
236
+ ? [
237
+ `At this size the trade itself moves the price by about ${percent(move)}, past the tolerance: the call would fail. Lower the amount or raise tolerance_percent.`,
238
+ ]
239
+ : []),
240
+ ]
241
+ : [`No call to sign here: ${signable.reason}.`];
155
242
  return {
156
243
  structured: {
157
244
  url,
158
245
  action: { type, sell, buy, amount: linkAmount, amount_unit: unitOf(sell), ...(hotkey === undefined ? {} : { hotkey }) },
159
246
  ...(estimate ? { estimate } : {}),
247
+ ...(call ? { call } : {}),
160
248
  checks: found,
161
249
  },
162
250
  text: [
@@ -165,6 +253,7 @@ const prepareTrade = {
165
253
  about,
166
254
  `Checked: ${confirmed.map((c) => c.check).join("; ")}.`,
167
255
  ...(validator && !validator.listed ? [sentence(validator.check.check)] : []),
256
+ ...signing,
168
257
  ].join("\n"),
169
258
  };
170
259
  },
@@ -288,16 +377,17 @@ const prepareNewWallet = {
288
377
  name: "prepare_new_wallet",
289
378
  title: "Prepare a new wallet",
290
379
  operations: [],
291
- description: "Returns the taoswap.org link where the user creates a wallet in their own browser. The app shows its recovery phrase to the user alone: never ask for it, nor accept it.",
380
+ description: "Returns the taoswap.org link where the user creates a wallet in their own browser. The app shows its recovery phrase to the user alone: never ask for it, nor accept it. Also names the ways to create one on the user's own machine instead, where the phrase stays.",
292
381
  input: z.strictObject({}),
293
- output: output(z.object({ type: z.literal("create_wallet") })),
382
+ output: output(z.object({ type: z.literal("create_wallet"), local: z.array(z.object({ with: z.string(), how: z.string() })) })),
294
383
  async run() {
295
384
  const url = walletCreationLink({ utm: UTM });
296
385
  return {
297
- structured: { url, action: { type: "create_wallet" }, checks: [] },
386
+ structured: { url, action: { type: "create_wallet", local: LOCAL_WALLETS }, checks: [] },
298
387
  text: [
299
388
  `Link for the user to open: ${url}`,
300
389
  "The app creates the wallet in the user's browser and shows its recovery phrase to them alone. They write it down offline and never share it, with this assistant or anyone else.",
390
+ `Without the web, on the user's own machine: ${LOCAL_WALLETS.map((way) => `${way.with} (${way.how})`).join("; ")}. The phrase stays on that machine: this server never sees it, and the assistant never reads it back.`,
301
391
  ].join("\n"),
302
392
  };
303
393
  },
package/dist/call.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ /** The unsigned chain call of a trade, for a wallet on the user's machine to sign: this server signs nothing and holds no key. */
2
+ /** Taoswap's validator (Kusanagi), which taoswap.org stakes to when the user names none. */
3
+ export declare const HOUSE_HOTKEY = "5CszMVts9ueMUSKdAwLFSLT7u4oyxN7fUBpo8Z3ETw1ggMUV";
4
+ export declare const DEFAULT_TOLERANCE_PERCENT = 1;
5
+ export type CallMethod = "add_stake" | "add_stake_limit" | "remove_stake" | "remove_stake_limit" | "swap_stake_limit";
6
+ /** A SubtensorModule call by the names its runtime metadata gives it: u64 amounts in rao as decimal text, prices in rao per alpha. */
7
+ export interface UnsignedCall {
8
+ pallet: "SubtensorModule";
9
+ method: CallMethod;
10
+ args: Record<string, string | number | boolean>;
11
+ }
12
+ export interface TradeCallInput {
13
+ sell: "tao" | number;
14
+ buy: "tao" | number;
15
+ /** The link's amount: a positive decimal with at most 6 decimals, in the sold asset. */
16
+ amount: string;
17
+ /** The validator staked to, or the one whose position is sold; undefined when the user named none. */
18
+ hotkey: string | undefined;
19
+ tolerancePercent: number;
20
+ /** TAO per alpha of each subnet traded, where the API serves one. */
21
+ prices: ReadonlyMap<number, number>;
22
+ }
23
+ export type TradeCall = {
24
+ call: UnsignedCall;
25
+ /** What limit_price bounds, in TAO per alpha, or alpha received per alpha sold on a swap; undefined for a call without a limit. */
26
+ referencePrice: number | undefined;
27
+ /** Whether the call stakes with HOUSE_HOTKEY because the user named no validator. */
28
+ houseHotkey: boolean;
29
+ } | {
30
+ call: undefined;
31
+ reason: string;
32
+ };
33
+ /** A decimal with at most 9 decimals as rao. */
34
+ export declare function toRao(amount: string): bigint;
35
+ /** A price as the u64 the chain reads, scaled by 1e9: floored, or rounded up for a ceiling. */
36
+ export declare function priceToRao(price: number, rounding: "floor" | "ceil"): bigint;
37
+ /**
38
+ * The call a trade signs, as taoswap.org builds it: a price-limited call that fails rather than fill past the limit, allow_partial
39
+ * off. The limit sits `tolerancePercent` from the API's last price, so it bounds the trade's own price impact and the market's move
40
+ * together. Free TAO and root trade one for one, without a limit.
41
+ */
42
+ export declare function tradeCall(input: TradeCallInput): TradeCall;
43
+ /** The call as one line: SubtensorModule.add_stake_limit(hotkey=..., netuid=64, ...). */
44
+ export declare function callLine(call: UnsignedCall): string;
package/dist/call.js ADDED
@@ -0,0 +1,136 @@
1
+ /** The unsigned chain call of a trade, for a wallet on the user's machine to sign: this server signs nothing and holds no key. */
2
+ /** Taoswap's validator (Kusanagi), which taoswap.org stakes to when the user names none. */
3
+ export const HOUSE_HOTKEY = "5CszMVts9ueMUSKdAwLFSLT7u4oyxN7fUBpo8Z3ETw1ggMUV";
4
+ export const DEFAULT_TOLERANCE_PERCENT = 1;
5
+ const U64_MAX = 0xffffffffffffffffn;
6
+ /** A decimal with at most 9 decimals as rao. */
7
+ export function toRao(amount) {
8
+ const [whole = "0", fraction = ""] = amount.split(".");
9
+ return BigInt(whole) * 1000000000n + BigInt(fraction.padEnd(9, "0").slice(0, 9));
10
+ }
11
+ /** "5.7e-7" as "0.00000057", by string arithmetic. */
12
+ function expandExponential(value) {
13
+ const [mantissa = "", exponent = "0"] = value.toLowerCase().split("e");
14
+ const [whole = "", fraction = ""] = mantissa.split(".");
15
+ const digits = whole + fraction;
16
+ const point = whole.length + Number.parseInt(exponent, 10);
17
+ if (point <= 0)
18
+ return `0.${"0".repeat(-point)}${digits}`;
19
+ if (point >= digits.length)
20
+ return digits + "0".repeat(point - digits.length);
21
+ return `${digits.slice(0, point)}.${digits.slice(point)}`;
22
+ }
23
+ /** A price as the u64 the chain reads, scaled by 1e9: floored, or rounded up for a ceiling. */
24
+ export function priceToRao(price, rounding) {
25
+ if (!Number.isFinite(price) || price <= 0)
26
+ return 0n;
27
+ let text = String(price);
28
+ if (/e/i.test(text))
29
+ text = expandExponential(text);
30
+ const [whole = "0", fraction = ""] = text.split(".");
31
+ const rao = BigInt(whole || "0") * 1000000000n + BigInt(fraction.padEnd(9, "0").slice(0, 9));
32
+ return rounding === "ceil" && /[1-9]/.test(fraction.slice(9)) ? rao + 1n : rao;
33
+ }
34
+ /**
35
+ * The call a trade signs, as taoswap.org builds it: a price-limited call that fails rather than fill past the limit, allow_partial
36
+ * off. The limit sits `tolerancePercent` from the API's last price, so it bounds the trade's own price impact and the market's move
37
+ * together. Free TAO and root trade one for one, without a limit.
38
+ */
39
+ export function tradeCall(input) {
40
+ const { sell, buy, hotkey, prices } = input;
41
+ const rao = toRao(input.amount);
42
+ if (rao > U64_MAX)
43
+ return { call: undefined, reason: "the amount is past what the chain's u64 holds" };
44
+ const amount = rao.toString();
45
+ const tolerance = input.tolerancePercent / 100;
46
+ const noPrice = (netuid) => `the API serves no price for subnet ${netuid}, so no limit can be set`;
47
+ // A limit is a whole number of rao: at a price of a few rao it sits further from the price than the tolerance asked for.
48
+ const unheld = (limit, reference) => limit <= 0n
49
+ ? "the limit rounds to 0 rao, which the chain reads as no limit"
50
+ : Math.abs(Number(limit) / 1e9 / reference - 1) > 2 * tolerance
51
+ ? "the price is too small for a limit in whole rao to hold this tolerance"
52
+ : undefined;
53
+ if (sell === "tao" && typeof buy === "number") {
54
+ const staked = { hotkey: hotkey ?? HOUSE_HOTKEY, netuid: buy, amount_staked: amount };
55
+ const houseHotkey = hotkey === undefined;
56
+ if (buy === 0)
57
+ return { call: { pallet: "SubtensorModule", method: "add_stake", args: staked }, referencePrice: undefined, houseHotkey };
58
+ const price = prices.get(buy);
59
+ if (price === undefined)
60
+ return { call: undefined, reason: noPrice(buy) };
61
+ const limit = priceToRao(price * (1 + tolerance), "ceil");
62
+ const reason = unheld(limit, price);
63
+ if (reason)
64
+ return { call: undefined, reason };
65
+ return {
66
+ call: {
67
+ pallet: "SubtensorModule",
68
+ method: "add_stake_limit",
69
+ args: { ...staked, limit_price: limit.toString(), allow_partial: false },
70
+ },
71
+ referencePrice: price,
72
+ houseHotkey,
73
+ };
74
+ }
75
+ if (hotkey === undefined)
76
+ return { call: undefined, reason: "name the hotkey of the position sold, which the link leaves to the app and a call cannot" };
77
+ if (typeof sell === "number" && buy === "tao") {
78
+ const unstaked = { hotkey, netuid: sell, amount_unstaked: amount };
79
+ if (sell === 0)
80
+ return { call: { pallet: "SubtensorModule", method: "remove_stake", args: unstaked }, referencePrice: undefined, houseHotkey: false };
81
+ const price = prices.get(sell);
82
+ if (price === undefined)
83
+ return { call: undefined, reason: noPrice(sell) };
84
+ const limit = priceToRao(price * (1 - tolerance), "floor");
85
+ const reason = unheld(limit, price);
86
+ if (reason)
87
+ return { call: undefined, reason };
88
+ return {
89
+ call: {
90
+ pallet: "SubtensorModule",
91
+ method: "remove_stake_limit",
92
+ args: { ...unstaked, limit_price: limit.toString(), allow_partial: false },
93
+ },
94
+ referencePrice: price,
95
+ houseHotkey: false,
96
+ };
97
+ }
98
+ if (typeof sell === "number" && typeof buy === "number") {
99
+ if (sell === 0 || buy === 0)
100
+ return { call: undefined, reason: "a swap with root on one side has no price-limited call: unstake to free TAO, then stake" };
101
+ const from = prices.get(sell);
102
+ const to = prices.get(buy);
103
+ if (from === undefined)
104
+ return { call: undefined, reason: noPrice(sell) };
105
+ if (to === undefined)
106
+ return { call: undefined, reason: noPrice(buy) };
107
+ const ratio = from / to;
108
+ const limit = priceToRao(ratio * (1 - tolerance), "floor");
109
+ const reason = unheld(limit, ratio);
110
+ if (reason)
111
+ return { call: undefined, reason };
112
+ return {
113
+ call: {
114
+ pallet: "SubtensorModule",
115
+ method: "swap_stake_limit",
116
+ args: {
117
+ hotkey,
118
+ origin_netuid: sell,
119
+ destination_netuid: buy,
120
+ alpha_amount: amount,
121
+ limit_price: limit.toString(),
122
+ allow_partial: false,
123
+ },
124
+ },
125
+ referencePrice: ratio,
126
+ houseHotkey: false,
127
+ };
128
+ }
129
+ return { call: undefined, reason: "a trade needs two different assets" };
130
+ }
131
+ /** The call as one line: SubtensorModule.add_stake_limit(hotkey=..., netuid=64, ...). */
132
+ export function callLine(call) {
133
+ return `${call.pallet}.${call.method}(${Object.entries(call.args)
134
+ .map(([name, value]) => `${name}=${value}`)
135
+ .join(", ")})`;
136
+ }
package/dist/cli.js CHANGED
@@ -4,7 +4,7 @@ import { parseArgs } from "node:util";
4
4
  import { localhostAllowedHostnames } from "@modelcontextprotocol/server";
5
5
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
6
6
  import { createHttpServer, HTTP_DEFAULTS, MAX_BODY_BYTES } from "./http.js";
7
- import { Metrics } from "./metrics.js";
7
+ import { clientLabel, KNOWN_CLIENTS, MAX_KNOWN_CLIENTS, Metrics } from "./metrics.js";
8
8
  import { createServer, defaultClient, MIN_MAX_CHARS, VERSION } from "./server.js";
9
9
  import { UPSTREAM_DEFAULTS, Upstream, upstreamClient } from "./upstream.js";
10
10
  /** At 4 requests a second, a request queued behind this many starts within the client's 20-second timeout. */
@@ -37,6 +37,7 @@ With --http:
37
37
  TAOSWAP_MCP_MAX_QUEUE API requests that may wait their turn before a tool call fails as busy (${UPSTREAM_DEFAULTS.maxQueued}, ${MAX_QUEUE_LIMIT} at most)
38
38
  TAOSWAP_MCP_CACHE_MB megabytes of API answers kept in memory (${UPSTREAM_DEFAULTS.maxBytes / 1024 / 1024})
39
39
  TAOSWAP_MCP_METRICS 1 serves Prometheus counters at GET /metrics, which a proxy should keep private (0)
40
+ TAOSWAP_MCP_METRICS_CLIENTS client names counted from zero under their own label, comma-separated, besides ${KNOWN_CLIENTS.join(", ")}
40
41
  A request body is ${MAX_BODY_BYTES / 1024} KiB at most.`;
41
42
  const flags = (() => {
42
43
  try {
@@ -93,7 +94,8 @@ function serveHttp() {
93
94
  const timeout = whole("TAOSWAP_MCP_TIMEOUT", env.TAOSWAP_MCP_TIMEOUT, HTTP_DEFAULTS.timeoutSeconds, 1, 3600);
94
95
  const maxQueued = whole("TAOSWAP_MCP_MAX_QUEUE", env.TAOSWAP_MCP_MAX_QUEUE, UPSTREAM_DEFAULTS.maxQueued, 0, MAX_QUEUE_LIMIT);
95
96
  const cacheMb = whole("TAOSWAP_MCP_CACHE_MB", env.TAOSWAP_MCP_CACHE_MB, UPSTREAM_DEFAULTS.maxBytes / 1024 / 1024, 0, 65_536);
96
- const metrics = whole("TAOSWAP_MCP_METRICS", env.TAOSWAP_MCP_METRICS, 0, 0, 1) === 1 ? new Metrics(VERSION) : undefined;
97
+ const clients = clientList("TAOSWAP_MCP_METRICS_CLIENTS", env.TAOSWAP_MCP_METRICS_CLIENTS);
98
+ const metrics = whole("TAOSWAP_MCP_METRICS", env.TAOSWAP_MCP_METRICS, 0, 0, 1) === 1 ? new Metrics(VERSION, { clients }) : undefined;
97
99
  const client = upstreamClient(new Upstream({ maxQueued, maxBytes: cacheMb * 1024 * 1024, ...(metrics ? { metrics } : {}) }));
98
100
  const server = createHttpServer({
99
101
  factory: () => createServer({ client, ...(maxChars ? { maxChars } : {}), ...(metrics ? { metrics } : {}) }),
@@ -150,6 +152,16 @@ function hostList(name, raw) {
150
152
  fail(`${name} must list host names, comma-separated, without scheme or port and IPv6 in brackets: got ${wrong ?? raw}`);
151
153
  return entries;
152
154
  }
155
+ function clientList(name, raw) {
156
+ const entries = (raw ?? "")
157
+ .split(",")
158
+ .map((entry) => entry.trim())
159
+ .filter(Boolean);
160
+ const wrong = entries.find((entry) => clientLabel(entry) === "");
161
+ if (wrong !== undefined || entries.length > MAX_KNOWN_CLIENTS)
162
+ fail(`${name} must list at most ${MAX_KNOWN_CLIENTS} client names, comma-separated: got ${wrong ?? `${entries.length} names`}`);
163
+ return entries;
164
+ }
153
165
  function fail(message) {
154
166
  console.error(`taoswap-mcp: ${message}`);
155
167
  process.exit(2);
@@ -30,5 +30,11 @@ export interface LimitEstimate {
30
30
  * subnets pays the fee once, on the subnet sold. Undefined when a subnet traded has no pool in `pools`.
31
31
  */
32
32
  export declare function estimateTrade(sell: "tao" | number, buy: "tao" | number, amount: number, pools: ReadonlyMap<number, Pool>): TradeEstimate | undefined;
33
+ /**
34
+ * How far the trade itself moves what a price-limited call holds its limit against, in percent: the pool's price once a stake or an
35
+ * unstake has gone through, or the sold subnet's price over the bought one's once a swap has, which moves about twice as far as the
36
+ * average rate the swap fills at. Undefined for a one-for-one trade or a missing pool.
37
+ */
38
+ export declare function priceMovePercent(sell: "tao" | number, buy: "tao" | number, amount: number, pools: ReadonlyMap<number, Pool>): number | undefined;
33
39
  /** A limit order's type and distance from the market, typed as taoswap-app's orderTypeForSide does, on prices scaled by 1e9. */
34
40
  export declare function estimateLimit(side: "buy" | "sell", limitPrice: number, currentPrice: number, amount: number | undefined): LimitEstimate;
package/dist/estimate.js CHANGED
@@ -37,6 +37,34 @@ export function estimateTrade(sell, buy, amount, pools) {
37
37
  return undefined;
38
38
  return { receive, spot, priceImpactPercent: ((spot - receive) / spot) * 100, feePercent: DEFAULT_FEE_RATE * 100 };
39
39
  }
40
+ /**
41
+ * How far the trade itself moves what a price-limited call holds its limit against, in percent: the pool's price once a stake or an
42
+ * unstake has gone through, or the sold subnet's price over the bought one's once a swap has, which moves about twice as far as the
43
+ * average rate the swap fills at. Undefined for a one-for-one trade or a missing pool.
44
+ */
45
+ export function priceMovePercent(sell, buy, amount, pools) {
46
+ if (!Number.isFinite(amount) || amount <= 0)
47
+ return undefined;
48
+ const from = sell === "tao" || sell === 0 ? undefined : pools.get(sell);
49
+ const to = buy === "tao" || buy === 0 ? undefined : pools.get(buy);
50
+ const net = amount * (1 - DEFAULT_FEE_RATE);
51
+ if (sell === "tao" && to) {
52
+ const left = to.alpha - alphaOut(to, net);
53
+ return left > 0 ? ((weightRatio(to) * (to.tao + net)) / left / to.price - 1) * 100 : undefined;
54
+ }
55
+ if (buy === "tao" && from)
56
+ return (1 - (weightRatio(from) * (from.tao - taoOut(from, net))) / (from.alpha + net) / from.price) * 100;
57
+ if (from && to) {
58
+ const tao = taoOut(from, net);
59
+ const left = to.alpha - alphaOut(to, tao);
60
+ if (left <= 0)
61
+ return undefined;
62
+ const soldAfter = (weightRatio(from) * (from.tao - tao)) / (from.alpha + net);
63
+ const boughtAfter = (weightRatio(to) * (to.tao + tao)) / left;
64
+ return (1 - soldAfter / boughtAfter / (from.price / to.price)) * 100;
65
+ }
66
+ return undefined;
67
+ }
40
68
  /** A limit order's type and distance from the market, typed as taoswap-app's orderTypeForSide does, on prices scaled by 1e9. */
41
69
  export function estimateLimit(side, limitPrice, currentPrice, amount) {
42
70
  const limit = Math.round(limitPrice * 1e9);