Skip to main content
Glama
JamesANZ

prediction-market-mcp

get-prediction-markets

Retrieve prediction market prices from Polymarket, PredictIt, and Kalshi by entering a keyword to find current market data for specific events or topics.

Instructions

Get prediction market prices from Polymarket, PredictIt, and Kalshi

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
keywordYesKeyword for the market you're looking for (e.g. 'trump')

Implementation Reference

  • src/index.ts:20-192 (registration)
    Registers the 'get-prediction-markets' tool, defines input schema, and provides the inline handler function that fetches data from Polymarket, PredictIt, and Kalshi APIs, filters by keyword, handles errors, and returns formatted text response.
    server.tool(
      "get-prediction-markets",
      "Get prediction market prices from Polymarket, PredictIt, and Kalshi",
      {
        keyword: z
          .string()
          .max(50)
          .describe("Keyword for the market you're looking for (e.g. 'trump')"),
      },
      async ({ keyword }) => {
        const lowerKeyword = keyword.toLowerCase();
        const errors: string[] = [];
    
        // Try each API separately with error handling
        let polyMarkets: any[] = [];
        let predictItMarkets: any[] = [];
        let kalshiMarkets: any[] = [];
    
        try {
          polyMarkets = await getPolymarketPredictionData(50, keyword);
        } catch (error) {
          errors.push(`Polymarket: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
    
        try {
          predictItMarkets = await getPredictItMarkets();
        } catch (error) {
          errors.push(`PredictIt: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
    
        try {
          kalshiMarkets = await getKalshiEventsWithMarkets(keyword);
        } catch (error) {
          errors.push(`Kalshi: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
    
        const filteredPredictIt = predictItMarkets.filter(
          (m) =>
            m.name.toLowerCase().includes(lowerKeyword) ||
            m.shortName.toLowerCase().includes(lowerKeyword),
        );
    
        const filteredKalshi = kalshiMarkets;
    
        // If all APIs failed
        if (errors.length === 3) {
          return {
            content: [
              {
                type: "text",
                text: `Failed to fetch prediction markets from all platforms:\n${errors.join('\n')}\n\nPlease try again later or check your internet connection.`,
              },
            ],
          };
        }
    
        // If no markets found but some APIs succeeded
        if (
          polyMarkets.length === 0 &&
          filteredPredictIt.length === 0 &&
          filteredKalshi.length === 0
        ) {
          const errorText = errors.length > 0 ? `⚠️ Some platforms failed: ${errors.join('; ')}\n\n` : '';
          return {
            content: [
              {
                type: "text",
                text: `${errorText}No prediction markets found for keyword: "${keyword}"`,
              },
            ],
          };
        }
    
        const polyText = polyMarkets
          .map((m: any) => {
            const oddsList = Object.entries(m.odds)
              .map(([outcome, prob]: [string, any]) => `${outcome}: ${(prob * 100).toFixed(1)}%`)
              .join(" | ");
            return `**Polymarket: ${m.question}**\n${oddsList}`;
          })
          .join("\n\n");
    
        const predictItText = filteredPredictIt
          .map((m: any) => {
            const contractOdds = m.contracts
              .map((c: any) => {
                const pct =
                  c.lastTradePrice != null
                    ? `${(c.lastTradePrice * 100).toFixed(1)}%`
                    : "n/a";
                return `${c.shortName}: ${pct}`;
              })
              .join(" | ");
            return `**PredictIt: ${m.name}**\n${contractOdds}`;
          })
          .join("\n\n");
    
        const kalshiText = filteredKalshi
          .map((e) => {
            if (!e.markets || e.markets.length === 0) {
              return `**Kalshi: ${e.title}**\n${e.sub_title} (${e.category}) - No active markets`;
            }
    
            const marketTexts = e.markets.map((market: KalshiMarket) => {
              // Calculate probability from bid/ask midpoint, or use last price
              const yesBid = parseFloat(market.yes_bid_dollars || "0");
              const yesAsk = parseFloat(market.yes_ask_dollars || "0");
              const noBid = parseFloat(market.no_bid_dollars || "0");
              const noAsk = parseFloat(market.no_ask_dollars || "0");
              const lastPrice = parseFloat(market.last_price_dollars || "0");
    
              let yesProb = "n/a";
              let noProb = "n/a";
    
              // Calculate Yes probability
              if (yesBid > 0 || yesAsk > 0) {
                const yesMid = yesBid > 0 && yesAsk > 0 
                  ? (yesBid + yesAsk) / 2 
                  : lastPrice > 0 
                    ? lastPrice 
                    : yesBid > 0 
                      ? yesBid 
                      : yesAsk;
                yesProb = `${(yesMid * 100).toFixed(1)}%`;
              } else if (lastPrice > 0) {
                yesProb = `${(lastPrice * 100).toFixed(1)}%`;
              }
    
              // Calculate No probability (complement of Yes for binary markets)
              if (noBid > 0 || noAsk > 0) {
                const noMid = noBid > 0 && noAsk > 0 
                  ? (noBid + noAsk) / 2 
                  : (1 - lastPrice) > 0 && lastPrice > 0
                    ? (1 - lastPrice) 
                    : noBid > 0 
                      ? noBid 
                      : noAsk;
                noProb = `${(noMid * 100).toFixed(1)}%`;
              } else if (lastPrice > 0) {
                noProb = `${((1 - lastPrice) * 100).toFixed(1)}%`;
              }
    
              const statusText = market.status && market.status !== "open" && market.status !== "active" && market.status !== "live"
                ? ` [${market.status}]`
                : "";
    
              const marketSubtitle = market.subtitle || market.yes_sub_title || "";
              const subtitleText = marketSubtitle ? ` (${marketSubtitle})` : "";
    
              return `  ${market.yes_sub_title || "Yes"}: ${yesProb} | ${market.no_sub_title || "No"}: ${noProb}${subtitleText}${statusText}`;
            });
    
            const eventSubtitle = e.sub_title ? `\n${e.sub_title}` : "";
            return `**Kalshi: ${e.title}**${eventSubtitle} (${e.category})\n${marketTexts.join("\n")}`;
          })
          .join("\n\n");
    
        const text = [polyText, predictItText, kalshiText]
          .filter(Boolean)
          .join("\n\n");
    
        const errorText = errors.length > 0 ? `⚠️ Some platforms failed: ${errors.join('; ')}\n\n` : '';
    
        return {
          content: [
            {
              type: "text",
              text: errorText + text,
            },
          ],
        };
      },
    );
  • The core handler logic for executing the tool: calls helper functions to fetch data from three prediction market platforms, filters results by keyword, computes probabilities, formats into markdown, and handles API errors gracefully.
      async ({ keyword }) => {
        const lowerKeyword = keyword.toLowerCase();
        const errors: string[] = [];
    
        // Try each API separately with error handling
        let polyMarkets: any[] = [];
        let predictItMarkets: any[] = [];
        let kalshiMarkets: any[] = [];
    
        try {
          polyMarkets = await getPolymarketPredictionData(50, keyword);
        } catch (error) {
          errors.push(`Polymarket: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
    
        try {
          predictItMarkets = await getPredictItMarkets();
        } catch (error) {
          errors.push(`PredictIt: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
    
        try {
          kalshiMarkets = await getKalshiEventsWithMarkets(keyword);
        } catch (error) {
          errors.push(`Kalshi: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
    
        const filteredPredictIt = predictItMarkets.filter(
          (m) =>
            m.name.toLowerCase().includes(lowerKeyword) ||
            m.shortName.toLowerCase().includes(lowerKeyword),
        );
    
        const filteredKalshi = kalshiMarkets;
    
        // If all APIs failed
        if (errors.length === 3) {
          return {
            content: [
              {
                type: "text",
                text: `Failed to fetch prediction markets from all platforms:\n${errors.join('\n')}\n\nPlease try again later or check your internet connection.`,
              },
            ],
          };
        }
    
        // If no markets found but some APIs succeeded
        if (
          polyMarkets.length === 0 &&
          filteredPredictIt.length === 0 &&
          filteredKalshi.length === 0
        ) {
          const errorText = errors.length > 0 ? `⚠️ Some platforms failed: ${errors.join('; ')}\n\n` : '';
          return {
            content: [
              {
                type: "text",
                text: `${errorText}No prediction markets found for keyword: "${keyword}"`,
              },
            ],
          };
        }
    
        const polyText = polyMarkets
          .map((m: any) => {
            const oddsList = Object.entries(m.odds)
              .map(([outcome, prob]: [string, any]) => `${outcome}: ${(prob * 100).toFixed(1)}%`)
              .join(" | ");
            return `**Polymarket: ${m.question}**\n${oddsList}`;
          })
          .join("\n\n");
    
        const predictItText = filteredPredictIt
          .map((m: any) => {
            const contractOdds = m.contracts
              .map((c: any) => {
                const pct =
                  c.lastTradePrice != null
                    ? `${(c.lastTradePrice * 100).toFixed(1)}%`
                    : "n/a";
                return `${c.shortName}: ${pct}`;
              })
              .join(" | ");
            return `**PredictIt: ${m.name}**\n${contractOdds}`;
          })
          .join("\n\n");
    
        const kalshiText = filteredKalshi
          .map((e) => {
            if (!e.markets || e.markets.length === 0) {
              return `**Kalshi: ${e.title}**\n${e.sub_title} (${e.category}) - No active markets`;
            }
    
            const marketTexts = e.markets.map((market: KalshiMarket) => {
              // Calculate probability from bid/ask midpoint, or use last price
              const yesBid = parseFloat(market.yes_bid_dollars || "0");
              const yesAsk = parseFloat(market.yes_ask_dollars || "0");
              const noBid = parseFloat(market.no_bid_dollars || "0");
              const noAsk = parseFloat(market.no_ask_dollars || "0");
              const lastPrice = parseFloat(market.last_price_dollars || "0");
    
              let yesProb = "n/a";
              let noProb = "n/a";
    
              // Calculate Yes probability
              if (yesBid > 0 || yesAsk > 0) {
                const yesMid = yesBid > 0 && yesAsk > 0 
                  ? (yesBid + yesAsk) / 2 
                  : lastPrice > 0 
                    ? lastPrice 
                    : yesBid > 0 
                      ? yesBid 
                      : yesAsk;
                yesProb = `${(yesMid * 100).toFixed(1)}%`;
              } else if (lastPrice > 0) {
                yesProb = `${(lastPrice * 100).toFixed(1)}%`;
              }
    
              // Calculate No probability (complement of Yes for binary markets)
              if (noBid > 0 || noAsk > 0) {
                const noMid = noBid > 0 && noAsk > 0 
                  ? (noBid + noAsk) / 2 
                  : (1 - lastPrice) > 0 && lastPrice > 0
                    ? (1 - lastPrice) 
                    : noBid > 0 
                      ? noBid 
                      : noAsk;
                noProb = `${(noMid * 100).toFixed(1)}%`;
              } else if (lastPrice > 0) {
                noProb = `${((1 - lastPrice) * 100).toFixed(1)}%`;
              }
    
              const statusText = market.status && market.status !== "open" && market.status !== "active" && market.status !== "live"
                ? ` [${market.status}]`
                : "";
    
              const marketSubtitle = market.subtitle || market.yes_sub_title || "";
              const subtitleText = marketSubtitle ? ` (${marketSubtitle})` : "";
    
              return `  ${market.yes_sub_title || "Yes"}: ${yesProb} | ${market.no_sub_title || "No"}: ${noProb}${subtitleText}${statusText}`;
            });
    
            const eventSubtitle = e.sub_title ? `\n${e.sub_title}` : "";
            return `**Kalshi: ${e.title}**${eventSubtitle} (${e.category})\n${marketTexts.join("\n")}`;
          })
          .join("\n\n");
    
        const text = [polyText, predictItText, kalshiText]
          .filter(Boolean)
          .join("\n\n");
    
        const errorText = errors.length > 0 ? `⚠️ Some platforms failed: ${errors.join('; ')}\n\n` : '';
    
        return {
          content: [
            {
              type: "text",
              text: errorText + text,
            },
          ],
        };
      },
    );
  • Zod schema for the tool's input parameter: a string keyword limited to 50 characters.
    {
      keyword: z
        .string()
        .max(50)
        .describe("Keyword for the market you're looking for (e.g. 'trump')"),
    },
  • Helper function to fetch and filter Polymarket data, calculating outcome probabilities from token prices.
    export async function getPolymarketPredictionData(
      limit = 50,
      keyword = "",
    ): Promise<MarketWithOdds[]> {
      const res = await superagent
        .get(`${POLYMARKET_API_BASE}?limit=${limit}`)
        .set("User-Agent", USER_AGENT);
    
      const json = res.body;
    
      if (!Array.isArray(json.data)) {
        throw new Error("Unexpected API response format");
      }
    
      const lowerKeyword = keyword.toLowerCase();
    
      const currentMarkets = json.data.filter(
        (market: Market) =>
          market.active &&
          !market.archived &&
          (market.question?.toLowerCase().includes(lowerKeyword) ||
            market.description?.toLowerCase().includes(lowerKeyword) ||
            market.market_slug?.toLowerCase().includes(lowerKeyword)),
      );
    
      return currentMarkets.map((market: { tokens: any[] }) => {
        const totalPrice = market.tokens.reduce(
          (sum, token) => sum + token.price,
          0,
        );
        const odds: Record<string, number> = {};
        for (const token of market.tokens) {
          odds[token.outcome] = totalPrice > 0 ? token.price / totalPrice : 0;
        }
    
        return { ...market, odds };
      });
    }
  • Helper to fetch open markets from PredictIt.
    export async function getPredictItMarkets(): Promise<PredictItMarket[]> {
      const res = await superagent
        .get(PREDICTIT_API_URL)
        .set("User-Agent", USER_AGENT);
    
      const data: PredictItResponse = res.body;
    
      if (!Array.isArray(data.markets)) {
        throw new Error("Unexpected PredictIt API format");
      }
    
      return data.markets.filter((market) => market.status === "Open");
    }
  • Helper to fetch Kalshi events and their active markets, filtered by keyword.
    export async function getKalshiEventsWithMarkets(
      keyword: string = ""
    ): Promise<KalshiEventWithMarkets[]> {
      const events = await getKalshiMarkets();
      const lowerKeyword = keyword.toLowerCase();
    
      // Filter events by keyword
      const filteredEvents = events.filter(
        (e) =>
          e.title.toLowerCase().includes(lowerKeyword) ||
          e.sub_title.toLowerCase().includes(lowerKeyword) ||
          e.category.toLowerCase().includes(lowerKeyword)
      );
    
      // Fetch market data for filtered events (limit to first 20 to avoid too many API calls)
      const eventsWithMarkets: KalshiEventWithMarkets[] = await Promise.all(
        filteredEvents.slice(0, 20).map(async (event) => {
          const markets = await getKalshiMarketData(event.event_ticker);
          return {
            ...event,
            markets: markets.length > 0 ? markets : undefined,
          };
        })
      );
    
      // Only return events that have active markets
      return eventsWithMarkets.filter((e) => e.markets && e.markets.length > 0);
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. While 'Get' implies a read operation, it doesn't specify whether this requires authentication, has rate limits, returns real-time or historical data, or what format the output takes. For a data retrieval tool with zero annotation coverage, this represents significant gaps in behavioral context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise - a single sentence that efficiently communicates the core functionality. Every word earns its place by specifying the action, resource, and sources. There's no redundancy or unnecessary elaboration, making it easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool that retrieves data from multiple prediction market platforms with no annotations and no output schema, the description is insufficient. It doesn't explain what format the prices come in, whether it returns all markets matching the keyword or just some, how results from different platforms are organized, or any error conditions. The agent lacks critical context to understand what to expect from using this tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, with the single parameter 'keyword' well-documented in the schema. The description doesn't add any parameter-specific information beyond what's already in the schema. This meets the baseline expectation when the schema does the heavy lifting, but doesn't provide additional semantic context about how the keyword parameter affects results across the different platforms.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Get') and resource ('prediction market prices') with specific sources listed (Polymarket, PredictIt, Kalshi). It distinguishes this as a data retrieval operation rather than creation or modification. However, without sibling tools, we cannot assess differentiation from alternatives, preventing a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives, prerequisites, or limitations. It simply states what the tool does without context about appropriate use cases or constraints. This leaves the agent with insufficient information to make informed decisions about tool selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/JamesANZ/prediction-market-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server