taoswap-mcp 0.2.0 → 0.4.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,14 +4,20 @@ 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.4.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
 
14
- **Claude Code**
14
+ **By its URL**: `https://mcp.taoswap.org/mcp` is the server Taoswap runs, over Streamable HTTP, for clients that add a server by its URL, such as claude.ai custom connectors, Claude mobile and ChatGPT. In Claude Code:
15
+
16
+ ```sh
17
+ claude mcp add --transport http taoswap https://mcp.taoswap.org/mcp
18
+ ```
19
+
20
+ **Claude Code**, running the server on your machine:
15
21
 
16
22
  ```sh
17
23
  claude mcp add taoswap -- npx -y taoswap-mcp@latest
@@ -49,31 +55,36 @@ args = ["-y", "taoswap-mcp@latest"]
49
55
 
50
56
  All tools are read-only and call `https://api.taoswap.org` only; the four `prepare_` tools sign nothing and send nothing.
51
57
 
52
- | Tool | Answers | API operation |
53
- | -------------------------- | ----------------------------------------------------------------------- | -------------------------------------- |
54
- | `list_subnets` | Every subnet with price, market cap, emission and volume, sortable here | `GET /v2/subnets/` |
55
- | `get_subnet` | One subnet: identity, price, pools, emission, burn, holders, dereg risk | `GET /v2/subnets/{netuid}/` |
56
- | `get_subnet_candles` | OHLCV candles of a subnet's alpha price | `GET /subnet-price-history/` |
57
- | `get_tao_price` | Daily TAO price in USD or EUR | `GET /price-history/` |
58
- | `list_validators` | Validators with take, root and alpha yields, stake and delegators | `GET /v2/validators/` |
59
- | `get_validator` | One validator, its subnets, history and delegators | `GET /v2/validators/{hotkey}/` |
60
- | `list_subnet_validators` | A subnet's validators with their yields | `GET /v2/subnets/{netuid}/validators/` |
61
- | `get_metagraph` | A subnet's neurons: stake, vtrust, incentive, dividends, rewards | `GET /metagraph/{netuid}/` |
62
- | `get_portfolio` | A coldkey's balance per day | `GET /portfolio-balance/` |
63
- | `get_portfolio_pnl` | A coldkey's APY and realized and unrealized PnL | `GET /portfolio-pnl-apy/` |
64
- | `get_account_ledger` | A coldkey's TAO and alpha movements | `GET /v1/account-ledger/` |
65
- | `get_account_transactions` | A coldkey's stake operations and TAO transfers | `GET /account-transactions/` |
66
- | `list_trades` | Buys and sells against the subnet pools, filterable | `GET /trades/` |
67
- | `search` | Blocks, extrinsics, subnets, validators and accounts | `GET /search/` |
68
- | `get_network_stats` | How the network's TAO splits between root, pools and free balances | `GET /network-stats/` |
69
- | `list_api_operations` | Every GET operation, or one with its parameters and each field's unit | the bundled schema, no request |
70
- | `call_api` | Any other GET operation of the schema, on the pinned host | the path you pass |
71
- | `prepare_trade` | A taoswap.org link to stake, unstake or swap between subnets | the subnets and validators, to check |
72
- | `prepare_limit_order` | A taoswap.org link to place a limit buy, take-profit or stop-loss | `GET /v2/subnets/{netuid}/`, to check |
73
- | `prepare_transfer` | A taoswap.org link to send TAO | no request |
74
- | `prepare_new_wallet` | The taoswap.org link that creates a wallet in the user's browser | no request |
75
-
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.
58
+ | Tool | Answers | API operation |
59
+ | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
60
+ | `list_subnets` | Every subnet with price, market cap, emission and volume, sortable here | `GET /v2/subnets/` |
61
+ | `get_subnet` | One subnet: identity, price, pools, emission, burn, holders, dereg risk | `GET /v2/subnets/{netuid}/` |
62
+ | `get_subnet_candles` | OHLCV candles of a subnet's alpha price | `GET /subnet-price-history/` |
63
+ | `get_subnet_history` | A subnet's emissions, pool reserves, price, holders and burns per day | `GET /v2/subnets/{netuid}/history/` |
64
+ | `get_tao_price` | Daily TAO price in USD or EUR | `GET /price-history/` |
65
+ | `list_validators` | Validators with take, root and alpha yields, stake and delegators | `GET /v2/validators/` |
66
+ | `get_validator` | One validator, its subnets, history and delegators | `GET /v2/validators/{hotkey}/` |
67
+ | `get_validator_history` | A validator's root and alpha stake and its delegator counts per day | `GET /v2/validators/{hotkey}/history/` |
68
+ | `list_subnet_validators` | A subnet's validators with their yields | `GET /v2/subnets/{netuid}/validators/` |
69
+ | `get_metagraph` | A subnet's neurons: stake, vtrust, incentive, dividends, rewards | `GET /metagraph/{netuid}/` |
70
+ | `get_portfolio` | A coldkey's balance per day | `GET /portfolio-balance/` |
71
+ | `get_portfolio_pnl` | A coldkey's APY and realized and unrealized PnL | `GET /portfolio-pnl-apy/` |
72
+ | `get_account_ledger` | A coldkey's TAO and alpha movements | `GET /v1/account-ledger/` |
73
+ | `get_account_transactions` | A coldkey's stake operations and TAO transfers | `GET /account-transactions/` |
74
+ | `list_trades` | Buys and sells against the subnet pools, filterable | `GET /trades/` |
75
+ | `search` | Subnets, validators, coldkeys, blocks and extrinsics by name, number or address, and the collections a question needs, as ids, titles and taoswap.org pages | `GET /search/` |
76
+ | `fetch` | One search result whole: a subnet, a validator, a coldkey's balances, a block, an extrinsic or a collection | the operation that serves it |
77
+ | `get_network_stats` | How the network's TAO splits between root, pools and free balances | `GET /network-stats/` |
78
+ | `list_api_operations` | Every GET operation, or one with its parameters and each field's unit | the bundled schema, no request |
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 |
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
+ | `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 |
84
+
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
+
87
+ `search` and `fetch` answer in the shape that ChatGPT's deep research and company knowledge read. `search` takes one `query` and returns `results`, each an `id`, a `title` and the taoswap.org page to cite; `fetch` takes one of those ids and returns the document's `title`, `url`, `text` and `metadata.api_url`, as structured content and as the same JSON in its text. A query that the API's search does not find whole is searched by its terms (addresses, hashes, netuids, then names), and a question about subnets, validators, the TAO price or the network adds the matching collection.
77
88
 
78
89
  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
90
 
@@ -92,6 +103,26 @@ Amounts are in the sold asset: TAO to stake or to buy with a limit order, alpha
92
103
 
93
104
  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
105
 
106
+ ## Prompts
107
+
108
+ 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.
109
+
110
+ | Prompt | Arguments | Asks for |
111
+ | -------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
112
+ | `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` |
113
+ | `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` |
114
+ | `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 |
115
+
116
+ Clients that complete arguments suggest a netuid from its first digits or from its subnet's name. 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.
117
+
118
+ ## Resources
119
+
120
+ The server lists three kinds of resources, which clients such as Claude Code (`@taoswap:taoswap://guide`) attach to the conversation without a tool call:
121
+
122
+ - `taoswap://guide`: what to know before writing code against the API, from units and identifiers to pagination, limits, freshness and stability;
123
+ - `taoswap://operations`: every GET operation, with its rate limit and whether it is stable;
124
+ - `taoswap://operations/{operationId}`: one operation's parameters and response fields with their units, listed for the stable operations and completed for all of them.
125
+
95
126
  ## Link to Taoswap
