@polytest/mcp 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +107 -2
- package/dist/budget.d.ts +46 -0
- package/dist/budget.js +93 -0
- package/dist/failures.d.ts +10 -0
- package/dist/failures.js +113 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/instructions.d.ts +1 -0
- package/dist/instructions.js +16 -0
- package/dist/series.d.ts +33 -0
- package/dist/series.js +143 -0
- package/dist/server.d.ts +4 -0
- package/dist/server.js +27 -0
- package/dist/stdio.d.ts +2 -0
- package/dist/stdio.js +5 -0
- package/dist/tools.d.ts +22 -0
- package/dist/tools.js +292 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/package.json +45 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 omnilabss
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,108 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @polytest/mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An MCP server for the [PolyTest](https://www.polytest.io) API. It lets an MCP client read historical data for Polymarket crypto Up/Down markets: the markets, their price snapshots, and their order books. Every tool is read-only.
|
|
4
|
+
|
|
5
|
+
## Hosted server
|
|
6
|
+
|
|
7
|
+
The server runs at `https://mcp.polytest.io/mcp` over Streamable HTTP. There are two ways to authenticate.
|
|
8
|
+
|
|
9
|
+
Sign in with your PolyTest account. If your client supports OAuth, add the URL with no header. In Claude Code, run `/mcp`, select `polytest` and choose Authenticate, or run `claude mcp login polytest` in a terminal, from the folder where you added the server. Other clients ask you to sign in when they connect or the first time they call a tool. Your browser opens and you approve the connection. Until you sign in, a client can list the tools but not call them.
|
|
10
|
+
|
|
11
|
+
Send an API key. Add the header `Authorization: Bearer <key>`. Create a key at https://www.polytest.io/app/keys.
|
|
12
|
+
|
|
13
|
+
## Tools
|
|
14
|
+
|
|
15
|
+
| Tool | What it returns | API requests |
|
|
16
|
+
| --- | --- | --- |
|
|
17
|
+
| `polytest_list_markets` | Markets of one type for one coin, newest first. | 1 |
|
|
18
|
+
| `polytest_get_market` | One market, by market id or by Polymarket slug. | 1 |
|
|
19
|
+
| `polytest_get_snapshots` | Snapshots of one market, oldest first. Order books are optional. | 1 |
|
|
20
|
+
| `polytest_get_limits` | The plan behind your credential: rate limits, data access, and trial budget. | 1 |
|
|
21
|
+
| `polytest_get_price_series` | Evenly spaced price points across one market. | 1 + `samples`. `samples` is 20 by default, so 21 |
|
|
22
|
+
|
|
23
|
+
## The data
|
|
24
|
+
|
|
25
|
+
- Coins are btc, eth and sol for 5m, 15m and 1hr markets. 4hr and 24hr markets are btc only.
|
|
26
|
+
- `price_up` and `price_down` are the lowest asks on each side's order book, from 0 to 1. They usually add up to a little more than 1.
|
|
27
|
+
- PolyTest loads new markets in batches, so the newest data can be hours old. Each market row has a `status` of `upcoming`, `open`, `resolved` or `ended_no_result`, and `polytest_list_markets` adds a note when its newest market started hours ago.
|
|
28
|
+
- `polytest_get_limits` returns `trial_budget`, the total a free trial may use over its 3 days. It applies only during a trial and doesn't show what's left.
|
|
29
|
+
|
|
30
|
+
## Plan limits
|
|
31
|
+
|
|
32
|
+
Tool calls count against your plan limits the same way direct API calls do. Rate limits are per key, so a key shared between an MCP client and your own code shares one rate limit. Create a dedicated key for MCP use.
|
|
33
|
+
|
|
34
|
+
## Setup
|
|
35
|
+
|
|
36
|
+
Most of these snippets read the key from the `POLYTEST_KEY` environment variable. Claude Desktop takes the key in its config file.
|
|
37
|
+
|
|
38
|
+
### Claude Code
|
|
39
|
+
|
|
40
|
+
Sign in:
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
claude mcp add --transport http polytest https://mcp.polytest.io/mcp
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
API key:
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
claude mcp add --transport http polytest https://mcp.polytest.io/mcp --header "Authorization: Bearer $POLYTEST_KEY"
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Local server:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
claude mcp add --transport stdio --env POLYTEST_KEY=$POLYTEST_KEY polytest -- npx -y @polytest/mcp
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Cursor
|
|
59
|
+
|
|
60
|
+
In `~/.cursor/mcp.json`:
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{"mcpServers":{"polytest":{"url":"https://mcp.polytest.io/mcp","headers":{"Authorization":"Bearer ${env:POLYTEST_KEY}"}}}}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### VS Code
|
|
67
|
+
|
|
68
|
+
In `.mcp.json`:
|
|
69
|
+
|
|
70
|
+
```json
|
|
71
|
+
{"mcpServers":{"polytest":{"type":"http","url":"https://mcp.polytest.io/mcp","headers":{"Authorization":"Bearer ${POLYTEST_KEY}"}}}}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Codex
|
|
75
|
+
|
|
76
|
+
In `~/.codex/config.toml`:
|
|
77
|
+
|
|
78
|
+
```toml
|
|
79
|
+
[mcp_servers.polytest]
|
|
80
|
+
url = "https://mcp.polytest.io/mcp"
|
|
81
|
+
bearer_token_env_var = "POLYTEST_KEY"
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### Gemini CLI
|
|
85
|
+
|
|
86
|
+
```sh
|
|
87
|
+
gemini mcp add --transport http --header "Authorization: Bearer $POLYTEST_KEY" polytest https://mcp.polytest.io/mcp
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Claude Desktop
|
|
91
|
+
|
|
92
|
+
In `claude_desktop_config.json`:
|
|
93
|
+
|
|
94
|
+
```json
|
|
95
|
+
{"mcpServers":{"polytest":{"command":"npx","args":["-y","@polytest/mcp"],"env":{"POLYTEST_KEY":"pt_live_..."}}}}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Local use
|
|
99
|
+
|
|
100
|
+
`npx -y @polytest/mcp` starts the same server on stdio. It reads the API key from `POLYTEST_KEY`. Without a key the server still starts, and each tool call returns an error that says how to set one.
|
|
101
|
+
|
|
102
|
+
## Docs
|
|
103
|
+
|
|
104
|
+
https://www.polytest.io/docs/mcp
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
MIT
|
package/dist/budget.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Market, OrderLevel, Snapshot, SnapshotWithBooks } from "@polytest/sdk";
|
|
2
|
+
export declare const MAX_OUTPUT_CHARS = 16000;
|
|
3
|
+
export type MarketStatus = "upcoming" | "open" | "resolved" | "ended_no_result";
|
|
4
|
+
export declare function marketStatus(market: Pick<Market, "start_time" | "end_time" | "winner">, nowMs: number): MarketStatus;
|
|
5
|
+
export type MarketRow = {
|
|
6
|
+
market_id: string;
|
|
7
|
+
slug: string;
|
|
8
|
+
market_type: string;
|
|
9
|
+
coin: string;
|
|
10
|
+
start_time: string;
|
|
11
|
+
end_time: string;
|
|
12
|
+
price_start: number | null;
|
|
13
|
+
price_end: number | null;
|
|
14
|
+
winner: string | null;
|
|
15
|
+
final_volume: number | null;
|
|
16
|
+
resolved_at: string | null;
|
|
17
|
+
status: MarketStatus;
|
|
18
|
+
};
|
|
19
|
+
export type MarketDetail = MarketRow & {
|
|
20
|
+
event_id: string;
|
|
21
|
+
final_liquidity: number | null;
|
|
22
|
+
condition_id: string | null;
|
|
23
|
+
clob_token_up: string | null;
|
|
24
|
+
clob_token_down: string | null;
|
|
25
|
+
created_at: string | null;
|
|
26
|
+
updated_at: string | null;
|
|
27
|
+
};
|
|
28
|
+
export type Book = {
|
|
29
|
+
bids: OrderLevel[];
|
|
30
|
+
asks: OrderLevel[];
|
|
31
|
+
};
|
|
32
|
+
export type SnapshotRow = {
|
|
33
|
+
time: string;
|
|
34
|
+
spot_price: number | null;
|
|
35
|
+
price_up: number | null;
|
|
36
|
+
price_down: number | null;
|
|
37
|
+
orderbook_up?: Book | null;
|
|
38
|
+
orderbook_down?: Book | null;
|
|
39
|
+
};
|
|
40
|
+
export declare function projectMarketRow(market: Market, nowMs: number): MarketRow;
|
|
41
|
+
export declare function projectMarket(market: Market, nowMs: number): MarketDetail;
|
|
42
|
+
export declare function projectSnapshot(snapshot: Snapshot | SnapshotWithBooks, depth: number | null): SnapshotRow;
|
|
43
|
+
export declare function fitRows<T>(rows: readonly T[], maxChars: number): {
|
|
44
|
+
rows: T[];
|
|
45
|
+
truncated: boolean;
|
|
46
|
+
};
|
package/dist/budget.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export const MAX_OUTPUT_CHARS = 16_000;
|
|
2
|
+
export function marketStatus(market, nowMs) {
|
|
3
|
+
if (market.winner)
|
|
4
|
+
return "resolved";
|
|
5
|
+
if (nowMs < Date.parse(market.start_time))
|
|
6
|
+
return "upcoming";
|
|
7
|
+
if (nowMs < Date.parse(market.end_time))
|
|
8
|
+
return "open";
|
|
9
|
+
return "ended_no_result";
|
|
10
|
+
}
|
|
11
|
+
// The SDK checks only market_id and slug on a market, and id, market_id, and time on a snapshot.
|
|
12
|
+
// A nullable field the server left out arrives as undefined, which the output schema would reject.
|
|
13
|
+
export function projectMarketRow(market, nowMs) {
|
|
14
|
+
return {
|
|
15
|
+
market_id: market.market_id,
|
|
16
|
+
slug: market.slug,
|
|
17
|
+
market_type: market.market_type,
|
|
18
|
+
coin: market.coin,
|
|
19
|
+
start_time: market.start_time,
|
|
20
|
+
end_time: market.end_time,
|
|
21
|
+
price_start: market.price_start ?? null,
|
|
22
|
+
price_end: market.price_end ?? null,
|
|
23
|
+
winner: market.winner ?? null,
|
|
24
|
+
final_volume: market.final_volume ?? null,
|
|
25
|
+
resolved_at: market.resolved_at ?? null,
|
|
26
|
+
status: marketStatus(market, nowMs),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export function projectMarket(market, nowMs) {
|
|
30
|
+
return {
|
|
31
|
+
market_id: market.market_id,
|
|
32
|
+
event_id: market.event_id,
|
|
33
|
+
slug: market.slug,
|
|
34
|
+
market_type: market.market_type,
|
|
35
|
+
coin: market.coin,
|
|
36
|
+
start_time: market.start_time,
|
|
37
|
+
end_time: market.end_time,
|
|
38
|
+
price_start: market.price_start ?? null,
|
|
39
|
+
price_end: market.price_end ?? null,
|
|
40
|
+
winner: market.winner ?? null,
|
|
41
|
+
final_volume: market.final_volume ?? null,
|
|
42
|
+
final_liquidity: market.final_liquidity ?? null,
|
|
43
|
+
condition_id: market.condition_id ?? null,
|
|
44
|
+
clob_token_up: market.clob_token_up ?? null,
|
|
45
|
+
clob_token_down: market.clob_token_down ?? null,
|
|
46
|
+
resolved_at: market.resolved_at ?? null,
|
|
47
|
+
created_at: market.created_at ?? null,
|
|
48
|
+
updated_at: market.updated_at ?? null,
|
|
49
|
+
status: marketStatus(market, nowMs),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function trimSide(levels, depth, direction) {
|
|
53
|
+
return levels
|
|
54
|
+
.map((level) => ({ price: level.price, size: level.size }))
|
|
55
|
+
.sort((a, b) => direction * (a.price - b.price))
|
|
56
|
+
.slice(0, depth);
|
|
57
|
+
}
|
|
58
|
+
function trimBook(book, depth) {
|
|
59
|
+
if (book === null || book === undefined)
|
|
60
|
+
return null;
|
|
61
|
+
return {
|
|
62
|
+
bids: trimSide(book.bids, depth, -1),
|
|
63
|
+
asks: trimSide(book.asks, depth, 1),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
export function projectSnapshot(snapshot, depth) {
|
|
67
|
+
const row = {
|
|
68
|
+
time: snapshot.time,
|
|
69
|
+
spot_price: snapshot.spot_price ?? null,
|
|
70
|
+
price_up: snapshot.price_up ?? null,
|
|
71
|
+
price_down: snapshot.price_down ?? null,
|
|
72
|
+
};
|
|
73
|
+
if (depth === null)
|
|
74
|
+
return row;
|
|
75
|
+
// Snapshot's index signature types both books as unknown.
|
|
76
|
+
const books = snapshot;
|
|
77
|
+
row.orderbook_up = trimBook(books.orderbook_up, depth);
|
|
78
|
+
row.orderbook_down = trimBook(books.orderbook_down, depth);
|
|
79
|
+
return row;
|
|
80
|
+
}
|
|
81
|
+
export function fitRows(rows, maxChars) {
|
|
82
|
+
// JSON.stringify of an array is "[" + the rows joined by "," + "]".
|
|
83
|
+
let used = 2;
|
|
84
|
+
let kept = 0;
|
|
85
|
+
for (const row of rows) {
|
|
86
|
+
const next = used + JSON.stringify(row).length + (kept > 0 ? 1 : 0);
|
|
87
|
+
if (next > maxChars)
|
|
88
|
+
break;
|
|
89
|
+
used = next;
|
|
90
|
+
kept += 1;
|
|
91
|
+
}
|
|
92
|
+
return { rows: rows.slice(0, kept), truncated: kept < rows.length };
|
|
93
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type Failure } from "@polytest/sdk";
|
|
2
|
+
export type Entry = "stdio" | "http_key" | "oauth";
|
|
3
|
+
export declare function explainFailure(failure: Failure, entry: Entry): string;
|
|
4
|
+
export declare function explainError(error: unknown, entry: Entry): string;
|
|
5
|
+
export type RetryOptions = {
|
|
6
|
+
sleep?: (ms: number) => Promise<void>;
|
|
7
|
+
random?: () => number;
|
|
8
|
+
};
|
|
9
|
+
export declare function sleep(ms: number): Promise<void>;
|
|
10
|
+
export declare function withRetry<T>(work: () => Promise<T>, opts?: RetryOptions): Promise<T>;
|
package/dist/failures.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { isRetryable, PolyTestFailure, retryDelayMs } from "@polytest/sdk";
|
|
2
|
+
const KEYS_URL = "https://www.polytest.io/app/keys";
|
|
3
|
+
const BILLING_URL = "https://www.polytest.io/app/billing";
|
|
4
|
+
const DOCS_URL = "https://www.polytest.io/docs/mcp";
|
|
5
|
+
// The SDK's error text when no key reached the client. Every other config failure names a bad key or option.
|
|
6
|
+
const NO_KEY = "Set POLYTEST_KEY or pass key.";
|
|
7
|
+
const SERVER_TEXT_MAX = 120;
|
|
8
|
+
// For a key that was sent and is wrong. A client sends a configured header on every request, so it signs in
|
|
9
|
+
// only once the header is gone.
|
|
10
|
+
const KEY_FIX = {
|
|
11
|
+
stdio: "Set POLYTEST_KEY to a valid key in the MCP server's env and restart it.",
|
|
12
|
+
http_key: "Put a valid key in the Authorization header of the server's MCP config, or remove the header and reconnect to sign in instead.",
|
|
13
|
+
oauth: "Reconnect the PolyTest server and sign in again.",
|
|
14
|
+
};
|
|
15
|
+
const NO_KEY_TEXT = {
|
|
16
|
+
stdio: `No PolyTest API key is set. ${KEY_FIX.stdio} Create a key at ${KEYS_URL}. Retrying will not help until the key is set.`,
|
|
17
|
+
http_key: `No PolyTest API key was sent. Add the header Authorization: Bearer <your key> to the server's MCP config, or reconnect and sign in. Create a key at ${KEYS_URL}. Retrying will not help until the key is set.`,
|
|
18
|
+
oauth: `The PolyTest connection is misconfigured and carries no API key. ${KEY_FIX.oauth} Retrying will not help until you reconnect. Docs: ${DOCS_URL}`,
|
|
19
|
+
};
|
|
20
|
+
// Server text is cut so a long upstream message cannot push the result past 400 characters.
|
|
21
|
+
function clip(text, max = SERVER_TEXT_MAX) {
|
|
22
|
+
const trimmed = text.trim();
|
|
23
|
+
return trimmed.length > max ? `${trimmed.slice(0, max - 3)}...` : trimmed;
|
|
24
|
+
}
|
|
25
|
+
function sentence(text) {
|
|
26
|
+
const cut = clip(text);
|
|
27
|
+
return /[.!?]$/.test(cut) ? cut : `${cut}.`;
|
|
28
|
+
}
|
|
29
|
+
function wait(retryAfter) {
|
|
30
|
+
if (retryAfter === null)
|
|
31
|
+
return "Wait a few seconds, then retry.";
|
|
32
|
+
const seconds = Math.max(1, Math.ceil(retryAfter));
|
|
33
|
+
return `Wait ${seconds} ${seconds === 1 ? "second" : "seconds"}, then retry.`;
|
|
34
|
+
}
|
|
35
|
+
export function explainFailure(failure, entry) {
|
|
36
|
+
switch (failure.kind) {
|
|
37
|
+
case "config":
|
|
38
|
+
if (failure.error === NO_KEY)
|
|
39
|
+
return NO_KEY_TEXT[entry];
|
|
40
|
+
return `The PolyTest client is misconfigured: ${sentence(failure.error)} ${KEY_FIX[entry]} Retrying will not help until this is fixed. Docs: ${DOCS_URL}`;
|
|
41
|
+
case "network":
|
|
42
|
+
return `Could not reach the PolyTest API: ${sentence(failure.message)} Check the network connection. Retrying may help.`;
|
|
43
|
+
case "unauthorized":
|
|
44
|
+
return `PolyTest rejected the API key: ${sentence(failure.error)} ${KEY_FIX[entry]} Keys are listed at ${KEYS_URL}. Retrying with the same key will not help.`;
|
|
45
|
+
case "trial_exhausted":
|
|
46
|
+
return `The trial usage budget is used up. Its ${failure.dimension} limit of ${failure.limit} was reached. Billing is at ${BILLING_URL}. Retrying will not help.`;
|
|
47
|
+
case "subscription_inactive":
|
|
48
|
+
return `The PolyTest subscription or trial is no longer active. Reactivate it at ${BILLING_URL}. Retrying will not help until it is active.`;
|
|
49
|
+
case "forbidden":
|
|
50
|
+
return `PolyTest refused this request on the ${clip(failure.tier, 24)} plan: ${sentence(failure.message)} Call polytest_get_limits to see what the plan covers. Plans are at ${BILLING_URL}. Retrying will not help.`;
|
|
51
|
+
case "rate_limited":
|
|
52
|
+
return `The PolyTest rate limit was reached. ${wait(failure.retry_after)} Space out calls to avoid this.`;
|
|
53
|
+
case "concurrency_limited":
|
|
54
|
+
return `Too many PolyTest requests ran at once. This plan allows ${failure.max_concurrent} at a time. Wait for the other calls to finish, then retry. Make calls one after another to avoid this.`;
|
|
55
|
+
case "bad_request":
|
|
56
|
+
return `PolyTest rejected the arguments: ${sentence(failure.error)}${failure.message === undefined ? "" : ` ${sentence(failure.message)}`} Fix the arguments and call again. Retrying unchanged will not help.`;
|
|
57
|
+
case "not_found":
|
|
58
|
+
return `PolyTest found no match: ${sentence(failure.error)} Check the market_id or slug. polytest_list_markets returns valid ids. Retrying unchanged will not help.`;
|
|
59
|
+
case "unavailable":
|
|
60
|
+
return `The PolyTest API is temporarily unavailable. ${wait(failure.retry_after)}`;
|
|
61
|
+
case "server":
|
|
62
|
+
return `The PolyTest API had a server error: ${sentence(failure.error)} Retry once. If it fails again, stop and report it${failure.error_id === null ? "" : ` with error id ${clip(failure.error_id, 40)}`}.`;
|
|
63
|
+
case "http":
|
|
64
|
+
return `The PolyTest API returned an unexpected response${failure.error === null ? "." : `: ${sentence(failure.error)}`} Retrying may not help. Docs: ${DOCS_URL}`;
|
|
65
|
+
default: {
|
|
66
|
+
const unknownKind = failure;
|
|
67
|
+
return unknownKind;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
export function explainError(error, entry) {
|
|
72
|
+
if (error instanceof PolyTestFailure)
|
|
73
|
+
return explainFailure(error.failure, entry);
|
|
74
|
+
return `The PolyTest MCP server hit an unexpected error. Retry once. If it fails again, stop and report it. Docs: ${DOCS_URL}`;
|
|
75
|
+
}
|
|
76
|
+
const RETRY_BUDGET_MS = 8_000;
|
|
77
|
+
const FIRST_BACKOFF_MS = 250;
|
|
78
|
+
// A server wait of 0 would retry in a loop that never spends the budget.
|
|
79
|
+
const MIN_DELAY_MS = 100;
|
|
80
|
+
export function sleep(ms) {
|
|
81
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
82
|
+
}
|
|
83
|
+
export async function withRetry(work, opts = {}) {
|
|
84
|
+
const pause = opts.sleep ?? sleep;
|
|
85
|
+
const random = opts.random ?? Math.random;
|
|
86
|
+
let waited = 0;
|
|
87
|
+
let backoff = FIRST_BACKOFF_MS;
|
|
88
|
+
for (;;) {
|
|
89
|
+
try {
|
|
90
|
+
return await work();
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (!isRetryable(error))
|
|
94
|
+
throw error;
|
|
95
|
+
const asked = retryDelayMs(error);
|
|
96
|
+
let delay;
|
|
97
|
+
if (asked !== null) {
|
|
98
|
+
delay = Math.max(asked, MIN_DELAY_MS);
|
|
99
|
+
}
|
|
100
|
+
else if (error instanceof PolyTestFailure && error.failure.kind === "concurrency_limited") {
|
|
101
|
+
delay = Math.round(150 + random() * 250);
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
delay = backoff;
|
|
105
|
+
backoff *= 2;
|
|
106
|
+
}
|
|
107
|
+
if (waited + delay > RETRY_BUDGET_MS)
|
|
108
|
+
throw error;
|
|
109
|
+
await pause(delay);
|
|
110
|
+
waited += delay;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const INSTRUCTIONS: string;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Some clients keep only the start of the instructions, so the first paragraph has to make sense alone.
|
|
2
|
+
export const INSTRUCTIONS = [
|
|
3
|
+
"PolyTest serves historical data for Polymarket crypto Up/Down markets. A market asks whether a coin's price ends a fixed window at or above where it started. Each market has about 8 snapshots per second with the coin spot price and the Up and Down token prices. Order books are optional. All tools are read-only. Usual flow: polytest_list_markets to find a market, polytest_get_price_series for the shape of that market, then polytest_get_snapshots for tick detail or the order book at one moment.",
|
|
4
|
+
[
|
|
5
|
+
"Rules:",
|
|
6
|
+
"- market_type is one of 5m, 15m, 1hr, 4hr, 24hr. Do not write 1h or 4h.",
|
|
7
|
+
"- coin is btc, eth, or sol, in lowercase. 4hr and 24hr markets exist for btc only.",
|
|
8
|
+
"- Times are ISO 8601. A time with no zone is UTC.",
|
|
9
|
+
"- price_up and price_down are the lowest asks on each side's order book, from 0 to 1. Together they usually add up to a little more than 1.",
|
|
10
|
+
"- Read a market's status field, not its winner, to tell whether it is still running. PolyTest loads new markets in batches, so the newest data can be hours old. polytest_list_markets says so when it is.",
|
|
11
|
+
"- Markets list newest first. Snapshots list oldest first.",
|
|
12
|
+
"- A tie resolves Up. Up wins when the close is at or above the open.",
|
|
13
|
+
"- Every call counts against the caller's plan limits. Each tool description states its cost in API requests. polytest_get_limits shows the plan.",
|
|
14
|
+
"- For bulk pulls or backtests, write code against the REST API or the @polytest/sdk package instead of paging through tools. SDK docs: https://www.polytest.io/docs/sdk",
|
|
15
|
+
].join("\n"),
|
|
16
|
+
].join("\n\n");
|
package/dist/series.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { McpServer } from "@modelcontextprotocol/server";
|
|
2
|
+
import { type PolyTestClient } from "@polytest/sdk";
|
|
3
|
+
import * as z from "zod/v4";
|
|
4
|
+
import { type RetryOptions } from "./failures.js";
|
|
5
|
+
import { type ServerDeps } from "./tools.js";
|
|
6
|
+
declare const seriesOutput: z.ZodObject<{
|
|
7
|
+
market_id: z.ZodString;
|
|
8
|
+
start_time: z.ZodString;
|
|
9
|
+
end_time: z.ZodString;
|
|
10
|
+
bucket_seconds: z.ZodNumber;
|
|
11
|
+
points: z.ZodArray<z.ZodObject<{
|
|
12
|
+
time: z.ZodString;
|
|
13
|
+
spot_price: z.ZodNullable<z.ZodNumber>;
|
|
14
|
+
price_up: z.ZodNullable<z.ZodNumber>;
|
|
15
|
+
price_down: z.ZodNullable<z.ZodNumber>;
|
|
16
|
+
}, z.core.$strip>>;
|
|
17
|
+
empty_buckets: z.ZodNumber;
|
|
18
|
+
requests_used: z.ZodNumber;
|
|
19
|
+
note: z.ZodOptional<z.ZodString>;
|
|
20
|
+
}, z.core.$strip>;
|
|
21
|
+
export type SeriesInput = {
|
|
22
|
+
market_id: string;
|
|
23
|
+
samples: number;
|
|
24
|
+
start_time?: string;
|
|
25
|
+
end_time?: string;
|
|
26
|
+
};
|
|
27
|
+
export type SeriesOptions = RetryOptions & {
|
|
28
|
+
signal?: AbortSignal;
|
|
29
|
+
now?: number;
|
|
30
|
+
};
|
|
31
|
+
export declare function priceSeries(client: PolyTestClient, input: SeriesInput, options?: SeriesOptions): Promise<z.infer<typeof seriesOutput>>;
|
|
32
|
+
export declare function registerPriceSeries(server: McpServer, deps: ServerDeps): void;
|
|
33
|
+
export {};
|
package/dist/series.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { PolyTestFailure } from "@polytest/sdk";
|
|
2
|
+
import * as z from "zod/v4";
|
|
3
|
+
import { projectSnapshot } from "./budget.js";
|
|
4
|
+
import { sleep, withRetry } from "./failures.js";
|
|
5
|
+
import { optionalText, PRICE_DOWN, PRICE_UP, READ_ONLY, run } from "./tools.js";
|
|
6
|
+
const PACE_MS = 100;
|
|
7
|
+
const seriesInput = z.object({
|
|
8
|
+
market_id: z.string().describe("PolyTest market id from polytest_list_markets or polytest_get_market."),
|
|
9
|
+
samples: z.number().int().min(2).max(60).default(20).describe("Number of buckets. Each one costs 1 API request."),
|
|
10
|
+
start_time: optionalText
|
|
11
|
+
.describe("ISO 8601. Start of the range. Defaults to the market start. No zone means UTC."),
|
|
12
|
+
end_time: optionalText
|
|
13
|
+
.describe("ISO 8601. End of the range. Defaults to the market end. No zone means UTC."),
|
|
14
|
+
});
|
|
15
|
+
const seriesOutput = z.object({
|
|
16
|
+
market_id: z.string(),
|
|
17
|
+
start_time: z.string().describe("Start of the sampled range."),
|
|
18
|
+
end_time: z.string().describe("End of the sampled range."),
|
|
19
|
+
bucket_seconds: z.number().describe("Length of each bucket in seconds."),
|
|
20
|
+
points: z.array(z.object({
|
|
21
|
+
time: z.string(),
|
|
22
|
+
spot_price: z.number().nullable().describe("Coin spot price."),
|
|
23
|
+
price_up: z.number().nullable().describe(PRICE_UP),
|
|
24
|
+
price_down: z.number().nullable().describe(PRICE_DOWN),
|
|
25
|
+
})),
|
|
26
|
+
empty_buckets: z.number().int().describe("Buckets that had no snapshot."),
|
|
27
|
+
requests_used: z.number().int().describe("API requests this call made, retries included."),
|
|
28
|
+
note: z.string().optional(),
|
|
29
|
+
});
|
|
30
|
+
const ISO_INSTANT = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?)?$/;
|
|
31
|
+
// Date.parse reads a time with no zone as local time. The SDK reads it as UTC, so this does too.
|
|
32
|
+
function parseTime(value) {
|
|
33
|
+
const match = ISO_INSTANT.exec(value);
|
|
34
|
+
if (!match)
|
|
35
|
+
return null;
|
|
36
|
+
const [, date, hour = "00", minute = "00", second = "00", fraction = ".", zone = "Z"] = match;
|
|
37
|
+
const utc = `${date}T${hour}:${minute}:${second}.${fraction.slice(1, 4).padEnd(3, "0")}Z`;
|
|
38
|
+
const wall = Date.parse(utc);
|
|
39
|
+
// Date.parse rolls February 30 or hour 24 forward instead of rejecting it.
|
|
40
|
+
if (Number.isNaN(wall) || new Date(wall).toISOString() !== utc)
|
|
41
|
+
return null;
|
|
42
|
+
if (zone.toUpperCase() === "Z")
|
|
43
|
+
return wall;
|
|
44
|
+
const hours = Number(zone.slice(1, 3));
|
|
45
|
+
const minutes = Number(zone.slice(-2));
|
|
46
|
+
if (hours > 23 || minutes > 59)
|
|
47
|
+
return null;
|
|
48
|
+
return wall - (zone[0] === "+" ? 1 : -1) * (hours * 60 + minutes) * 60_000;
|
|
49
|
+
}
|
|
50
|
+
function badRequest(error) {
|
|
51
|
+
return new PolyTestFailure({ kind: "bad_request", error }, null, error);
|
|
52
|
+
}
|
|
53
|
+
function readBound(value, name) {
|
|
54
|
+
if (value === undefined)
|
|
55
|
+
return null;
|
|
56
|
+
const time = parseTime(value);
|
|
57
|
+
if (time === null)
|
|
58
|
+
throw badRequest(`${name} must be an ISO 8601 date`);
|
|
59
|
+
return time;
|
|
60
|
+
}
|
|
61
|
+
function iso(time) {
|
|
62
|
+
return new Date(time).toISOString();
|
|
63
|
+
}
|
|
64
|
+
export async function priceSeries(client, input, options = {}) {
|
|
65
|
+
const pause = options.sleep ?? sleep;
|
|
66
|
+
const request = { signal: options.signal };
|
|
67
|
+
const from = readBound(input.start_time, "start_time");
|
|
68
|
+
const to = readBound(input.end_time, "end_time");
|
|
69
|
+
if (from !== null && to !== null && from > to) {
|
|
70
|
+
throw badRequest("start_time must be less than or equal to end_time");
|
|
71
|
+
}
|
|
72
|
+
let requests = 0;
|
|
73
|
+
const market = await withRetry(() => {
|
|
74
|
+
requests += 1;
|
|
75
|
+
return client.market({ market_id: input.market_id }, request);
|
|
76
|
+
}, options);
|
|
77
|
+
const opens = parseTime(market.start_time);
|
|
78
|
+
const closes = parseTime(market.end_time);
|
|
79
|
+
if (opens === null || closes === null) {
|
|
80
|
+
const error = "market has no readable start_time or end_time";
|
|
81
|
+
throw new PolyTestFailure({ kind: "server", error, message: null, error_id: null }, null, error);
|
|
82
|
+
}
|
|
83
|
+
const nowMs = options.now ?? Date.now();
|
|
84
|
+
const start = Math.max(opens, from ?? opens);
|
|
85
|
+
// Nothing after the current time has data yet, so buckets there would cost a request each and come back empty.
|
|
86
|
+
const end = Math.min(closes, to ?? closes, nowMs);
|
|
87
|
+
if (start >= nowMs) {
|
|
88
|
+
throw badRequest(`The range starts after the current time, ${iso(nowMs)}, so it has no data yet`);
|
|
89
|
+
}
|
|
90
|
+
if (start >= end) {
|
|
91
|
+
throw badRequest(`The range is outside the market window, ${iso(opens)} to ${iso(closes)}`);
|
|
92
|
+
}
|
|
93
|
+
const width = (end - start) / input.samples;
|
|
94
|
+
const points = [];
|
|
95
|
+
let empty = 0;
|
|
96
|
+
let trailing = 0;
|
|
97
|
+
for (let index = 0; index < input.samples; index++) {
|
|
98
|
+
const bucketStart = Math.round(start + index * width);
|
|
99
|
+
const nextStart = Math.round(start + (index + 1) * width);
|
|
100
|
+
// Upstream ranges include both ends, so a bucket ending on the next one's start would share that instant.
|
|
101
|
+
// The max keeps a bucket narrower than 1 ms from ending before it starts.
|
|
102
|
+
const bucketEnd = index === input.samples - 1 ? end : Math.max(bucketStart, nextStart - 1);
|
|
103
|
+
const query = { start_time: iso(bucketStart), end_time: iso(bucketEnd), limit: 1 };
|
|
104
|
+
await pause(PACE_MS);
|
|
105
|
+
const page = await withRetry(() => {
|
|
106
|
+
requests += 1;
|
|
107
|
+
return client.snapshots(input.market_id, query, request);
|
|
108
|
+
}, options);
|
|
109
|
+
const first = page.items[0];
|
|
110
|
+
if (first === undefined) {
|
|
111
|
+
empty += 1;
|
|
112
|
+
trailing += 1;
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
points.push(projectSnapshot(first, null));
|
|
116
|
+
trailing = 0;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const last = points.at(-1);
|
|
120
|
+
return {
|
|
121
|
+
market_id: input.market_id,
|
|
122
|
+
start_time: iso(start),
|
|
123
|
+
end_time: iso(end),
|
|
124
|
+
bucket_seconds: width / 1000,
|
|
125
|
+
points,
|
|
126
|
+
empty_buckets: empty,
|
|
127
|
+
requests_used: requests,
|
|
128
|
+
...(last !== undefined && trailing > 0
|
|
129
|
+
? {
|
|
130
|
+
note: `The last ${trailing === 1 ? "bucket" : `${trailing} buckets`} had no snapshot. The data in this range ends at ${last.time}.`,
|
|
131
|
+
}
|
|
132
|
+
: {}),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
export function registerPriceSeries(server, deps) {
|
|
136
|
+
server.registerTool("polytest_get_price_series", {
|
|
137
|
+
title: "Get price series",
|
|
138
|
+
description: "Returns evenly spaced price points across one market, oldest first. Use it to see the shape of a market without paging through snapshots. It splits the market window, or the part of it inside start_time and end_time, into samples equal buckets and returns the first snapshot of each bucket. Each point has time, spot_price, price_up, and price_down. empty_buckets counts the buckets with no snapshot, and note says where the data ends when the last buckets are empty. For a market still running, the range stops at the current time. Costs 1 + samples API requests, which is 21 with the default. The result is complete and has no paging. For more detail, raise samples or call polytest_get_snapshots on a short range.",
|
|
139
|
+
inputSchema: seriesInput,
|
|
140
|
+
outputSchema: seriesOutput,
|
|
141
|
+
annotations: READ_ONLY,
|
|
142
|
+
}, ({ market_id, samples, start_time, end_time }, ctx) => run(deps.entry, () => priceSeries(deps.client(), { market_id, samples, start_time, end_time }, { ...deps.retry, signal: ctx.mcpReq.signal, now: (deps.now ?? Date.now)() })));
|
|
143
|
+
}
|
package/dist/server.d.ts
ADDED
package/dist/server.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/server";
|
|
2
|
+
import { INSTRUCTIONS } from "./instructions.js";
|
|
3
|
+
import { registerPriceSeries } from "./series.js";
|
|
4
|
+
import { registerTools } from "./tools.js";
|
|
5
|
+
import { VERSION } from "./version.js";
|
|
6
|
+
export function buildServer(deps) {
|
|
7
|
+
const server = new McpServer({
|
|
8
|
+
name: "polytest",
|
|
9
|
+
title: "PolyTest",
|
|
10
|
+
version: VERSION,
|
|
11
|
+
websiteUrl: "https://www.polytest.io",
|
|
12
|
+
}, {
|
|
13
|
+
instructions: INSTRUCTIONS,
|
|
14
|
+
capabilities: { tools: { listChanged: false } },
|
|
15
|
+
cacheHints: { "tools/list": { ttlMs: 300_000, cacheScope: "private" } },
|
|
16
|
+
});
|
|
17
|
+
registerTools(server, deps);
|
|
18
|
+
registerPriceSeries(server, deps);
|
|
19
|
+
return server;
|
|
20
|
+
}
|
|
21
|
+
export function withUserAgent(inner) {
|
|
22
|
+
return (input, init) => {
|
|
23
|
+
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
|
|
24
|
+
headers.set("User-Agent", `polytest-mcp/${VERSION}`);
|
|
25
|
+
return (inner ?? globalThis.fetch)(input, { ...init, headers });
|
|
26
|
+
};
|
|
27
|
+
}
|
package/dist/stdio.d.ts
ADDED
package/dist/stdio.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
3
|
+
import { polytest } from "@polytest/sdk";
|
|
4
|
+
import { buildServer, withUserAgent } from "./server.js";
|
|
5
|
+
serveStdio(() => buildServer({ entry: "stdio", client: () => polytest({ fetch: withUserAgent() }) }));
|
package/dist/tools.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { CallToolResult, McpServer } from "@modelcontextprotocol/server";
|
|
2
|
+
import { type PolyTestClient } from "@polytest/sdk";
|
|
3
|
+
import * as z from "zod/v4";
|
|
4
|
+
import { type Entry, type RetryOptions } from "./failures.js";
|
|
5
|
+
export type ServerDeps = {
|
|
6
|
+
client: () => PolyTestClient;
|
|
7
|
+
entry: Entry;
|
|
8
|
+
retry?: RetryOptions;
|
|
9
|
+
now?: () => number;
|
|
10
|
+
};
|
|
11
|
+
export declare const READ_ONLY: {
|
|
12
|
+
readonly readOnlyHint: true;
|
|
13
|
+
readonly destructiveHint: false;
|
|
14
|
+
readonly idempotentHint: true;
|
|
15
|
+
readonly openWorldHint: false;
|
|
16
|
+
};
|
|
17
|
+
export declare function failed(text: string): CallToolResult;
|
|
18
|
+
export declare function run(entry: Entry, work: () => Promise<Record<string, unknown>>): Promise<CallToolResult>;
|
|
19
|
+
export declare const PRICE_UP = "Lowest ask on the Up order book, 0 to 1: what buying Up cost at that moment. Null when nobody was selling Up.";
|
|
20
|
+
export declare const PRICE_DOWN = "Lowest ask on the Down order book, 0 to 1: what buying Down cost at that moment. Null when nobody was selling Down. Up and Down asks usually add up to a little more than 1.";
|
|
21
|
+
export declare const optionalText: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
|
|
22
|
+
export declare function registerTools(server: McpServer, deps: ServerDeps): void;
|
package/dist/tools.js
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { MARKET_TYPES } from "@polytest/sdk";
|
|
2
|
+
import * as z from "zod/v4";
|
|
3
|
+
import { fitRows, MAX_OUTPUT_CHARS, projectMarket, projectMarketRow, projectSnapshot } from "./budget.js";
|
|
4
|
+
import { explainError, withRetry } from "./failures.js";
|
|
5
|
+
export const READ_ONLY = {
|
|
6
|
+
readOnlyHint: true,
|
|
7
|
+
destructiveHint: false,
|
|
8
|
+
idempotentHint: true,
|
|
9
|
+
openWorldHint: false,
|
|
10
|
+
};
|
|
11
|
+
const BOOK_PAGE_MAX = 20;
|
|
12
|
+
export function failed(text) {
|
|
13
|
+
return { content: [{ type: "text", text }], isError: true };
|
|
14
|
+
}
|
|
15
|
+
export async function run(entry, work) {
|
|
16
|
+
try {
|
|
17
|
+
const structuredContent = await work();
|
|
18
|
+
return { content: [{ type: "text", text: JSON.stringify(structuredContent) }], structuredContent };
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
return failed(explainError(error, entry));
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
// Verified on production order books: both prices are the best ask of their side.
|
|
25
|
+
export const PRICE_UP = "Lowest ask on the Up order book, 0 to 1: what buying Up cost at that moment. Null when nobody was selling Up.";
|
|
26
|
+
export const PRICE_DOWN = "Lowest ask on the Down order book, 0 to 1: what buying Down cost at that moment. Null when nobody was selling Down. Up and Down asks usually add up to a little more than 1.";
|
|
27
|
+
const WINDOW_MS = {
|
|
28
|
+
"5m": 5 * 60_000,
|
|
29
|
+
"15m": 15 * 60_000,
|
|
30
|
+
"1hr": 60 * 60_000,
|
|
31
|
+
"4hr": 4 * 60 * 60_000,
|
|
32
|
+
"24hr": 24 * 60 * 60_000,
|
|
33
|
+
};
|
|
34
|
+
// Slack past one window before the newest market counts as old.
|
|
35
|
+
const FRESH_SLACK_MS = 30 * 60_000;
|
|
36
|
+
// Some models send "" for an optional string they mean to leave out.
|
|
37
|
+
export const optionalText = z
|
|
38
|
+
.string()
|
|
39
|
+
.optional()
|
|
40
|
+
.transform((value) => (value === "" ? undefined : value));
|
|
41
|
+
const marketRow = {
|
|
42
|
+
market_id: z.string(),
|
|
43
|
+
slug: z.string(),
|
|
44
|
+
market_type: z.string(),
|
|
45
|
+
coin: z.string(),
|
|
46
|
+
start_time: z.string(),
|
|
47
|
+
end_time: z.string(),
|
|
48
|
+
price_start: z.number().nullable().describe("Coin spot price when the window opened."),
|
|
49
|
+
price_end: z.number().nullable().describe("Coin spot price when the window closed. Null until it is recorded."),
|
|
50
|
+
winner: z.string().nullable().describe("Winning side once the market resolves. A tie resolves Up."),
|
|
51
|
+
final_volume: z.number().nullable(),
|
|
52
|
+
resolved_at: z.string().nullable(),
|
|
53
|
+
status: z
|
|
54
|
+
.enum(["upcoming", "open", "resolved", "ended_no_result"])
|
|
55
|
+
.describe("upcoming: not started. open: the window is still running. resolved: the winner is known. ended_no_result: the window closed and PolyTest has no result for it."),
|
|
56
|
+
};
|
|
57
|
+
// A pasted Polymarket link carries the slug as its last path segment, and a slug never contains a slash.
|
|
58
|
+
function slugFromLink(value) {
|
|
59
|
+
const path = value.split(/[?#]/)[0] ?? value;
|
|
60
|
+
return path.split("/").filter((part) => part !== "").at(-1) ?? value;
|
|
61
|
+
}
|
|
62
|
+
const listMarketsInput = z.object({
|
|
63
|
+
market_type: z.enum(MARKET_TYPES).describe("Window length. One of 5m, 15m, 1hr, 4hr, 24hr."),
|
|
64
|
+
coin: z
|
|
65
|
+
.string()
|
|
66
|
+
.default("btc")
|
|
67
|
+
.transform((value) => (value === "" ? "btc" : value))
|
|
68
|
+
.describe("Coin symbol in lowercase: btc, eth, or sol. 4hr and 24hr markets exist for btc only."),
|
|
69
|
+
start_time: optionalText
|
|
70
|
+
.describe("ISO 8601. Keeps markets that start at or after this time. No zone means UTC."),
|
|
71
|
+
end_time: optionalText
|
|
72
|
+
.describe("ISO 8601. Keeps markets that start at or before this time. No zone means UTC."),
|
|
73
|
+
limit: z.number().int().min(1).max(100).default(20).describe("Rows per page."),
|
|
74
|
+
offset: z.number().int().min(0).default(0).describe("Rows to skip. Pass next_offset from the previous page."),
|
|
75
|
+
});
|
|
76
|
+
const listMarketsOutput = z.object({
|
|
77
|
+
markets: z.array(z.object(marketRow)),
|
|
78
|
+
count: z.number().int().describe("Rows in this result."),
|
|
79
|
+
stop: z.enum(["more", "end", "tier_window"]),
|
|
80
|
+
next_offset: z.number().int().nullable().describe("Offset of the next page when stop is more."),
|
|
81
|
+
truncated: z.boolean().describe("True when rows were cut to keep the result small."),
|
|
82
|
+
note: z.string().optional(),
|
|
83
|
+
});
|
|
84
|
+
const getMarketInput = z.object({
|
|
85
|
+
market_id: optionalText.describe("PolyTest market id. Pass this or slug, not both."),
|
|
86
|
+
slug: optionalText
|
|
87
|
+
.transform((value) => (value === undefined ? undefined : slugFromLink(value)))
|
|
88
|
+
.describe("A Polymarket event URL, or its last path segment. Pass this or market_id, not both."),
|
|
89
|
+
});
|
|
90
|
+
const getMarketOutput = z.object({
|
|
91
|
+
market: z.object({
|
|
92
|
+
...marketRow,
|
|
93
|
+
event_id: z.string(),
|
|
94
|
+
final_liquidity: z.number().nullable(),
|
|
95
|
+
condition_id: z.string().nullable(),
|
|
96
|
+
clob_token_up: z.string().nullable(),
|
|
97
|
+
clob_token_down: z.string().nullable(),
|
|
98
|
+
created_at: z.string().nullable(),
|
|
99
|
+
updated_at: z.string().nullable(),
|
|
100
|
+
}),
|
|
101
|
+
});
|
|
102
|
+
const getSnapshotsInput = z.object({
|
|
103
|
+
market_id: z.string().describe("PolyTest market id from polytest_list_markets or polytest_get_market."),
|
|
104
|
+
start_time: optionalText
|
|
105
|
+
.describe("ISO 8601. Keeps snapshots at or after this time. No zone means UTC."),
|
|
106
|
+
end_time: optionalText
|
|
107
|
+
.describe("ISO 8601. Keeps snapshots at or before this time. No zone means UTC."),
|
|
108
|
+
limit: z.number().int().min(1).max(200).default(50).describe("Rows per page. At most 20 with order books."),
|
|
109
|
+
offset: z
|
|
110
|
+
.number()
|
|
111
|
+
.int()
|
|
112
|
+
.min(0)
|
|
113
|
+
.max(100_000)
|
|
114
|
+
.default(0)
|
|
115
|
+
.describe("Rows to skip. Pass next_offset from the previous page."),
|
|
116
|
+
include_orderbook: z.boolean().default(false).describe("Adds the Up and Down order books to each row."),
|
|
117
|
+
orderbook_depth: z.number().int().min(1).max(25).default(5).describe("Price levels kept per side of each book."),
|
|
118
|
+
});
|
|
119
|
+
const level = z.object({ price: z.number(), size: z.number() });
|
|
120
|
+
const book = z
|
|
121
|
+
.object({
|
|
122
|
+
bids: z.array(level).describe("Best bid first."),
|
|
123
|
+
asks: z.array(level).describe("Best ask first."),
|
|
124
|
+
})
|
|
125
|
+
.nullable();
|
|
126
|
+
const getSnapshotsOutput = z.object({
|
|
127
|
+
market_id: z.string(),
|
|
128
|
+
snapshots: z.array(z.object({
|
|
129
|
+
time: z.string(),
|
|
130
|
+
spot_price: z.number().nullable().describe("Coin spot price."),
|
|
131
|
+
price_up: z.number().nullable().describe(PRICE_UP),
|
|
132
|
+
price_down: z.number().nullable().describe(PRICE_DOWN),
|
|
133
|
+
orderbook_up: book.optional(),
|
|
134
|
+
orderbook_down: book.optional(),
|
|
135
|
+
})),
|
|
136
|
+
count: z.number().int().describe("Rows in this result."),
|
|
137
|
+
stop: z.enum(["more", "end", "tier_window", "snapshot_offset_cap"]),
|
|
138
|
+
next_offset: z.number().int().nullable().describe("Offset of the next page when stop is more."),
|
|
139
|
+
truncated: z.boolean().describe("True when rows were cut to keep the result small."),
|
|
140
|
+
note: z.string().optional(),
|
|
141
|
+
});
|
|
142
|
+
const cap = z.number().nullable();
|
|
143
|
+
const getLimitsOutput = z.object({
|
|
144
|
+
tier: z.string(),
|
|
145
|
+
rate_limits: z.object({ requests_per_minute: z.number(), burst_per_second: z.number() }),
|
|
146
|
+
concurrency: z.object({ max_concurrent: cap }),
|
|
147
|
+
data_access: z.object({
|
|
148
|
+
"5m_markets": cap,
|
|
149
|
+
"15m_markets": cap,
|
|
150
|
+
"1hr_markets": cap,
|
|
151
|
+
"4hr_markets": cap,
|
|
152
|
+
"24hr_markets": cap,
|
|
153
|
+
snapshots_per_market: cap,
|
|
154
|
+
}),
|
|
155
|
+
api_keys: z.object({ max_active: cap }),
|
|
156
|
+
trial_budget: z.object({ requests: z.number(), records: z.number(), bytes: z.number() }),
|
|
157
|
+
});
|
|
158
|
+
function projectLimits(limits) {
|
|
159
|
+
return {
|
|
160
|
+
tier: limits.tier,
|
|
161
|
+
rate_limits: {
|
|
162
|
+
requests_per_minute: limits.rate_limits.requests_per_minute,
|
|
163
|
+
burst_per_second: limits.rate_limits.burst_per_second,
|
|
164
|
+
},
|
|
165
|
+
concurrency: { max_concurrent: limits.concurrency.max_concurrent },
|
|
166
|
+
data_access: {
|
|
167
|
+
"5m_markets": limits.data_access["5m_markets"],
|
|
168
|
+
"15m_markets": limits.data_access["15m_markets"],
|
|
169
|
+
"1hr_markets": limits.data_access["1hr_markets"],
|
|
170
|
+
"4hr_markets": limits.data_access["4hr_markets"],
|
|
171
|
+
"24hr_markets": limits.data_access["24hr_markets"],
|
|
172
|
+
snapshots_per_market: limits.data_access.snapshots_per_market,
|
|
173
|
+
},
|
|
174
|
+
api_keys: { max_active: limits.api_keys.max_active },
|
|
175
|
+
trial_budget: {
|
|
176
|
+
requests: limits.trial_budget.requests,
|
|
177
|
+
records: limits.trial_budget.records,
|
|
178
|
+
bytes: limits.trial_budget.bytes,
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
function marketRef(market_id, slug) {
|
|
183
|
+
if (market_id !== undefined && slug === undefined)
|
|
184
|
+
return { market_id };
|
|
185
|
+
if (slug !== undefined && market_id === undefined)
|
|
186
|
+
return { slug };
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
function note(parts) {
|
|
190
|
+
const text = parts.filter((part) => part !== undefined).join(" ");
|
|
191
|
+
return text === "" ? {} : { note: text };
|
|
192
|
+
}
|
|
193
|
+
// The newest market starting well before now means PolyTest has not loaded the most recent markets yet.
|
|
194
|
+
function ageNote(newest, nowMs) {
|
|
195
|
+
if (newest === undefined)
|
|
196
|
+
return undefined;
|
|
197
|
+
const age = nowMs - Date.parse(newest.start_time);
|
|
198
|
+
const window = WINDOW_MS[newest.market_type] ?? 0;
|
|
199
|
+
if (!(age > window + FRESH_SLACK_MS))
|
|
200
|
+
return undefined;
|
|
201
|
+
const hours = (age / 3_600_000).toFixed(1);
|
|
202
|
+
return `The newest ${newest.coin} ${newest.market_type} market PolyTest has started at ${newest.start_time}, ${hours} hours before this call. PolyTest loads new markets in batches, so later markets are not available yet.`;
|
|
203
|
+
}
|
|
204
|
+
function skippedNote(skipped) {
|
|
205
|
+
if (skipped <= 0)
|
|
206
|
+
return undefined;
|
|
207
|
+
return skipped === 1
|
|
208
|
+
? "1 row could not be read and was left out."
|
|
209
|
+
: `${skipped} rows could not be read and were left out.`;
|
|
210
|
+
}
|
|
211
|
+
export function registerTools(server, deps) {
|
|
212
|
+
const now = deps.now ?? Date.now;
|
|
213
|
+
server.registerTool("polytest_list_markets", {
|
|
214
|
+
title: "List markets",
|
|
215
|
+
description: 'Lists Up/Down markets of one market_type for one coin. Use it to find a market_id before reading snapshots or a price series. Returns market rows, newest first by start time, each with its window, opening and closing spot price, winner, volume, and status. Use status, not winner, to tell whether a market is still running. coin is btc, eth, or sol, and 4hr and 24hr markets exist for btc only. start_time and end_time filter on the market start time. PolyTest loads new markets in batches, and note says so when the newest market is hours old. Costs 1 API request. To continue, call again with offset set to next_offset while stop is "more". stop "tier_window" means the plan does not cover the requested markets. If truncated is true, rows were cut to keep the result small and next_offset points at the first cut row.',
|
|
216
|
+
inputSchema: listMarketsInput,
|
|
217
|
+
outputSchema: listMarketsOutput,
|
|
218
|
+
annotations: READ_ONLY,
|
|
219
|
+
}, ({ market_type, coin, start_time, end_time, limit, offset }, ctx) => run(deps.entry, async () => {
|
|
220
|
+
const client = deps.client();
|
|
221
|
+
const page = await withRetry(() => client.markets({ market_type, coin: coin.toLowerCase(), start_time, end_time, limit, offset }, { signal: ctx.mcpReq.signal }), deps.retry);
|
|
222
|
+
const nowMs = now();
|
|
223
|
+
const rows = page.items.map((market) => projectMarketRow(market, nowMs));
|
|
224
|
+
// Only the first page of an open-ended range starts at the newest market PolyTest has.
|
|
225
|
+
const newest = offset === 0 && end_time === undefined ? rows[0] : undefined;
|
|
226
|
+
const fitted = fitRows(rows, MAX_OUTPUT_CHARS);
|
|
227
|
+
// The Page type is shared, but only the snapshots route ever stops on its offset cap.
|
|
228
|
+
const stop = page.stop === "snapshot_offset_cap" ? "end" : page.stop;
|
|
229
|
+
return {
|
|
230
|
+
markets: fitted.rows,
|
|
231
|
+
count: fitted.rows.length,
|
|
232
|
+
stop: fitted.truncated ? "more" : stop,
|
|
233
|
+
next_offset: fitted.truncated ? page.offset + fitted.rows.length : page.nextOffset,
|
|
234
|
+
truncated: fitted.truncated,
|
|
235
|
+
...note([page.warning, skippedNote(page.skipped), ageNote(newest, nowMs)]),
|
|
236
|
+
};
|
|
237
|
+
}));
|
|
238
|
+
server.registerTool("polytest_get_market", {
|
|
239
|
+
title: "Get market",
|
|
240
|
+
description: "Returns one market by market_id or by slug. Pass exactly one of them. A slug is the last path segment of a Polymarket event URL, as in https://polymarket.com/event/<slug>, and the whole URL works too. Use it to resolve a Polymarket link or to read the full record of a market, including token ids and resolution fields. Costs 1 API request.",
|
|
241
|
+
inputSchema: getMarketInput,
|
|
242
|
+
outputSchema: getMarketOutput,
|
|
243
|
+
annotations: READ_ONLY,
|
|
244
|
+
}, async ({ market_id, slug }, ctx) => {
|
|
245
|
+
const ref = marketRef(market_id, slug);
|
|
246
|
+
if (ref === null)
|
|
247
|
+
return failed("Pass exactly one of market_id or slug.");
|
|
248
|
+
return run(deps.entry, async () => {
|
|
249
|
+
const client = deps.client();
|
|
250
|
+
const market = await withRetry(() => client.market(ref, { signal: ctx.mcpReq.signal }), deps.retry);
|
|
251
|
+
return { market: projectMarket(market, now()) };
|
|
252
|
+
});
|
|
253
|
+
});
|
|
254
|
+
server.registerTool("polytest_get_snapshots", {
|
|
255
|
+
title: "Get snapshots",
|
|
256
|
+
description: 'Returns snapshots of one market, oldest first. Each row has time, spot_price, price_up, and price_down. Use it for tick detail in a short time range. For the shape of a whole market, use polytest_get_price_series. A market has about 8 snapshots per second, so narrow the range with start_time and end_time. With include_orderbook each row also has the Up and Down order books, cut to orderbook_depth levels per side, and a page holds at most 20 rows. The book at one moment is this tool with start_time set to that moment, limit 1, and include_orderbook true. Costs 1 API request. To continue, call again with offset set to next_offset while stop is "more". stop "snapshot_offset_cap" means offsets end at 100000, so move start_time forward to continue. If truncated is true, rows were cut to keep the result small and next_offset points at the first cut row.',
|
|
257
|
+
inputSchema: getSnapshotsInput,
|
|
258
|
+
outputSchema: getSnapshotsOutput,
|
|
259
|
+
annotations: READ_ONLY,
|
|
260
|
+
}, ({ market_id, start_time, end_time, limit, offset, include_orderbook, orderbook_depth }, ctx) => run(deps.entry, async () => {
|
|
261
|
+
const sent = include_orderbook ? Math.min(limit, BOOK_PAGE_MAX) : limit;
|
|
262
|
+
const client = deps.client();
|
|
263
|
+
const page = await withRetry(() => client.snapshots(market_id, { start_time, end_time, limit: sent, offset, include_orderbook }, { signal: ctx.mcpReq.signal }), deps.retry);
|
|
264
|
+
const depth = include_orderbook ? orderbook_depth : null;
|
|
265
|
+
const fitted = fitRows(page.items.map((snapshot) => projectSnapshot(snapshot, depth)), MAX_OUTPUT_CHARS);
|
|
266
|
+
return {
|
|
267
|
+
market_id,
|
|
268
|
+
snapshots: fitted.rows,
|
|
269
|
+
count: fitted.rows.length,
|
|
270
|
+
stop: fitted.truncated ? "more" : page.stop,
|
|
271
|
+
next_offset: fitted.truncated ? page.offset + fitted.rows.length : page.nextOffset,
|
|
272
|
+
truncated: fitted.truncated,
|
|
273
|
+
...note([
|
|
274
|
+
sent < limit
|
|
275
|
+
? `The limit was lowered from ${limit} to ${sent} because order books are included.`
|
|
276
|
+
: undefined,
|
|
277
|
+
page.warning,
|
|
278
|
+
skippedNote(page.skipped),
|
|
279
|
+
]),
|
|
280
|
+
};
|
|
281
|
+
}));
|
|
282
|
+
server.registerTool("polytest_get_limits", {
|
|
283
|
+
title: "Get plan limits",
|
|
284
|
+
description: "Returns the plan behind the current credential, an API key or a signed-in account: tier, rate limits, concurrency cap, data access, key cap, and trial budget. data_access gives how many of the most recent markets of each type the plan can read. A null cap means no cap. trial_budget is what a free trial may use in total over its 3 days. It applies only during a trial and does not show how much is left. Use it before a large read or after a plan or rate limit error. Costs 1 API request.",
|
|
285
|
+
inputSchema: z.object({}),
|
|
286
|
+
outputSchema: getLimitsOutput,
|
|
287
|
+
annotations: READ_ONLY,
|
|
288
|
+
}, (_args, ctx) => run(deps.entry, async () => {
|
|
289
|
+
const client = deps.client();
|
|
290
|
+
return projectLimits(await withRetry(() => client.limits({ signal: ctx.mcpReq.signal }), deps.retry));
|
|
291
|
+
}));
|
|
292
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const VERSION = "0.2.0";
|
package/dist/version.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const VERSION = "0.2.0";
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@polytest/mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "MCP server for the PolyTest API. Read historical Polymarket crypto Up/Down market data from an MCP client.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://www.polytest.io/docs/mcp",
|
|
7
|
+
"mcpName": "io.polytest/mcp",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"engines": {
|
|
10
|
+
"node": ">=20"
|
|
11
|
+
},
|
|
12
|
+
"bin": {
|
|
13
|
+
"polytest-mcp": "./dist/stdio.js"
|
|
14
|
+
},
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"import": "./dist/index.js",
|
|
19
|
+
"default": "./dist/index.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"main": "./dist/index.js",
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"README.md"
|
|
27
|
+
],
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc",
|
|
33
|
+
"test": "npm run build && vitest run",
|
|
34
|
+
"typecheck": "tsc -p tsconfig.test.json"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@modelcontextprotocol/server": "^2.4.0",
|
|
38
|
+
"@polytest/sdk": "^0.2.2",
|
|
39
|
+
"zod": "^4.2.0"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@modelcontextprotocol/client": "^2.4.0",
|
|
43
|
+
"@types/node": "^22",
|
|
44
|
+
"typescript": "^5.8",
|
|
45
|
+
"vitest": "^3"
|
|
46
|
+
}
|
|
47
|
+
}
|