@polytest/mcp 0.1.0 → 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/README.md CHANGED
@@ -6,7 +6,7 @@ An MCP server for the [PolyTest](https://www.polytest.io) API. It lets an MCP cl
6
6
 
7
7
  The server runs at `https://mcp.polytest.io/mcp` over Streamable HTTP. There are two ways to authenticate.
8
8
 
9
- Sign in with your PolyTest account. If your client supports OAuth, add the URL with no header. The client opens a browser window and you sign in there.
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
10
 
11
11
  Send an API key. Add the header `Authorization: Bearer <key>`. Create a key at https://www.polytest.io/app/keys.
12
12
 
@@ -18,7 +18,14 @@ Send an API key. Add the header `Authorization: Bearer <key>`. Create a key at h
18
18
  | `polytest_get_market` | One market, by market id or by Polymarket slug. | 1 |
19
19
  | `polytest_get_snapshots` | Snapshots of one market, oldest first. Order books are optional. | 1 |
20
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`, which is 21 by default |
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.
22
29
 
23
30
  ## Plan limits
24
31
 
package/dist/budget.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { Market, OrderLevel, Snapshot, SnapshotWithBooks } from "@polytest/sdk";
2
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;
3
5
  export type MarketRow = {
4
6
  market_id: string;
5
7
  slug: string;
@@ -12,6 +14,7 @@ export type MarketRow = {
12
14
  winner: string | null;
13
15
  final_volume: number | null;
14
16
  resolved_at: string | null;
17
+ status: MarketStatus;
15
18
  };
16
19
  export type MarketDetail = MarketRow & {
17
20
  event_id: string;
@@ -34,8 +37,8 @@ export type SnapshotRow = {
34
37
  orderbook_up?: Book | null;
35
38
  orderbook_down?: Book | null;
36
39
  };
37
- export declare function projectMarketRow(market: Market): MarketRow;
38
- export declare function projectMarket(market: Market): MarketDetail;
40
+ export declare function projectMarketRow(market: Market, nowMs: number): MarketRow;
41
+ export declare function projectMarket(market: Market, nowMs: number): MarketDetail;
39
42
  export declare function projectSnapshot(snapshot: Snapshot | SnapshotWithBooks, depth: number | null): SnapshotRow;
40
43
  export declare function fitRows<T>(rows: readonly T[], maxChars: number): {
41
44
  rows: T[];
package/dist/budget.js CHANGED
@@ -1,7 +1,16 @@
1
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
+ }
2
11
  // The SDK checks only market_id and slug on a market, and id, market_id, and time on a snapshot.
3
12
  // A nullable field the server left out arrives as undefined, which the output schema would reject.
4
- export function projectMarketRow(market) {
13
+ export function projectMarketRow(market, nowMs) {
5
14
  return {
6
15
  market_id: market.market_id,
7
16
  slug: market.slug,
@@ -14,9 +23,10 @@ export function projectMarketRow(market) {
14
23
  winner: market.winner ?? null,
15
24
  final_volume: market.final_volume ?? null,
16
25
  resolved_at: market.resolved_at ?? null,
26
+ status: marketStatus(market, nowMs),
17
27
  };
18
28
  }
19
- export function projectMarket(market) {
29
+ export function projectMarket(market, nowMs) {
20
30
  return {
21
31
  market_id: market.market_id,
22
32
  event_id: market.event_id,
@@ -36,6 +46,7 @@ export function projectMarket(market) {
36
46
  resolved_at: market.resolved_at ?? null,
37
47
  created_at: market.created_at ?? null,
38
48
  updated_at: market.updated_at ?? null,
49
+ status: marketStatus(market, nowMs),
39
50
  };
40
51
  }
41
52
  function trimSide(levels, depth, direction) {
package/dist/failures.js CHANGED
@@ -5,14 +5,16 @@ const DOCS_URL = "https://www.polytest.io/docs/mcp";
5
5
  // The SDK's error text when no key reached the client. Every other config failure names a bad key or option.
6
6
  const NO_KEY = "Set POLYTEST_KEY or pass key.";
7
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.
8
10
  const KEY_FIX = {
9
11
  stdio: "Set POLYTEST_KEY to a valid key in the MCP server's env and restart it.",
10
- http_key: "Add the header Authorization: Bearer <your key> to the server's MCP config, or reconnect and sign in.",
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.",
11
13
  oauth: "Reconnect the PolyTest server and sign in again.",
12
14
  };
13
15
  const NO_KEY_TEXT = {
14
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.`,
15
- http_key: `No PolyTest API key was sent. ${KEY_FIX.http_key} 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.`,
16
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}`,
17
19
  };
18
20
  // Server text is cut so a long upstream message cannot push the result past 400 characters.
@@ -4,9 +4,10 @@ export const INSTRUCTIONS = [
4
4
  [
5
5
  "Rules:",
6
6
  "- market_type is one of 5m, 15m, 1hr, 4hr, 24hr. Do not write 1h or 4h.",
7
- "- coin is lowercase, such as btc, eth, or sol.",
7
+ "- coin is btc, eth, or sol, in lowercase. 4hr and 24hr markets exist for btc only.",
8
8
  "- Times are ISO 8601. A time with no zone is UTC.",
9
- "- Up and Down token prices run from 0 to 1.",
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.",
10
11
  "- Markets list newest first. Snapshots list oldest first.",
11
12
  "- A tie resolves Up. Up wins when the close is at or above the open.",
12
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.",
package/dist/series.d.ts CHANGED
@@ -16,6 +16,7 @@ declare const seriesOutput: z.ZodObject<{
16
16
  }, z.core.$strip>>;
17
17
  empty_buckets: z.ZodNumber;
18
18
  requests_used: z.ZodNumber;
19
+ note: z.ZodOptional<z.ZodString>;
19
20
  }, z.core.$strip>;
20
21
  export type SeriesInput = {
21
22
  market_id: string;
@@ -25,6 +26,7 @@ export type SeriesInput = {
25
26
  };
26
27
  export type SeriesOptions = RetryOptions & {
27
28
  signal?: AbortSignal;
29
+ now?: number;
28
30
  };
29
31
  export declare function priceSeries(client: PolyTestClient, input: SeriesInput, options?: SeriesOptions): Promise<z.infer<typeof seriesOutput>>;
30
32
  export declare function registerPriceSeries(server: McpServer, deps: ServerDeps): void;
package/dist/series.js CHANGED
@@ -2,18 +2,14 @@ import { PolyTestFailure } from "@polytest/sdk";
2
2
  import * as z from "zod/v4";
3
3
  import { projectSnapshot } from "./budget.js";
4
4
  import { sleep, withRetry } from "./failures.js";
5
- import { READ_ONLY, run } from "./tools.js";
5
+ import { optionalText, PRICE_DOWN, PRICE_UP, READ_ONLY, run } from "./tools.js";
6
6
  const PACE_MS = 100;
7
7
  const seriesInput = z.object({
8
8
  market_id: z.string().describe("PolyTest market id from polytest_list_markets or polytest_get_market."),
9
9
  samples: z.number().int().min(2).max(60).default(20).describe("Number of buckets. Each one costs 1 API request."),
10
- start_time: z
11
- .string()
12
- .optional()
10
+ start_time: optionalText
13
11
  .describe("ISO 8601. Start of the range. Defaults to the market start. No zone means UTC."),
14
- end_time: z
15
- .string()
16
- .optional()
12
+ end_time: optionalText
17
13
  .describe("ISO 8601. End of the range. Defaults to the market end. No zone means UTC."),
18
14
  });
19
15
  const seriesOutput = z.object({
@@ -24,11 +20,12 @@ const seriesOutput = z.object({
24
20
  points: z.array(z.object({
25
21
  time: z.string(),
26
22
  spot_price: z.number().nullable().describe("Coin spot price."),
27
- price_up: z.number().nullable().describe("Up token price, 0 to 1."),
28
- price_down: z.number().nullable().describe("Down token price, 0 to 1."),
23
+ price_up: z.number().nullable().describe(PRICE_UP),
24
+ price_down: z.number().nullable().describe(PRICE_DOWN),
29
25
  })),
30
26
  empty_buckets: z.number().int().describe("Buckets that had no snapshot."),
31
27
  requests_used: z.number().int().describe("API requests this call made, retries included."),
28
+ note: z.string().optional(),
32
29
  });
33
30
  const ISO_INSTANT = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?)?$/;
34
31
  // Date.parse reads a time with no zone as local time. The SDK reads it as UTC, so this does too.
@@ -72,22 +69,31 @@ export async function priceSeries(client, input, options = {}) {
72
69
  if (from !== null && to !== null && from > to) {
73
70
  throw badRequest("start_time must be less than or equal to end_time");
74
71
  }
75
- const market = await client.market({ market_id: input.market_id }, request);
76
- let requests = 1;
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
77
  const opens = parseTime(market.start_time);
78
78
  const closes = parseTime(market.end_time);
79
79
  if (opens === null || closes === null) {
80
80
  const error = "market has no readable start_time or end_time";
81
81
  throw new PolyTestFailure({ kind: "server", error, message: null, error_id: null }, null, error);
82
82
  }
83
+ const nowMs = options.now ?? Date.now();
83
84
  const start = Math.max(opens, from ?? opens);
84
- const end = Math.min(closes, to ?? closes);
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
+ }
85
90
  if (start >= end) {
86
91
  throw badRequest(`The range is outside the market window, ${iso(opens)} to ${iso(closes)}`);
87
92
  }
88
93
  const width = (end - start) / input.samples;
89
94
  const points = [];
90
95
  let empty = 0;
96
+ let trailing = 0;
91
97
  for (let index = 0; index < input.samples; index++) {
92
98
  const bucketStart = Math.round(start + index * width);
93
99
  const nextStart = Math.round(start + (index + 1) * width);
@@ -101,11 +107,16 @@ export async function priceSeries(client, input, options = {}) {
101
107
  return client.snapshots(input.market_id, query, request);
102
108
  }, options);
103
109
  const first = page.items[0];
104
- if (first === undefined)
110
+ if (first === undefined) {
105
111
  empty += 1;
106
- else
112
+ trailing += 1;
113
+ }
114
+ else {
107
115
  points.push(projectSnapshot(first, null));
116
+ trailing = 0;
117
+ }
108
118
  }
119
+ const last = points.at(-1);
109
120
  return {
110
121
  market_id: input.market_id,
111
122
  start_time: iso(start),
@@ -114,14 +125,19 @@ export async function priceSeries(client, input, options = {}) {
114
125
  points,
115
126
  empty_buckets: empty,
116
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
+ : {}),
117
133
  };
118
134
  }
119
135
  export function registerPriceSeries(server, deps) {
120
136
  server.registerTool("polytest_get_price_series", {
121
137
  title: "Get price series",
122
- 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. 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.",
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.",
123
139
  inputSchema: seriesInput,
124
140
  outputSchema: seriesOutput,
125
141
  annotations: READ_ONLY,
126
- }, ({ 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 })));
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)() })));
127
143
  }
package/dist/tools.d.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  import type { CallToolResult, McpServer } from "@modelcontextprotocol/server";
2
2
  import { type PolyTestClient } from "@polytest/sdk";
3
+ import * as z from "zod/v4";
3
4
  import { type Entry, type RetryOptions } from "./failures.js";
4
5
  export type ServerDeps = {
5
6
  client: () => PolyTestClient;
6
7
  entry: Entry;
7
8
  retry?: RetryOptions;
9
+ now?: () => number;
8
10
  };
9
11
  export declare const READ_ONLY: {
10
12
  readonly readOnlyHint: true;
@@ -14,4 +16,7 @@ export declare const READ_ONLY: {
14
16
  };
15
17
  export declare function failed(text: string): CallToolResult;
16
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>>;
17
22
  export declare function registerTools(server: McpServer, deps: ServerDeps): void;
package/dist/tools.js CHANGED
@@ -21,6 +21,23 @@ export async function run(entry, work) {
21
21
  return failed(explainError(error, entry));
22
22
  }
23
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));
24
41
  const marketRow = {
25
42
  market_id: z.string(),
26
43
  slug: z.string(),
@@ -33,17 +50,25 @@ const marketRow = {
33
50
  winner: z.string().nullable().describe("Winning side once the market resolves. A tie resolves Up."),
34
51
  final_volume: z.number().nullable(),
35
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."),
36
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
+ }
37
62
  const listMarketsInput = z.object({
38
63
  market_type: z.enum(MARKET_TYPES).describe("Window length. One of 5m, 15m, 1hr, 4hr, 24hr."),
39
- coin: z.string().default("btc").describe("Coin symbol in lowercase, such as btc, eth, or sol."),
40
- start_time: z
64
+ coin: z
41
65
  .string()
42
- .optional()
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
43
70
  .describe("ISO 8601. Keeps markets that start at or after this time. No zone means UTC."),
44
- end_time: z
45
- .string()
46
- .optional()
71
+ end_time: optionalText
47
72
  .describe("ISO 8601. Keeps markets that start at or before this time. No zone means UTC."),
48
73
  limit: z.number().int().min(1).max(100).default(20).describe("Rows per page."),
49
74
  offset: z.number().int().min(0).default(0).describe("Rows to skip. Pass next_offset from the previous page."),
@@ -57,11 +82,10 @@ const listMarketsOutput = z.object({
57
82
  note: z.string().optional(),
58
83
  });
59
84
  const getMarketInput = z.object({
60
- market_id: z.string().optional().describe("PolyTest market id. Pass this or slug, not both."),
61
- slug: z
62
- .string()
63
- .optional()
64
- .describe("Last path segment of a Polymarket event URL. Pass this or market_id, not both."),
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."),
65
89
  });
66
90
  const getMarketOutput = z.object({
67
91
  market: z.object({
@@ -77,13 +101,9 @@ const getMarketOutput = z.object({
77
101
  });
78
102
  const getSnapshotsInput = z.object({
79
103
  market_id: z.string().describe("PolyTest market id from polytest_list_markets or polytest_get_market."),
80
- start_time: z
81
- .string()
82
- .optional()
104
+ start_time: optionalText
83
105
  .describe("ISO 8601. Keeps snapshots at or after this time. No zone means UTC."),
84
- end_time: z
85
- .string()
86
- .optional()
106
+ end_time: optionalText
87
107
  .describe("ISO 8601. Keeps snapshots at or before this time. No zone means UTC."),
88
108
  limit: z.number().int().min(1).max(200).default(50).describe("Rows per page. At most 20 with order books."),
89
109
  offset: z
@@ -108,8 +128,8 @@ const getSnapshotsOutput = z.object({
108
128
  snapshots: z.array(z.object({
109
129
  time: z.string(),
110
130
  spot_price: z.number().nullable().describe("Coin spot price."),
111
- price_up: z.number().nullable().describe("Up token price, 0 to 1."),
112
- price_down: z.number().nullable().describe("Down token price, 0 to 1."),
131
+ price_up: z.number().nullable().describe(PRICE_UP),
132
+ price_down: z.number().nullable().describe(PRICE_DOWN),
113
133
  orderbook_up: book.optional(),
114
134
  orderbook_down: book.optional(),
115
135
  })),
@@ -159,20 +179,28 @@ function projectLimits(limits) {
159
179
  },
160
180
  };
161
181
  }
162
- // Some models send "" for an optional string they mean to leave out.
163
182
  function marketRef(market_id, slug) {
164
- const id = market_id === "" ? undefined : market_id;
165
- const name = slug === "" ? undefined : slug;
166
- if (id !== undefined && name === undefined)
167
- return { market_id: id };
168
- if (name !== undefined && id === undefined)
169
- return { slug: name };
183
+ if (market_id !== undefined && slug === undefined)
184
+ return { market_id };
185
+ if (slug !== undefined && market_id === undefined)
186
+ return { slug };
170
187
  return null;
171
188
  }
172
189
  function note(parts) {
173
190
  const text = parts.filter((part) => part !== undefined).join(" ");
174
191
  return text === "" ? {} : { note: text };
175
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
+ }
176
204
  function skippedNote(skipped) {
177
205
  if (skipped <= 0)
178
206
  return undefined;
@@ -181,16 +209,21 @@ function skippedNote(skipped) {
181
209
  : `${skipped} rows could not be read and were left out.`;
182
210
  }
183
211
  export function registerTools(server, deps) {
212
+ const now = deps.now ?? Date.now;
184
213
  server.registerTool("polytest_list_markets", {
185
214
  title: "List markets",
186
- 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, and volume. start_time and end_time filter on the market start time. 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.',
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.',
187
216
  inputSchema: listMarketsInput,
188
217
  outputSchema: listMarketsOutput,
189
218
  annotations: READ_ONLY,
190
219
  }, ({ market_type, coin, start_time, end_time, limit, offset }, ctx) => run(deps.entry, async () => {
191
220
  const client = deps.client();
192
221
  const page = await withRetry(() => client.markets({ market_type, coin: coin.toLowerCase(), start_time, end_time, limit, offset }, { signal: ctx.mcpReq.signal }), deps.retry);
193
- const fitted = fitRows(page.items.map(projectMarketRow), MAX_OUTPUT_CHARS);
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);
194
227
  // The Page type is shared, but only the snapshots route ever stops on its offset cap.
195
228
  const stop = page.stop === "snapshot_offset_cap" ? "end" : page.stop;
196
229
  return {
@@ -199,12 +232,12 @@ export function registerTools(server, deps) {
199
232
  stop: fitted.truncated ? "more" : stop,
200
233
  next_offset: fitted.truncated ? page.offset + fitted.rows.length : page.nextOffset,
201
234
  truncated: fitted.truncated,
202
- ...note([page.warning, skippedNote(page.skipped)]),
235
+ ...note([page.warning, skippedNote(page.skipped), ageNote(newest, nowMs)]),
203
236
  };
204
237
  }));
205
238
  server.registerTool("polytest_get_market", {
206
239
  title: "Get market",
207
- 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>. 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.",
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.",
208
241
  inputSchema: getMarketInput,
209
242
  outputSchema: getMarketOutput,
210
243
  annotations: READ_ONLY,
@@ -215,7 +248,7 @@ export function registerTools(server, deps) {
215
248
  return run(deps.entry, async () => {
216
249
  const client = deps.client();
217
250
  const market = await withRetry(() => client.market(ref, { signal: ctx.mcpReq.signal }), deps.retry);
218
- return { market: projectMarket(market) };
251
+ return { market: projectMarket(market, now()) };
219
252
  });
220
253
  });
221
254
  server.registerTool("polytest_get_snapshots", {
@@ -248,7 +281,7 @@ export function registerTools(server, deps) {
248
281
  }));
249
282
  server.registerTool("polytest_get_limits", {
250
283
  title: "Get plan limits",
251
- description: "Returns the plan behind the current API key: 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. Use it before a large read or after a plan or rate limit error. Costs 1 API request.",
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.",
252
285
  inputSchema: z.object({}),
253
286
  outputSchema: getLimitsOutput,
254
287
  annotations: READ_ONLY,
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.0";
1
+ export declare const VERSION = "0.2.0";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = "0.1.0";
1
+ export const VERSION = "0.2.0";
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@polytest/mcp",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "MCP server for the PolyTest API. Read historical Polymarket crypto Up/Down market data from an MCP client.",
5
5
  "license": "MIT",
6
+ "homepage": "https://www.polytest.io/docs/mcp",
6
7
  "mcpName": "io.polytest/mcp",
7
8
  "type": "module",
8
9
  "engines": {