96
127
 
97
128
  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 +133,53 @@ The server paces itself to 4 requests a second and 4 at once, below the API's pe
102
133
 
103
134
  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
135
 
136
+ ## Remote (HTTP)
137
+
138
+ `--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 one at `https://mcp.taoswap.org/mcp`, with the settings below behind its own proxy; to run your own:
139
+
140
+ ```sh
141
+ npx -y taoswap-mcp@latest --http # http://127.0.0.1:8080/mcp
142
+ npx -y taoswap-mcp@latest --http --host 0.0.0.0 --port 3000
143
+ ```
144
+
145
+ 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`.
146
+
147
+ ```sh
148
+ docker build -t taoswap-mcp .
149
+ docker run --rm -i taoswap-mcp # stdio
150
+ docker run --rm -p 127.0.0.1:8080:8080 taoswap-mcp --http # http://127.0.0.1:8080/mcp
151
+ ```
152
+
153
+ 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"}`. A browser that opens `/` or `/mcp` gets a short page on adding the server instead, since people open the URL wherever it is shared. 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.
154
+
155
+ 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:
156
+
157
+ - 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;
158
+ - 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;
159
+ - 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;
160
+ - 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
+ - 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
+
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 |
177
+
178
+ `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
+
105
180
  ## Use from code
106
181
 
107
- `createServer()` builds the server without a transport, so it can be served over stdio, as the command does, or over HTTP:
182
+ `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
183
 
