taoswap-mcp 0.2.0 → 0.3.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
@@ -4,10 +4,10 @@ MCP server for the [Taoswap API](https://api.taoswap.org/llms.txt): free Bittens
4
4
 
5
5
  ```sh
6
6
  npx -y taoswap-mcp@latest # follows releases
7
- npx -y taoswap-mcp@0.2.0 # pins this version
7
+ npx -y taoswap-mcp@0.3.0 # pins this version
8
8
  ```
9
9
 
10
- It speaks MCP over stdio 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.
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.
11
11
 
12
12
  ## Add it to your assistant
13
13
 
@@ -54,9 +54,11 @@ All tools are read-only and call `https://api.taoswap.org` only; the four `prepa
54
54
  | `list_subnets` | Every subnet with price, market cap, emission and volume, sortable here | `GET /v2/subnets/` |
55
55
  | `get_subnet` | One subnet: identity, price, pools, emission, burn, holders, dereg risk | `GET /v2/subnets/{netuid}/` |
56
56
  | `get_subnet_candles` | OHLCV candles of a subnet's alpha price | `GET /subnet-price-history/` |
57
+ | `get_subnet_history` | A subnet's emissions, pool reserves, price, holders and burns per day | `GET /v2/subnets/{netuid}/history/` |
57
58
  | `get_tao_price` | Daily TAO price in USD or EUR | `GET /price-history/` |
58
59
  | `list_validators` | Validators with take, root and alpha yields, stake and delegators | `GET /v2/validators/` |
59
60
  | `get_validator` | One validator, its subnets, history and delegators | `GET /v2/validators/{hotkey}/` |
61
+ | `get_validator_history` | A validator's root and alpha stake and its delegator counts per day | `GET /v2/validators/{hotkey}/history/` |
60
62
  | `list_subnet_validators` | A subnet's validators with their yields | `GET /v2/subnets/{netuid}/validators/` |
61
63
  | `get_metagraph` | A subnet's neurons: stake, vtrust, incentive, dividends, rewards | `GET /metagraph/{netuid}/` |
62
64
  | `get_portfolio` | A coldkey's balance per day | `GET /portfolio-balance/` |
@@ -73,7 +75,7 @@ All tools are read-only and call `https://api.taoswap.org` only; the four `prepa
73
75
  | `prepare_transfer` | A taoswap.org link to send TAO | no request |
74
76
  | `prepare_new_wallet` | The taoswap.org link that creates a wallet in the user's browser | no request |
75
77
 
76
- 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; set `TAOSWAP_MCP_MAX_CHARS` to change that.
78
+ 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.
77
79
 
78
80
  Subnet and validator names, descriptions, URLs and Discord handles come from on-chain identities that anyone can write. The server cuts each such string at 200 characters, and an answer that carries them says, above the data, that they are untrusted text to read as data, never as instructions.
79
81
 
@@ -92,6 +94,18 @@ Amounts are in the sold asset: TAO to stake or to buy with a limit order, alpha
92
94
 
93
95
  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.
94
96
 
97
+ ## Prompts
98
+
99
+ The server offers three MCP prompts, which clients often show as slash commands. A prompt calls nothing: it writes the request that tells the assistant which tools to call and what to report, each figure with its unit and the API URL it came from.
100
+
101
+ | Prompt | Arguments | Asks for |
102
+ | -------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
103
+ | `analyze_subnet` | `netuid` | Price and its trend, pool depth, emissions and how concentrated the validators are, from `get_subnet`, `get_subnet_candles`, `get_subnet_history` and `list_subnet_validators` |
104
+ | `compare_validators` | `netuid`, and optionally `hotkeys`, comma-separated, 8 at most | A table of take, yields, stake and vtrust for those validators, or the subnet's 10 largest, from `list_subnet_validators` or `get_validator` |
105
+ | `review_portfolio` | `coldkey` | Positions, PnL and yields from `get_portfolio`, `get_portfolio_pnl` and `get_account_ledger`; an action only as a `prepare_` link the user signs in their own wallet |
106
+
107
+ Each argument is checked before it reaches the conversation: a netuid is a whole number from 0 to 65535, and an address a Bittensor SS58 address with a valid checksum. Anything else is refused with an error that names the argument without repeating it. Every prompt says that its figures are data, not financial advice, and that the user never shares a seed phrase, a private key or a password.
108
+
95
109
  ## Link to Taoswap
96
110
 
97
111
  A site or a bot builds the same links without the MCP server: `tradeLink`, `limitOrderLink`, `transferLink` and `walletCreationLink` in the [`taoswap`](https://www.npmjs.com/package/taoswap) npm package, `trade_link`, `limit_order_link`, `transfer_link` and `wallet_creation_link` in the [`taoswap`](https://pypi.org/project/taoswap/) PyPI package. They call nothing and take their own `utm` fields.
@@ -102,9 +116,52 @@ The server paces itself to 4 requests a second and 4 at once, below the API's pe
102
116
 
103
117
  Data is as fresh as the API: a block is indexed within about a minute, and routes cache their answers for 15 seconds (candles) to 10 minutes (TAO price), 2 minutes for subnets. The API is free, with no uptime commitment.
104
118
 
119
+ ## Remote (HTTP)
120
+
121
+ `--http` serves the same tools over Streamable HTTP, for clients that reach a server by its URL instead of starting it, such as claude.ai custom connectors, Claude mobile and ChatGPT. Taoswap runs no public endpoint yet: such a client needs a server that you run and expose over HTTPS yourself.
122
+
123
+ ```sh
124
+ npx -y taoswap-mcp@latest --http # http://127.0.0.1:8080/mcp
125
+ npx -y taoswap-mcp@latest --http --host 0.0.0.0 --port 3000
126
+ ```
127
+
128
+ The `Dockerfile` at the root of the repository builds the same server from source with `npm ci` and runs it as a non-root user: over stdio by default, and over HTTP on port 8080 of every interface of the container with `--http`.
129
+
130
+ ```sh
131
+ docker build -t taoswap-mcp .
132
+ docker run --rm -i taoswap-mcp # stdio
133
+ docker run --rm -p 127.0.0.1:8080:8080 taoswap-mcp --http # http://127.0.0.1:8080/mcp
134
+ ```
135
+
136
+ The server keeps no session: it answers each `POST /mcp` on its own, for protocol versions 2024-10-07 to 2025-11-25 after their `initialize` handshake, and for 2026-07-28 on any request that names it in `_meta`, as over stdio. `GET` and `DELETE` on `/mcp` answer `405`, since no stream or session stays open, and `GET /healthz` answers `{"status":"ok"}`. Nothing authenticates a client: the data is public, and the `prepare_` tools only return links. Put a reverse proxy that terminates TLS in front of the server, and set `TAOSWAP_MCP_TRUST_PROXY` and `TAOSWAP_MCP_ALLOWED_HOSTS` for it.
137
+
138
+ Every client shares the server's one Taoswap client, and with it the API's limits on the server's one address. So the server:
139
+
140
+ - keeps the API's successful JSON answers in memory as long as the API caches them, so an answer can be up to twice that old: 10 minutes for the TAO price, 2 minutes for the subnet list, 15 seconds for the rest; a `429` or an error is never kept;
141
+ - sends one request to the API for identical ones in flight, and paces its requests to the API at 4 a second and 4 at once;
142
+ - fails a tool call at once with `BUSY` and the seconds to wait when 40 requests to the API already wait their turn, rather than letting calls pile up;
143
+ - 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;
144
+ - 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.
145
+
146
+ | Setting | Default | What it sets |
147
+ | ------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
148
+ | `--port`, `TAOSWAP_MCP_PORT` | `8080` | The port; `0` picks a free one |
149
+ | `--host`, `TAOSWAP_MCP_HOST` | `127.0.0.1`, and `0.0.0.0` in the image | The address to listen on |
150
+ | `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 |
151
+ | `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 |
152
+ | `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 |
153
+ | `TAOSWAP_MCP_RATE_PER_IP` | `120` | Requests a minute per client address, which may all come at once |
154
+ | `TAOSWAP_MCP_CONCURRENT_PER_IP` | `8` | Requests at once per client address |
155
+ | `TAOSWAP_MCP_CONCURRENT` | `64` | Requests at once in all |
156
+ | `TAOSWAP_MCP_TIMEOUT` | `60` | Seconds before a request still without an answer gets a `504` |
157
+ | `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 |
158
+ | `TAOSWAP_MCP_CACHE_MB` | `64` | Megabytes of API answers kept in memory, 2,000 answers at most |
159
+
160
+ `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.
161
+
105
162
  ## Use from code
106
163
 
107
- `createServer()` builds the server without a transport, so it can be served over stdio, as the command does, or over HTTP:
164
+ `createServer()` builds the server without a transport, so it can be served over stdio or HTTP, as the command does, or over another transport:
108
165
 
109
166
  ```ts
110
167
  import { createServer } from "taoswap-mcp";
package/dist/cli.js CHANGED
@@ -1,21 +1,152 @@
1
1
  #!/usr/bin/env node
2
+ import { isIP } from "node:net";
3
+ import { parseArgs } from "node:util";
4
+ import { localhostAllowedHostnames } from "@modelcontextprotocol/server";
2
5
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
3
- import { createServer, defaultClient, VERSION } from "./server.js";
6
+ import { createHttpServer, HTTP_DEFAULTS, MAX_BODY_BYTES } from "./http.js";
7
+ import { createServer, defaultClient, MIN_MAX_CHARS, VERSION } from "./server.js";
8
+ import { UPSTREAM_DEFAULTS, Upstream, upstreamClient } from "./upstream.js";
9
+ /** At 4 requests a second, a request queued behind this many starts within the client's 20-second timeout. */
10
+ const MAX_QUEUE_LIMIT = 60;
11
+ const HOST_NAME = /^(?=.{1,253}$)[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
4
12
  const args = process.argv.slice(2);
5
13
  if (args.includes("--version")) {
6
14
  console.log(VERSION);
7
15
  process.exit(0);
8
16
  }
9
- if (args.includes("--help") || args.length > 0) {
10
- console.log(`taoswap-mcp ${VERSION}: MCP server for the Taoswap Bittensor API (https://api.taoswap.org), over stdio.
17
+ const help = `taoswap-mcp ${VERSION}: MCP server for the Taoswap Bittensor API (https://api.taoswap.org).
11
18
 
12
- Usage: npx -y taoswap-mcp@latest
19
+ Usage:
20
+ npx -y taoswap-mcp@latest serves MCP over stdio, to the client that starts it
21
+ npx -y taoswap-mcp@latest --http serves MCP over Streamable HTTP at /mcp, without sessions, and GET /healthz
22
+ --port <port> or TAOSWAP_MCP_PORT: ${HTTP_DEFAULTS.port} by default, 0 for any free port
23
+ --host <address> or TAOSWAP_MCP_HOST: ${HTTP_DEFAULTS.host} by default
13
24
 
14
- Environment: TAOSWAP_MCP_MAX_CHARS caps the length of a tool answer (40000 by default).`);
15
- process.exit(args.includes("--help") ? 0 : 2);
16
- }
17
- const maxChars = Number(process.env.TAOSWAP_MCP_MAX_CHARS ?? "") || undefined;
18
- const client = defaultClient();
19
- serveStdio(() => createServer({ client, ...(maxChars ? { maxChars } : {}) }), {
20
- onerror: (error) => console.error(`taoswap-mcp: ${error.message}`),
21
- });
25
+ Environment:
26
+ TAOSWAP_MCP_MAX_CHARS caps the length of a tool answer (40000 by default, ${MIN_MAX_CHARS} at least)
27
+
28
+ With --http:
29
+ TAOSWAP_MCP_TRUST_PROXY reverse proxies in front, each appending to X-Forwarded-For (0: the header is ignored)
30
+ TAOSWAP_MCP_ALLOWED_HOSTS Host names accepted, comma-separated, or * (localhost names on a loopback host, else any)
31
+ TAOSWAP_MCP_ALLOWED_ORIGINS browser Origin names accepted, comma-separated (localhost names)
32
+ TAOSWAP_MCP_RATE_PER_IP requests a minute per client address (${HTTP_DEFAULTS.ratePerIp})
33
+ TAOSWAP_MCP_CONCURRENT_PER_IP requests at once per client address (${HTTP_DEFAULTS.concurrentPerIp})
34
+ TAOSWAP_MCP_CONCURRENT requests at once in all (${HTTP_DEFAULTS.concurrent})
35
+ TAOSWAP_MCP_TIMEOUT seconds a request may take, its answer included (${HTTP_DEFAULTS.timeoutSeconds})
36
+ 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)
37
+ TAOSWAP_MCP_CACHE_MB megabytes of API answers kept in memory (${UPSTREAM_DEFAULTS.maxBytes / 1024 / 1024})
38
+ A request body is ${MAX_BODY_BYTES / 1024} KiB at most.`;
39
+ const flags = (() => {
40
+ try {
41
+ const options = { help: { type: "boolean" }, http: { type: "boolean" }, port: { type: "string" }, host: { type: "string" } };
42
+ return parseArgs({ args, options }).values;
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ })();
48
+ if (!flags || flags.help) {
49
+ console.log(help);
50
+ process.exit(flags ? 0 : 2);
51
+ }
52
+ const rawMaxChars = process.env.TAOSWAP_MCP_MAX_CHARS?.trim() ?? "";
53
+ const maxChars = rawMaxChars === "" ? undefined : Number(rawMaxChars);
54
+ if (maxChars !== undefined && (!Number.isInteger(maxChars) || maxChars < MIN_MAX_CHARS)) {
55
+ console.error(`taoswap-mcp: TAOSWAP_MCP_MAX_CHARS must be a whole number of characters, ${MIN_MAX_CHARS} or more: got ${rawMaxChars}`);
56
+ process.exit(2);
57
+ }
58
+ if (!flags.http) {
59
+ if (flags.port !== undefined || flags.host !== undefined)
60
+ fail("--port and --host serve HTTP: add --http");
61
+ const client = defaultClient();
62
+ serveStdio(() => createServer({ client, ...(maxChars ? { maxChars } : {}) }), {
63
+ onerror: (error) => console.error(`taoswap-mcp: ${error.message}`),
64
+ });
65
+ }
66
+ else {
67
+ serveHttp();
68
+ }
69
+ function serveHttp() {
70
+ const env = process.env;
71
+ const port = whole(...pick("--port", flags?.port, "TAOSWAP_MCP_PORT"), HTTP_DEFAULTS.port, 0, 65_535);
72
+ const [hostName, rawHost] = pick("--host", flags?.host, "TAOSWAP_MCP_HOST");
73
+ const host = rawHost?.trim() || HTTP_DEFAULTS.host;
74
+ if (!isHostName(host) || host.startsWith("["))
75
+ fail(`${hostName} must be an IP address or a host name: got ${host}`);
76
+ const loopback = host === "localhost" || host === "::1" || (isIP(host) === 4 && host.startsWith("127."));
77
+ const rawHosts = env.TAOSWAP_MCP_ALLOWED_HOSTS?.trim() ?? "";
78
+ const allowedHosts = rawHosts === ""
79
+ ? loopback
80
+ ? localhostAllowedHostnames()
81
+ : undefined
82
+ : rawHosts === "*"
83
+ ? undefined
84
+ : hostList("TAOSWAP_MCP_ALLOWED_HOSTS", rawHosts);
85
+ const rawOrigins = env.TAOSWAP_MCP_ALLOWED_ORIGINS?.trim() ?? "";
86
+ const allowedOrigins = rawOrigins === "" ? undefined : hostList("TAOSWAP_MCP_ALLOWED_ORIGINS", rawOrigins);
87
+ const trustProxy = whole("TAOSWAP_MCP_TRUST_PROXY", env.TAOSWAP_MCP_TRUST_PROXY, 0, 0, 10);
88
+ const ratePerIp = whole("TAOSWAP_MCP_RATE_PER_IP", env.TAOSWAP_MCP_RATE_PER_IP, HTTP_DEFAULTS.ratePerIp, 1, 1_000_000);
89
+ const concurrentPerIp = whole("TAOSWAP_MCP_CONCURRENT_PER_IP", env.TAOSWAP_MCP_CONCURRENT_PER_IP, HTTP_DEFAULTS.concurrentPerIp, 1, 100_000);
90
+ const concurrent = whole("TAOSWAP_MCP_CONCURRENT", env.TAOSWAP_MCP_CONCURRENT, HTTP_DEFAULTS.concurrent, 1, 100_000);
91
+ const timeout = whole("TAOSWAP_MCP_TIMEOUT", env.TAOSWAP_MCP_TIMEOUT, HTTP_DEFAULTS.timeoutSeconds, 1, 3600);
92
+ const maxQueued = whole("TAOSWAP_MCP_MAX_QUEUE", env.TAOSWAP_MCP_MAX_QUEUE, UPSTREAM_DEFAULTS.maxQueued, 0, MAX_QUEUE_LIMIT);
93
+ const cacheMb = whole("TAOSWAP_MCP_CACHE_MB", env.TAOSWAP_MCP_CACHE_MB, UPSTREAM_DEFAULTS.maxBytes / 1024 / 1024, 0, 65_536);
94
+ const client = upstreamClient(new Upstream({ maxQueued, maxBytes: cacheMb * 1024 * 1024 }));
95
+ const server = createHttpServer({
96
+ factory: () => createServer({ client, ...(maxChars ? { maxChars } : {}) }),
97
+ trustProxy,
98
+ ...(allowedHosts ? { allowedHosts } : {}),
99
+ ...(allowedOrigins ? { allowedOrigins } : {}),
100
+ ratePerIp,
101
+ concurrentPerIp,
102
+ concurrent,
103
+ timeoutMs: timeout * 1000,
104
+ onerror: (error) => console.error(`taoswap-mcp: ${error.message}`),
105
+ });
106
+ server.on("error", (error) => {
107
+ console.error(`taoswap-mcp: cannot serve HTTP on ${host} port ${port}: ${error.message}`);
108
+ process.exit(1);
109
+ });
110
+ server.listen(port, host, () => {
111
+ const bound = server.address();
112
+ const at = bound.family === "IPv6" ? `[${bound.address}]` : bound.address;
113
+ console.error(`taoswap-mcp ${VERSION}: MCP over Streamable HTTP at http://${at}:${bound.port}/mcp, health at /healthz`);
114
+ });
115
+ const stop = () => {
116
+ server.close(() => process.exit(0));
117
+ setTimeout(() => process.exit(0), 10_000).unref();
118
+ };
119
+ process.once("SIGTERM", stop);
120
+ process.once("SIGINT", stop);
121
+ }
122
+ /** The flag when given, else the environment variable, with the name to report it under. */
123
+ function pick(flag, value, variable) {
124
+ return value !== undefined ? [flag, value] : [variable, process.env[variable]];
125
+ }
126
+ function whole(name, raw, fallback, min, max) {
127
+ const text = raw?.trim() ?? "";
128
+ if (text === "")
129
+ return fallback;
130
+ const value = Number(text);
131
+ if (!Number.isInteger(value) || value < min || value > max)
132
+ fail(`${name} must be a whole number from ${min} to ${max}: got ${text}`);
133
+ return value;
134
+ }
135
+ function isHostName(entry) {
136
+ return isIP(entry) !== 0 || (entry.startsWith("[") && entry.endsWith("]") && isIP(entry.slice(1, -1)) === 6) || HOST_NAME.test(entry);
137
+ }
138
+ /** Host names as the SDK compares them: lowercase, without scheme or port, IPv6 in brackets. */
139
+ function hostList(name, raw) {
140
+ const entries = raw
141
+ .split(",")
142
+ .map((entry) => entry.trim().toLowerCase())
143
+ .filter(Boolean);
144
+ const wrong = entries.find((entry) => !isHostName(entry) || isIP(entry) === 6);
145
+ if (entries.length === 0 || wrong !== undefined)
146
+ fail(`${name} must list host names, comma-separated, without scheme or port and IPv6 in brackets: got ${wrong ?? raw}`);
147
+ return entries;
148
+ }
149
+ function fail(message) {
150
+ console.error(`taoswap-mcp: ${message}`);
151
+ process.exit(2);
152
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { type Server } from "node:http";
2
+ import { type McpServer } from "@modelcontextprotocol/server";
3
+ export declare const HTTP_DEFAULTS: {
4
+ readonly port: 8080;
5
+ readonly host: "127.0.0.1";
6
+ readonly ratePerIp: 120;
7
+ readonly concurrentPerIp: 8;
8
+ readonly concurrent: 64;
9
+ readonly timeoutSeconds: 60;
10
+ };
11
+ /** An MCP request is one small JSON-RPC message: no tool's arguments come near this. */
12
+ export declare const MAX_BODY_BYTES: number;
13
+ export interface HttpOptions {
14
+ /** Builds the MCP server that answers one request. */
15
+ factory: () => McpServer;
16
+ /** Reverse proxies in front of the server, each appending to X-Forwarded-For; 0, the default, ignores the header. */
17
+ trustProxy?: number;
18
+ /** Host header names accepted, ports aside; any host when absent. */
19
+ allowedHosts?: string[];
20
+ /** Origin header names accepted, localhost by default; a request without an Origin, as non-browser clients send, passes. */
21
+ allowedOrigins?: string[];
22
+ /** Requests a minute per client address, which may come in one burst. */
23
+ ratePerIp?: number;
24
+ /** Requests at once per client address. */
25
+ concurrentPerIp?: number;
26
+ /** Requests at once in all. */
27
+ concurrent?: number;
28
+ /** From a request's arrival to the end of its answer. */
29
+ timeoutMs?: number;
30
+ onerror?: (error: Error) => void;
31
+ /** The clock of the per-address token buckets, in milliseconds. */
32
+ now?: () => number;
33
+ }
34
+ /** A Node HTTP server, not yet listening, that serves MCP statelessly at /mcp and its health at /healthz. */
35
+ export declare function createHttpServer(options: HttpOptions): Server;
36
+ /** The key of a client's limits: its IPv4 address, or the /64 network of an IPv6 one, which one host often holds whole. */
37
+ export declare function clientKey(address: string): string;
package/dist/http.js ADDED
@@ -0,0 +1,289 @@
1
+ import { createServer } from "node:http";
2
+ import { isIP } from "node:net";
3
+ import { createMcpHandler, localhostAllowedOrigins, validateHostHeader, validateOriginHeader, } from "@modelcontextprotocol/server";
4
+ export const HTTP_DEFAULTS = {
5
+ port: 8080,
6
+ host: "127.0.0.1",
7
+ ratePerIp: 120,
8
+ concurrentPerIp: 8,
9
+ concurrent: 64,
10
+ timeoutSeconds: 60,
11
+ };
12
+ /** An MCP request is one small JSON-RPC message: no tool's arguments come near this. */
13
+ export const MAX_BODY_BYTES = 64 * 1024;
14
+ const HEADERS_TIMEOUT_MS = 10_000;
15
+ const RECEIVE_TIMEOUT_MS = 15_000;
16
+ /** A Node HTTP server, not yet listening, that serves MCP statelessly at /mcp and its health at /healthz. */
17
+ export function createHttpServer(options) {
18
+ const onerror = options.onerror ?? (() => undefined);
19
+ const trustProxy = options.trustProxy ?? 0;
20
+ const allowedOrigins = options.allowedOrigins ?? localhostAllowedOrigins();
21
+ const timeoutMs = options.timeoutMs ?? HTTP_DEFAULTS.timeoutSeconds * 1000;
22
+ const limits = new Limits(options.ratePerIp ?? HTTP_DEFAULTS.ratePerIp, options.concurrentPerIp ?? HTTP_DEFAULTS.concurrentPerIp, options.concurrent ?? HTTP_DEFAULTS.concurrent, options.now ?? (() => performance.now()));
23
+ const mcp = createMcpHandler(options.factory, { maxRequestBodySize: MAX_BODY_BYTES, onerror });
24
+ const serveMcp = async (req, res) => {
25
+ if (options.allowedHosts) {
26
+ const host = validateHostHeader(req.headers.host, options.allowedHosts);
27
+ if (!host.ok)
28
+ return reply(res, 403, host.message);
29
+ }
30
+ const origin = validateOriginHeader(req.headers.origin, allowedOrigins);
31
+ if (!origin.ok)
32
+ return reply(res, 403, origin.message);
33
+ const ended = new AbortController();
34
+ res.once("close", () => {
35
+ if (!res.writableFinished)
36
+ ended.abort();
37
+ });
38
+ let id = null;
39
+ const deadline = setTimeout(() => {
40
+ ended.abort();
41
+ if (res.headersSent)
42
+ res.destroy();
43
+ else
44
+ reply(res, 504, `Gateway Timeout: no answer within ${timeoutMs / 1000} seconds`, {}, id);
45
+ }, timeoutMs);
46
+ try {
47
+ const body = await readBody(req, MAX_BODY_BYTES);
48
+ if (body === "gone" || ended.signal.aborted)
49
+ return;
50
+ if (body === "too large")
51
+ return reply(res, 413, `Payload Too Large: the body must not exceed ${MAX_BODY_BYTES} bytes`);
52
+ id = requestId(body);
53
+ const request = new Request(new URL(req.url ?? "/mcp", "http://localhost"), {
54
+ method: "POST",
55
+ headers: headersOf(req),
56
+ body: new Uint8Array(body),
57
+ signal: ended.signal,
58
+ });
59
+ const response = await mcp.fetch(request);
60
+ if (res.headersSent || res.destroyed)
61
+ return void (await response.body?.cancel());
62
+ await send(res, response);
63
+ }
64
+ finally {
65
+ clearTimeout(deadline);
66
+ }
67
+ };
68
+ const route = async (req, res) => {
69
+ const path = (req.url ?? "/").split("?", 1)[0];
70
+ if (path === "/healthz") {
71
+ if (req.method !== "GET" && req.method !== "HEAD")
72
+ return reply(res, 405, "Method not allowed.", { Allow: "GET, HEAD" });
73
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
74
+ return void res.end('{"status":"ok"}');
75
+ }
76
+ if (path !== "/mcp")
77
+ return reply(res, 404, "Not Found: MCP is served at /mcp");
78
+ // Serving without sessions, the server has no stream to open on GET and no session to end on DELETE.
79
+ if (req.method !== "POST")
80
+ return reply(res, 405, "Method not allowed.", { Allow: "POST" });
81
+ const admitted = limits.admit(clientKey(clientAddress(req, trustProxy)));
82
+ if (typeof admitted !== "function")
83
+ return reply(res, admitted.status, admitted.message, { "Retry-After": String(admitted.retryAfter) });
84
+ try {
85
+ await serveMcp(req, res);
86
+ }
87
+ finally {
88
+ admitted();
89
+ }
90
+ };
91
+ const server = createServer({ headersTimeout: HEADERS_TIMEOUT_MS, requestTimeout: RECEIVE_TIMEOUT_MS, connectionsCheckingInterval: 2_000 }, (req, res) => {
92
+ // A client that leaves mid-request is no fault of the server's: nothing to report.
93
+ req.on("error", () => undefined);
94
+ res.on("error", () => undefined);
95
+ route(req, res).catch((caught) => {
96
+ onerror(caught instanceof Error ? caught : new Error(String(caught)));
97
+ if (res.headersSent)
98
+ res.destroy();
99
+ else
100
+ reply(res, 500, "Internal server error");
101
+ });
102
+ });
103
+ server.on("close", () => void mcp.close().catch(onerror));
104
+ return server;
105
+ }
106
+ /** The client's address: the socket's, or behind `trustProxy` proxies, the X-Forwarded-For entry the outermost one appended. */
107
+ function clientAddress(req, trustProxy) {
108
+ const socket = req.socket.remoteAddress ?? "";
109
+ if (trustProxy === 0)
110
+ return socket;
111
+ const header = req.headers["x-forwarded-for"];
112
+ const hops = (Array.isArray(header) ? header.join(",") : (header ?? ""))
113
+ .split(",")
114
+ .map((hop) => hop.trim())
115
+ .filter(Boolean);
116
+ // Earlier entries come from the client, which can write anything there.
117
+ const hop = hops[Math.max(0, hops.length - trustProxy)];
118
+ const address = hop === undefined ? "" : withoutPort(hop);
119
+ return isIP(address) ? address : socket;
120
+ }
121
+ /** The key of a client's limits: its IPv4 address, or the /64 network of an IPv6 one, which one host often holds whole. */
122
+ export function clientKey(address) {
123
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address)?.[1];
124
+ if (mapped)
125
+ return mapped;
126
+ if (isIP(address) !== 6)
127
+ return address;
128
+ const [head = "", tail] = address.split("::");
129
+ const left = head ? head.split(":") : [];
130
+ const right = tail ? tail.split(":") : [];
131
+ const groups = tail === undefined ? left : [...left, ...Array(Math.max(0, 8 - left.length - right.length)).fill("0"), ...right];
132
+ return `${groups
133
+ .slice(0, 4)
134
+ .map((group) => Number.parseInt(group, 16).toString(16))
135
+ .join(":")}::/64`;
136
+ }
137
+ function withoutPort(hop) {
138
+ if (hop.startsWith("["))
139
+ return hop.slice(1, hop.indexOf("]"));
140
+ const parts = hop.split(":");
141
+ return parts.length === 2 ? (parts[0] ?? "") : hop;
142
+ }
143
+ /** A token bucket and a count of requests in progress per client, and a count of all requests in progress. */
144
+ class Limits {
145
+ #buckets = new Map();
146
+ #perMinute;
147
+ #perClient;
148
+ #total;
149
+ #now;
150
+ #active = 0;
151
+ #sweepAt = 1024;
152
+ constructor(perMinute, perClient, total, now) {
153
+ this.#perMinute = perMinute;
154
+ this.#perClient = perClient;
155
+ this.#total = total;
156
+ this.#now = now;
157
+ }
158
+ /** Admits a request from `key` and returns the call that ends it, or the reason it is refused. */
159
+ admit(key) {
160
+ if (this.#active >= this.#total)
161
+ return {
162
+ status: 503,
163
+ retryAfter: 1,
164
+ message: `Service Unavailable: ${this.#total} requests in progress, the most this server takes`,
165
+ };
166
+ const now = this.#now();
167
+ let bucket = this.#buckets.get(key);
168
+ if (!bucket) {
169
+ this.#sweep(now);
170
+ bucket = { tokens: this.#perMinute, at: now, active: 0 };
171
+ this.#buckets.set(key, bucket);
172
+ }
173
+ bucket.tokens = this.#refilled(bucket, now);
174
+ bucket.at = now;
175
+ if (bucket.active >= this.#perClient)
176
+ return {
177
+ status: 429,
178
+ retryAfter: 1,
179
+ message: `Too Many Requests: ${bucket.active} requests from this address in progress, the most it may have`,
180
+ };
181
+ if (bucket.tokens < 1) {
182
+ const seconds = Math.ceil(((1 - bucket.tokens) * 60) / this.#perMinute);
183
+ return {
184
+ status: 429,
185
+ retryAfter: seconds,
186
+ message: `Too Many Requests: over ${this.#perMinute} a minute from this address, retry in ${seconds} seconds`,
187
+ };
188
+ }
189
+ bucket.tokens -= 1;
190
+ bucket.active++;
191
+ this.#active++;
192
+ const admitted = bucket;
193
+ let open = true;
194
+ return () => {
195
+ if (!open)
196
+ return;
197
+ open = false;
198
+ admitted.active--;
199
+ this.#active--;
200
+ };
201
+ }
202
+ #refilled(bucket, now) {
203
+ return Math.min(this.#perMinute, bucket.tokens + ((now - bucket.at) / 60_000) * this.#perMinute);
204
+ }
205
+ /** Forgets the idle clients whose bucket is full again, so the map stays as large as the recent clients. */
206
+ #sweep(now) {
207
+ if (this.#buckets.size < this.#sweepAt)
208
+ return;
209
+ for (const [key, bucket] of this.#buckets)
210
+ if (bucket.active === 0 && this.#refilled(bucket, now) >= this.#perMinute)
211
+ this.#buckets.delete(key);
212
+ this.#sweepAt = Math.max(1024, this.#buckets.size * 2);
213
+ }
214
+ }
215
+ function readBody(req, limit) {
216
+ return new Promise((resolve) => {
217
+ if (Number(req.headers["content-length"]) > limit)
218
+ return resolve("too large");
219
+ const chunks = [];
220
+ let size = 0;
221
+ const stop = (body) => {
222
+ req.off("data", onData).off("end", onEnd).off("close", onClose);
223
+ resolve(body);
224
+ };
225
+ const onData = (chunk) => {
226
+ size += chunk.length;
227
+ if (size <= limit)
228
+ return void chunks.push(chunk);
229
+ req.pause();
230
+ stop("too large");
231
+ };
232
+ const onEnd = () => stop(Buffer.concat(chunks));
233
+ const onClose = () => stop("gone");
234
+ req.on("data", onData).on("end", onEnd).on("close", onClose);
235
+ });
236
+ }
237
+ function headersOf(req) {
238
+ const headers = new Headers();
239
+ for (const [name, value] of Object.entries(req.headers)) {
240
+ for (const item of Array.isArray(value) ? value : value === undefined ? [] : [value])
241
+ headers.append(name, item);
242
+ }
243
+ return headers;
244
+ }
245
+ /** Writes a web Response to a Node one, its body streamed until it ends or the client leaves. */
246
+ async function send(res, response) {
247
+ response.headers.forEach((value, name) => {
248
+ res.setHeader(name, value);
249
+ });
250
+ res.writeHead(response.status);
251
+ if (!response.body)
252
+ return void res.end();
253
+ const reader = response.body.getReader();
254
+ const cancel = () => void reader.cancel().catch(() => undefined);
255
+ res.once("close", cancel);
256
+ try {
257
+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
258
+ if (!res.write(chunk.value))
259
+ await drained(res);
260
+ }
261
+ res.end();
262
+ }
263
+ finally {
264
+ res.off("close", cancel);
265
+ }
266
+ }
267
+ function drained(res) {
268
+ return new Promise((resolve) => {
269
+ const done = () => {
270
+ res.off("drain", done).off("close", done);
271
+ resolve();
272
+ };
273
+ res.on("drain", done).on("close", done);
274
+ });
275
+ }
276
+ function reply(res, status, message, headers = {}, id = null) {
277
+ // The body may be left unread, so the connection is not reused.
278
+ res.writeHead(status, { "Content-Type": "application/json", Connection: "close", ...headers });
279
+ res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: status === 500 ? -32603 : -32000, message }, id }));
280
+ }
281
+ function requestId(body) {
282
+ try {
283
+ const id = JSON.parse(body.toString("utf8"))?.id;
284
+ return typeof id === "string" || typeof id === "number" ? id : null;
285
+ }
286
+ catch {
287
+ return null;
288
+ }
289
+ }
@@ -1 +1 @@
1
- {"about":"The stable GET operations this toolkit builds on, and the MCP tools and Python methods that call each. check-manifest.mjs checks them against taoswap-api.json; each package's tests check its own column.","operations":{"/v2/subnets/":{"mcp":["list_subnets"],"python":["subnets"]},"/v2/subnets/{netuid}/":{"mcp":["get_subnet","prepare_trade","prepare_limit_order"],"python":["subnet"]},"/v2/subnets/{netuid}/history/":{"mcp":[],"python":["subnet_history"]},"/v2/subnets/{netuid}/validators/":{"mcp":["list_subnet_validators","prepare_trade"],"python":["subnet_validators"]},"/subnet-price-history/":{"mcp":["get_subnet_candles"],"python":["subnet_candles"]},"/price-history/":{"mcp":["get_tao_price"],"python":["tao_price"]},"/v2/validators/":{"mcp":["list_validators"],"python":["validators"]},"/v2/validators/{hotkey}/":{"mcp":["get_validator"],"python":["validator"]},"/v2/validators/{hotkey}/history/":{"mcp":[],"python":["validator_history"]},"/metagraph/{netuid}/":{"mcp":["get_metagraph"],"python":["metagraph"]},"/trades/":{"mcp":["list_trades"],"python":["trades"]},"/portfolio-balance/":{"mcp":["get_portfolio"],"python":["portfolio"]},"/portfolio-pnl-apy/":{"mcp":["get_portfolio_pnl"],"python":["portfolio_pnl"]},"/v1/account-ledger/":{"mcp":["get_account_ledger"],"python":["ledger"]},"/account-transactions/":{"mcp":["get_account_transactions"],"python":["transactions"]},"/search/":{"mcp":["search"],"python":["search"]},"/network-stats/":{"mcp":["get_network_stats"],"python":["network_stats"]}}}
1
+ {"about":"The stable GET operations this toolkit builds on, and the MCP tools and Python methods that call each. check-manifest.mjs checks them against taoswap-api.json; each package's tests check its own column.","operations":{"/v2/subnets/":{"mcp":["list_subnets"],"python":["subnets"]},"/v2/subnets/{netuid}/":{"mcp":["get_subnet","prepare_trade","prepare_limit_order"],"python":["subnet"]},"/v2/subnets/{netuid}/history/":{"mcp":["get_subnet_history"],"python":["subnet_history"]},"/v2/subnets/{netuid}/validators/":{"mcp":["list_subnet_validators","prepare_trade"],"python":["subnet_validators"]},"/subnet-price-history/":{"mcp":["get_subnet_candles"],"python":["subnet_candles"]},"/price-history/":{"mcp":["get_tao_price"],"python":["tao_price"]},"/v2/validators/":{"mcp":["list_validators"],"python":["validators"]},"/v2/validators/{hotkey}/":{"mcp":["get_validator"],"python":["validator"]},"/v2/validators/{hotkey}/history/":{"mcp":["get_validator_history"],"python":["validator_history"]},"/metagraph/{netuid}/":{"mcp":["get_metagraph"],"python":["metagraph"]},"/trades/":{"mcp":["list_trades"],"python":["trades"]},"/portfolio-balance/":{"mcp":["get_portfolio"],"python":["portfolio"]},"/portfolio-pnl-apy/":{"mcp":["get_portfolio_pnl"],"python":["portfolio_pnl"]},"/v1/account-ledger/":{"mcp":["get_account_ledger"],"python":["ledger"]},"/account-transactions/":{"mcp":["get_account_transactions"],"python":["transactions"]},"/search/":{"mcp":["search"],"python":["search"]},"/network-stats/":{"mcp":["get_network_stats"],"python":["network_stats"]}}}
@@ -0,0 +1,5 @@
1
+ import type { McpServer } from "@modelcontextprotocol/server";
2
+ /** The most hotkeys compare_validators takes: its table stays readable and its message short. */
3
+ export declare const MAX_HOTKEYS = 8;
4
+ /** Prompts that start an analysis: each names the tools to call and what to report, and makes no request itself. */
5
+ export declare function registerPrompts(server: McpServer): void;