@polytest/mcp 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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) {
@@ -1,5 +1,6 @@
1
1
  import { type Failure } from "@polytest/sdk";
2
2
  export type Entry = "stdio" | "http_key" | "oauth";
3
+ export declare function reasonOf(text: string): string;
3
4
  export declare function explainFailure(failure: Failure, entry: Entry): string;
4
5
  export declare function explainError(error: unknown, entry: Entry): string;
5
6
  export type RetryOptions = {
package/dist/failures.js CHANGED
@@ -1,18 +1,21 @@
1
1
  import { isRetryable, PolyTestFailure, retryDelayMs } from "@polytest/sdk";
2
2
  const KEYS_URL = "https://www.polytest.io/app/keys";
3
- const BILLING_URL = "https://www.polytest.io/app/billing";
3
+ // An app directory may let a tool say what a plan covers and link plan details, but not point at billing or upgrades.
4
+ const PRICING_URL = "https://www.polytest.io/pricing";
4
5
  const DOCS_URL = "https://www.polytest.io/docs/mcp";
5
6
  // The SDK's error text when no key reached the client. Every other config failure names a bad key or option.
6
7
  const NO_KEY = "Set POLYTEST_KEY or pass key.";
7
8
  const SERVER_TEXT_MAX = 120;
9
+ // For a key that was sent and is wrong. A client sends a configured header on every request, so it signs in
10
+ // only once the header is gone.
8
11
  const KEY_FIX = {
9
12
  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.",
13
+ 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
14
  oauth: "Reconnect the PolyTest server and sign in again.",
12
15
  };
13
16
  const NO_KEY_TEXT = {
14
17
  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.`,
18
+ 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
19
  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
20
  };
18
21
  // Server text is cut so a long upstream message cannot push the result past 400 characters.
@@ -24,6 +27,11 @@ function sentence(text) {
24
27
  const cut = clip(text);
25
28
  return /[.!?]$/.test(cut) ? cut : `${cut}.`;
26
29
  }
30
+ // The server's plan messages give the reason first and end with a call to upgrade or to pay, which is dropped.
31
+ export function reasonOf(text) {
32
+ const trimmed = text.trim();
33
+ return /^.*?[.!?](?=\s|$)/s.exec(trimmed)?.[0] ?? trimmed;
34
+ }
27
35
  function wait(retryAfter) {
28
36
  if (retryAfter === null)
29
37
  return "Wait a few seconds, then retry.";
@@ -41,11 +49,11 @@ export function explainFailure(failure, entry) {
41
49
  case "unauthorized":
42
50
  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.`;
43
51
  case "trial_exhausted":
44
- 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.`;
52
+ return `The trial usage budget is used up. Its ${failure.dimension} limit of ${failure.limit} was reached. Plan details are at ${PRICING_URL}. Retrying will not help.`;
45
53
  case "subscription_inactive":
46
- return `The PolyTest subscription or trial is no longer active. Reactivate it at ${BILLING_URL}. Retrying will not help until it is active.`;
54
+ return `This PolyTest account has no active subscription or trial, so it cannot read data. Plan details are at ${PRICING_URL}. Retrying will not help until one is active.`;
47
55
  case "forbidden":
48
- 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.`;
56
+ return `PolyTest refused this request on the ${clip(failure.tier, 24)} plan: ${sentence(reasonOf(failure.message))} Call polytest_get_limits to see what the plan covers. Plan details are at ${PRICING_URL}. Retrying will not help.`;
49
57
  case "rate_limited":
50
58
  return `The PolyTest rate limit was reached. ${wait(failure.retry_after)} Space out calls to avoid this.`;
51
59
  case "concurrency_limited":
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { buildServer, withUserAgent } from "./server.js";
2
2
  export { VERSION } from "./version.js";
3
3
  export type { Entry } from "./failures.js";
4
- export type { ServerDeps } from "./tools.js";
4
+ export type { SecurityScheme, ServerDeps } from "./tools.js";
@@ -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, toolMeta } 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,20 @@ 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
+ ...toolMeta(deps),
143
+ }, ({ 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
144
  }
package/dist/tools.d.ts CHANGED
@@ -1,10 +1,24 @@
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";
5
+ export type SecurityScheme = {
6
+ type: "noauth";
7
+ } | {
8
+ type: "oauth2";
9
+ scopes: readonly string[];
10
+ };
4
11
  export type ServerDeps = {
5
12
  client: () => PolyTestClient;
6
13
  entry: Entry;
7
14
  retry?: RetryOptions;
15
+ now?: () => number;
16
+ securitySchemes?: readonly SecurityScheme[];
17
+ };
18
+ export declare function toolMeta(deps: ServerDeps): {
19
+ _meta?: {
20
+ securitySchemes: readonly SecurityScheme[];
21
+ };
8
22
  };
9
23
  export declare const READ_ONLY: {
10
24
  readonly readOnlyHint: true;
@@ -14,4 +28,7 @@ export declare const READ_ONLY: {
14
28
  };
15
29
  export declare function failed(text: string): CallToolResult;
16
30
  export declare function run(entry: Entry, work: () => Promise<Record<string, unknown>>): Promise<CallToolResult>;
31
+ 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.";
32
+ 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.";
33
+ export declare const optionalText: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
17
34
  export declare function registerTools(server: McpServer, deps: ServerDeps): void;
package/dist/tools.js CHANGED
@@ -1,7 +1,10 @@
1
1
  import { MARKET_TYPES } from "@polytest/sdk";
2
2
  import * as z from "zod/v4";
3
3
  import { fitRows, MAX_OUTPUT_CHARS, projectMarket, projectMarketRow, projectSnapshot } from "./budget.js";
4
- import { explainError, withRetry } from "./failures.js";
4
+ import { explainError, reasonOf, withRetry } from "./failures.js";
5
+ export function toolMeta(deps) {
6
+ return deps.securitySchemes === undefined ? {} : { _meta: { securitySchemes: deps.securitySchemes } };
7
+ }
5
8
  export const READ_ONLY = {
6
9
  readOnlyHint: true,
7
10
  destructiveHint: false,
@@ -21,6 +24,23 @@ export async function run(entry, work) {
21
24
  return failed(explainError(error, entry));
22
25
  }
23
26
  }
27
+ // Verified on production order books: both prices are the best ask of their side.
28
+ 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.";
29
+ 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.";
30
+ const WINDOW_MS = {
31
+ "5m": 5 * 60_000,
32
+ "15m": 15 * 60_000,
33
+ "1hr": 60 * 60_000,
34
+ "4hr": 4 * 60 * 60_000,
35
+ "24hr": 24 * 60 * 60_000,
36
+ };
37
+ // Slack past one window before the newest market counts as old.
38
+ const FRESH_SLACK_MS = 30 * 60_000;
39
+ // Some models send "" for an optional string they mean to leave out.
40
+ export const optionalText = z
41
+ .string()
42
+ .optional()
43
+ .transform((value) => (value === "" ? undefined : value));
24
44
  const marketRow = {
25
45
  market_id: z.string(),
26
46
  slug: z.string(),
@@ -33,17 +53,25 @@ const marketRow = {
33
53
  winner: z.string().nullable().describe("Winning side once the market resolves. A tie resolves Up."),
34
54
  final_volume: z.number().nullable(),
35
55
  resolved_at: z.string().nullable(),
56
+ status: z
57
+ .enum(["upcoming", "open", "resolved", "ended_no_result"])
58
+ .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
59
  };
60
+ // A pasted Polymarket link carries the slug as its last path segment, and a slug never contains a slash.
61
+ function slugFromLink(value) {
62
+ const path = value.split(/[?#]/)[0] ?? value;
63
+ return path.split("/").filter((part) => part !== "").at(-1) ?? value;
64
+ }
37
65
  const listMarketsInput = z.object({
38
66
  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
67
+ coin: z
41
68
  .string()
42
- .optional()
69
+ .default("btc")
70
+ .transform((value) => (value === "" ? "btc" : value))
71
+ .describe("Coin symbol in lowercase: btc, eth, or sol. 4hr and 24hr markets exist for btc only."),
72
+ start_time: optionalText
43
73
  .describe("ISO 8601. Keeps markets that start at or after this time. No zone means UTC."),
44
- end_time: z
45
- .string()
46
- .optional()
74
+ end_time: optionalText
47
75
  .describe("ISO 8601. Keeps markets that start at or before this time. No zone means UTC."),
48
76
  limit: z.number().int().min(1).max(100).default(20).describe("Rows per page."),
49
77
  offset: z.number().int().min(0).default(0).describe("Rows to skip. Pass next_offset from the previous page."),
@@ -57,11 +85,10 @@ const listMarketsOutput = z.object({
57
85
  note: z.string().optional(),
58
86
  });
59
87
  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."),
88
+ market_id: optionalText.describe("PolyTest market id. Pass this or slug, not both."),
89
+ slug: optionalText
90
+ .transform((value) => (value === undefined ? undefined : slugFromLink(value)))
91
+ .describe("A Polymarket event URL, or its last path segment. Pass this or market_id, not both."),
65
92
  });
66
93
  const getMarketOutput = z.object({
67
94
  market: z.object({
@@ -77,13 +104,9 @@ const getMarketOutput = z.object({
77
104
  });
78
105
  const getSnapshotsInput = z.object({
79
106
  market_id: z.string().describe("PolyTest market id from polytest_list_markets or polytest_get_market."),
80
- start_time: z
81
- .string()
82
- .optional()
107
+ start_time: optionalText
83
108
  .describe("ISO 8601. Keeps snapshots at or after this time. No zone means UTC."),
84
- end_time: z
85
- .string()
86
- .optional()
109
+ end_time: optionalText
87
110
  .describe("ISO 8601. Keeps snapshots at or before this time. No zone means UTC."),
88
111
  limit: z.number().int().min(1).max(200).default(50).describe("Rows per page. At most 20 with order books."),
89
112
  offset: z
@@ -108,8 +131,8 @@ const getSnapshotsOutput = z.object({
108
131
  snapshots: z.array(z.object({
109
132
  time: z.string(),
110
133
  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."),
134
+ price_up: z.number().nullable().describe(PRICE_UP),
135
+ price_down: z.number().nullable().describe(PRICE_DOWN),
113
136
  orderbook_up: book.optional(),
114
137
  orderbook_down: book.optional(),
115
138
  })),
@@ -159,20 +182,32 @@ function projectLimits(limits) {
159
182
  },
160
183
  };
161
184
  }
162
- // Some models send "" for an optional string they mean to leave out.
163
185
  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 };
186
+ if (market_id !== undefined && slug === undefined)
187
+ return { market_id };
188
+ if (slug !== undefined && market_id === undefined)
189
+ return { slug };
170
190
  return null;
171
191
  }
172
192
  function note(parts) {
173
193
  const text = parts.filter((part) => part !== undefined).join(" ");
174
194
  return text === "" ? {} : { note: text };
175
195
  }
196
+ // A server warning ends with a call to upgrade. Only its first sentence, which says what was left out, is kept.
197
+ function warningNote(warning) {
198
+ return warning === undefined ? undefined : reasonOf(warning);
199
+ }
200
+ // The newest market starting well before now means PolyTest has not loaded the most recent markets yet.
201
+ function ageNote(newest, nowMs) {
202
+ if (newest === undefined)
203
+ return undefined;
204
+ const age = nowMs - Date.parse(newest.start_time);
205
+ const window = WINDOW_MS[newest.market_type] ?? 0;
206
+ if (!(age > window + FRESH_SLACK_MS))
207
+ return undefined;
208
+ const hours = (age / 3_600_000).toFixed(1);
209
+ 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.`;
210
+ }
176
211
  function skippedNote(skipped) {
177
212
  if (skipped <= 0)
178
213
  return undefined;
@@ -181,16 +216,22 @@ function skippedNote(skipped) {
181
216
  : `${skipped} rows could not be read and were left out.`;
182
217
  }
183
218
  export function registerTools(server, deps) {
219
+ const now = deps.now ?? Date.now;
184
220
  server.registerTool("polytest_list_markets", {
185
221
  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.',
222
+ 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
223
  inputSchema: listMarketsInput,
188
224
  outputSchema: listMarketsOutput,
189
225
  annotations: READ_ONLY,
226
+ ...toolMeta(deps),
190
227
  }, ({ market_type, coin, start_time, end_time, limit, offset }, ctx) => run(deps.entry, async () => {
191
228
  const client = deps.client();
192
229
  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);
230
+ const nowMs = now();
231
+ const rows = page.items.map((market) => projectMarketRow(market, nowMs));
232
+ // Only the first page of an open-ended range starts at the newest market PolyTest has.
233
+ const newest = offset === 0 && end_time === undefined ? rows[0] : undefined;
234
+ const fitted = fitRows(rows, MAX_OUTPUT_CHARS);
194
235
  // The Page type is shared, but only the snapshots route ever stops on its offset cap.
195
236
  const stop = page.stop === "snapshot_offset_cap" ? "end" : page.stop;
196
237
  return {
@@ -199,15 +240,16 @@ export function registerTools(server, deps) {
199
240
  stop: fitted.truncated ? "more" : stop,
200
241
  next_offset: fitted.truncated ? page.offset + fitted.rows.length : page.nextOffset,
201
242
  truncated: fitted.truncated,
202
- ...note([page.warning, skippedNote(page.skipped)]),
243
+ ...note([warningNote(page.warning), skippedNote(page.skipped), ageNote(newest, nowMs)]),
203
244
  };
204
245
  }));
205
246
  server.registerTool("polytest_get_market", {
206
247
  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.",
248
+ 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
249
  inputSchema: getMarketInput,
209
250
  outputSchema: getMarketOutput,
210
251
  annotations: READ_ONLY,
252
+ ...toolMeta(deps),
211
253
  }, async ({ market_id, slug }, ctx) => {
212
254
  const ref = marketRef(market_id, slug);
213
255
  if (ref === null)
@@ -215,7 +257,7 @@ export function registerTools(server, deps) {
215
257
  return run(deps.entry, async () => {
216
258
  const client = deps.client();
217
259
  const market = await withRetry(() => client.market(ref, { signal: ctx.mcpReq.signal }), deps.retry);
218
- return { market: projectMarket(market) };
260
+ return { market: projectMarket(market, now()) };
219
261
  });
220
262
  });
221
263
  server.registerTool("polytest_get_snapshots", {
@@ -224,6 +266,7 @@ export function registerTools(server, deps) {
224
266
  inputSchema: getSnapshotsInput,
225
267
  outputSchema: getSnapshotsOutput,
226
268
  annotations: READ_ONLY,
269
+ ...toolMeta(deps),
227
270
  }, ({ market_id, start_time, end_time, limit, offset, include_orderbook, orderbook_depth }, ctx) => run(deps.entry, async () => {
228
271
  const sent = include_orderbook ? Math.min(limit, BOOK_PAGE_MAX) : limit;
229
272
  const client = deps.client();
@@ -241,17 +284,18 @@ export function registerTools(server, deps) {
241
284
  sent < limit
242
285
  ? `The limit was lowered from ${limit} to ${sent} because order books are included.`
243
286
  : undefined,
244
- page.warning,
287
+ warningNote(page.warning),
245
288
  skippedNote(page.skipped),
246
289
  ]),
247
290
  };
248
291
  }));
249
292
  server.registerTool("polytest_get_limits", {
250
293
  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.",
294
+ 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
295
  inputSchema: z.object({}),
253
296
  outputSchema: getLimitsOutput,
254
297
  annotations: READ_ONLY,
298
+ ...toolMeta(deps),
255
299
  }, (_args, ctx) => run(deps.entry, async () => {
256
300
  const client = deps.client();
257
301
  return projectLimits(await withRetry(() => client.limits({ signal: ctx.mcpReq.signal }), deps.retry));
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.0";
1
+ export declare const VERSION = "0.2.1";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = "0.1.0";
1
+ export const VERSION = "0.2.1";
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@polytest/mcp",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
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": {