109
184
  ```ts
110
185
  import { createServer } from "taoswap-mcp";
package/dist/catalog.d.ts CHANGED
@@ -23,6 +23,7 @@ export interface ApiParameter {
23
23
  }
24
24
  export interface ApiOperation {
25
25
  path: string;
26
+ operationId: string;
26
27
  summary: string;
27
28
  description: string;
28
29
  tag: string;
package/dist/catalog.js CHANGED
@@ -57,6 +57,7 @@ export function indexOperations(schema, manifest) {
57
57
  const tags = Array.isArray(get.tags) ? get.tags : [];
58
58
  operations.push({
59
59
  path,
60
+ operationId: String(get.operationId ?? ""),
60
61
  summary: oneLine(get.summary, 120),
61
62
  description: String(get.description ?? ""),
62
63
  tag: String(tags[0] ?? ""),
package/dist/cli.js CHANGED
@@ -1,21 +1,156 @@
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 { Metrics } from "./metrics.js";
8
+ import { createServer, defaultClient, MIN_MAX_CHARS, VERSION } from "./server.js";
9
+ import { UPSTREAM_DEFAULTS, Upstream, upstreamClient } from "./upstream.js";
10
+ /** At 4 requests a second, a request queued behind this many starts within the client's 20-second timeout. */
11
+ const MAX_QUEUE_LIMIT = 60;
12
+ 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
13
  const args = process.argv.slice(2);
5
14
  if (args.includes("--version")) {
6
15
  console.log(VERSION);
7
16
  process.exit(0);
8
17
  }
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.
18
+ const help = `taoswap-mcp ${VERSION}: MCP server for the Taoswap Bittensor API (https://api.taoswap.org).
11
19
 
12
- Usage: npx -y taoswap-mcp@latest
20
+ Usage:
21
+ npx -y taoswap-mcp@latest serves MCP over stdio, to the client that starts it
22
+ npx -y taoswap-mcp@latest --http serves MCP over Streamable HTTP at /mcp, without sessions, and GET /healthz
23
+ --port <port> or TAOSWAP_MCP_PORT: ${HTTP_DEFAULTS.port} by default, 0 for any free port
24
+ --host <address> or TAOSWAP_MCP_HOST: ${HTTP_DEFAULTS.host} by default
13
25
 
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
- });
26
+ Environment:
27
+ TAOSWAP_MCP_MAX_CHARS caps the length of a tool answer (40000 by default, ${MIN_MAX_CHARS} at least)
28
+
29
+ With --http:
30
+ TAOSWAP_MCP_TRUST_PROXY reverse proxies in front, each appending to X-Forwarded-For (0: the header is ignored)
31
+ TAOSWAP_MCP_ALLOWED_HOSTS Host names accepted, comma-separated, or * (localhost names on a loopback host, else any)
32
+ TAOSWAP_MCP_ALLOWED_ORIGINS browser Origin names accepted, comma-separated (localhost names)
33
+ TAOSWAP_MCP_RATE_PER_IP requests a minute per client address (${HTTP_DEFAULTS.ratePerIp})
34
+ TAOSWAP_MCP_CONCURRENT_PER_IP requests at once per client address (${HTTP_DEFAULTS.concurrentPerIp})
35
+ TAOSWAP_MCP_CONCURRENT requests at once in all (${HTTP_DEFAULTS.concurrent})
36
+ TAOSWAP_MCP_TIMEOUT seconds a request may take, its answer included (${HTTP_DEFAULTS.timeoutSeconds})
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
+ TAOSWAP_MCP_CACHE_MB megabytes of API answers kept in memory (${UPSTREAM_DEFAULTS.maxBytes / 1024 / 1024})
39
+ TAOSWAP_MCP_METRICS 1 serves Prometheus counters at GET /metrics, which a proxy should keep private (0)
40
+ A request body is ${MAX_BODY_BYTES / 1024} KiB at most.`;
41
+ const flags = (() => {
42
+ try {
43
+ const options = { help: { type: "boolean" }, http: { type: "boolean" }, port: { type: "string" }, host: { type: "string" } };
44
+ return parseArgs({ args, options }).values;
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ })();
50
+ if (!flags || flags.help) {
51
+ console.log(help);
52
+ process.exit(flags ? 0 : 2);
53
+ }
54
+ const rawMaxChars = process.env.TAOSWAP_MCP_MAX_CHARS?.trim() ?? "";
55
+ const maxChars = rawMaxChars === "" ? undefined : Number(rawMaxChars);
56
+ if (maxChars !== undefined && (!Number.isInteger(maxChars) || maxChars < MIN_MAX_CHARS)) {
57
+ console.error(`taoswap-mcp: TAOSWAP_MCP_MAX_CHARS must be a whole number of characters, ${MIN_MAX_CHARS} or more: got ${rawMaxChars}`);
58
+ process.exit(2);
59
+ }
60
+ if (!flags.http) {
61
+ if (flags.port !== undefined || flags.host !== undefined)
62
+ fail("--port and --host serve HTTP: add --http");
63
+ const client = defaultClient();
64
+ serveStdio(() => createServer({ client, ...(maxChars ? { maxChars } : {}) }), {
65
+ onerror: (error) => console.error(`taoswap-mcp: ${error.message}`),
66
+ });
67
+ }
68
+ else {
69
+ serveHttp();
70
+ }
71
+ function serveHttp() {
72
+ const env = process.env;
73
+ const port = whole(...pick("--port", flags?.port, "TAOSWAP_MCP_PORT"), HTTP_DEFAULTS.port, 0, 65_535);
74
+ const [hostName, rawHost] = pick("--host", flags?.host, "TAOSWAP_MCP_HOST");
75
+ const host = rawHost?.trim() || HTTP_DEFAULTS.host;
76
+ if (!isHostName(host) || host.startsWith("["))
77
+ fail(`${hostName} must be an IP address or a host name: got ${host}`);
78
+ const loopback = host === "localhost" || host === "::1" || (isIP(host) === 4 && host.startsWith("127."));
79
+ const rawHosts = env.TAOSWAP_MCP_ALLOWED_HOSTS?.trim() ?? "";
80
+ const allowedHosts = rawHosts === ""
81
+ ? loopback
82
+ ? localhostAllowedHostnames()
83
+ : undefined
84
+ : rawHosts === "*"
85
+ ? undefined
86
+ : hostList("TAOSWAP_MCP_ALLOWED_HOSTS", rawHosts);
87
+ const rawOrigins = env.TAOSWAP_MCP_ALLOWED_ORIGINS?.trim() ?? "";
88
+ const allowedOrigins = rawOrigins === "" ? undefined : hostList("TAOSWAP_MCP_ALLOWED_ORIGINS", rawOrigins);
89
+ const trustProxy = whole("TAOSWAP_MCP_TRUST_PROXY", env.TAOSWAP_MCP_TRUST_PROXY, 0, 0, 10);
90
+ const ratePerIp = whole("TAOSWAP_MCP_RATE_PER_IP", env.TAOSWAP_MCP_RATE_PER_IP, HTTP_DEFAULTS.ratePerIp, 1, 1_000_000);
91
+ const concurrentPerIp = whole("TAOSWAP_MCP_CONCURRENT_PER_IP", env.TAOSWAP_MCP_CONCURRENT_PER_IP, HTTP_DEFAULTS.concurrentPerIp, 1, 100_000);
92
+ const concurrent = whole("TAOSWAP_MCP_CONCURRENT", env.TAOSWAP_MCP_CONCURRENT, HTTP_DEFAULTS.concurrent, 1, 100_000);
93
+ const timeout = whole("TAOSWAP_MCP_TIMEOUT", env.TAOSWAP_MCP_TIMEOUT, HTTP_DEFAULTS.timeoutSeconds, 1, 3600);
94
+ const maxQueued = whole("TAOSWAP_MCP_MAX_QUEUE", env.TAOSWAP_MCP_MAX_QUEUE, UPSTREAM_DEFAULTS.maxQueued, 0, MAX_QUEUE_LIMIT);
95
+ 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 client = upstreamClient(new Upstream({ maxQueued, maxBytes: cacheMb * 1024 * 1024, ...(metrics ? { metrics } : {}) }));
98
+ const server = createHttpServer({
99
+ factory: () => createServer({ client, ...(maxChars ? { maxChars } : {}), ...(metrics ? { metrics } : {}) }),
100
+ trustProxy,
101
+ ...(allowedHosts ? { allowedHosts } : {}),
102
+ ...(allowedOrigins ? { allowedOrigins } : {}),
103
+ ratePerIp,
104
+ concurrentPerIp,
105
+ concurrent,
106
+ timeoutMs: timeout * 1000,
107
+ onerror: (error) => console.error(`taoswap-mcp: ${error.message}`),
108
+ ...(metrics ? { metrics } : {}),
109
+ });
110
+ server.on("error", (error) => {
111
+ console.error(`taoswap-mcp: cannot serve HTTP on ${host} port ${port}: ${error.message}`);
112
+ process.exit(1);
113
+ });
114
+ server.listen(port, host, () => {
115
+ const bound = server.address();
116
+ const at = bound.family === "IPv6" ? `[${bound.address}]` : bound.address;
117
+ console.error(`taoswap-mcp ${VERSION}: MCP over Streamable HTTP at http://${at}:${bound.port}/mcp, health at /healthz${metrics ? ", metrics at /metrics" : ""}`);
118
+ });
119
+ const stop = () => {
120
+ server.close(() => process.exit(0));
121
+ setTimeout(() => process.exit(0), 10_000).unref();
122
+ };
123
+ process.once("SIGTERM", stop);
124
+ process.once("SIGINT", stop);
125
+ }
126
+ /** The flag when given, else the environment variable, with the name to report it under. */
127
+ function pick(flag, value, variable) {
128
+ return value !== undefined ? [flag, value] : [variable, process.env[variable]];
129
+ }
130
+ function whole(name, raw, fallback, min, max) {
131
+ const text = raw?.trim() ?? "";
132
+ if (text === "")
133
+ return fallback;
134
+ const value = Number(text);
135
+ if (!Number.isInteger(value) || value < min || value > max)
136
+ fail(`${name} must be a whole number from ${min} to ${max}: got ${text}`);
137
+ return value;
138
+ }
139
+ function isHostName(entry) {
140
+ return isIP(entry) !== 0 || (entry.startsWith("[") && entry.endsWith("]") && isIP(entry.slice(1, -1)) === 6) || HOST_NAME.test(entry);
141
+ }
142
+ /** Host names as the SDK compares them: lowercase, without scheme or port, IPv6 in brackets. */
143
+ function hostList(name, raw) {
144
+ const entries = raw
145
+ .split(",")
146
+ .map((entry) => entry.trim().toLowerCase())
147
+ .filter(Boolean);
148
+ const wrong = entries.find((entry) => !isHostName(entry) || isIP(entry) === 6);
149
+ if (entries.length === 0 || wrong !== undefined)
150
+ fail(`${name} must list host names, comma-separated, without scheme or port and IPv6 in brackets: got ${wrong ?? raw}`);
151
+ return entries;
152
+ }
153
+ function fail(message) {
154
+ console.error(`taoswap-mcp: ${message}`);
155
+ process.exit(2);
156
+ }
@@ -0,0 +1,63 @@
1
+ import type { QueryValue } from "taoswap";
2
+ import { z } from "zod";
3
+ import type { ShapeOptions } from "./shape.ts";
4
+ /** The pages that search results and fetched documents point to, which ChatGPT cites. */
5
+ export declare const SITE = "https://taoswap.org";
6
+ /** Hits kept from the API's search, and API calls one search makes at most. */
7
+ export declare const MAX_RESULTS = 10;
8
+ export declare const MAX_LOOKUPS = 4;
9
+ export interface SearchResult {
10
+ id: string;
11
+ title: string;
12
+ url: string;
13
+ }
14
+ /** What `fetch` reads for one document id, and how the answer gives its title and page. */
15
+ export interface DocumentSource {
16
+ path: string;
17
+ query: Record<string, QueryValue>;
18
+ shape?: ShapeOptions;
19
+ /** The part of the answer that is the document, undefined when the answer holds none. */
20
+ pick?(data: unknown): unknown;
21
+ title(item: unknown): string;
22
+ url(item: unknown): string;
23
+ }
24
+ export declare const searchInput: z.ZodObject<{
25
+ query: z.ZodString;
26
+ }, z.core.$strict>;
27
+ export declare const searchOutput: z.ZodObject<{
28
+ results: z.ZodArray<z.ZodObject<{
29
+ id: z.ZodString;
30
+ title: z.ZodString;
31
+ url: z.ZodString;
32
+ }, z.core.$strip>>;
33
+ }, z.core.$strip>;
34
+ export declare const fetchInput: z.ZodObject<{
35
+ id: z.ZodString;
36
+ }, z.core.$strict>;
37
+ export declare const fetchOutput: z.ZodObject<{
38
+ id: z.ZodString;
39
+ title: z.ZodString;
40
+ text: z.ZodString;
41
+ url: z.ZodString;
42
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
43
+ }, z.core.$strip>;
44
+ /** Text written on chain, made fit for a title: one line, without control characters, at most 60 characters. */
45
+ export declare function label(text: string | undefined): string | undefined;
46
+ /** The terms worth a search of their own, most specific first: addresses, hashes, numbers, then words. */
47
+ export declare function searchTerms(query: string): string[];
48
+ /** One hit of GET /search/ as a search result, or undefined for a hit not worth a document. */
49
+ export declare function resultOf(hit: unknown, term: string): SearchResult | undefined;
50
+ /**
51
+ * Search results for a query, in the shape ChatGPT's deep research reads: the API's search on the whole query, then on its
52
+ * terms when the whole finds nothing, then the collections its words name, or all of them when nothing else matched.
53
+ */
54
+ export declare function searchDocuments(query: string, lookup: (term: string) => Promise<unknown[]>): Promise<SearchResult[]>;
55
+ /** The hits of a /search/ answer. */
56
+ export declare function hitsOf(data: unknown): unknown[];
57
+ /** What `fetch` reads for an id that `search` returns, or undefined for any other id. */
58
+ export declare function documentSource(id: string): DocumentSource | undefined;
59
+ /** The operations of openapi/manifest.json that each tool reads. */
60
+ export declare const DOCUMENT_OPERATIONS: {
61
+ readonly search: readonly ["/search/"];
62
+ readonly fetch: string[];
63
+ };