Skip to main content
Glama

prediction_markets_markets_by_topic

Retrieve top prediction markets for a specific topic on Polymarket using a topic slug, returning JSON data with market titles, volumes, and outcome probabilities.

Instructions

Call after you have a Polymarket topic slug (from the user or prediction_markets_trending_topics) and need the top markets under it.

Parameters

topic_slug : str Identifier such as "trump-presidency". limit : int, default 10 Number of markets to return, ranked by 24-hour volume (desc).

Returns

str JSON array of objects with the schema: [ { "title": "Trump to win 2024?", "volume": 123456.78, "outcomes": [ {"option": "Yes", "probability": 0.42}, {"option": "No", "probability": 0.58} ] }, … ] Parse with json.loads.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
limitNo
topic_slugYes

Implementation Reference

  • main.py:27-60 (handler)
    MCP tool handler function for prediction_markets_markets_by_topic. Decorated with @mcp.tool for registration. Fetches markets using poly.markets_by_topic and returns JSON string.
    @mcp.tool
    async def prediction_markets_markets_by_topic(topic_slug: str, limit: int = 10) -> str:
        """
        Call after you have a Polymarket topic slug (from the user or
        `prediction_markets_trending_topics`) and need the top markets under it.
    
        Parameters
        ----------
        topic_slug : str
            Identifier such as "trump-presidency".
        limit : int, default 10
            Number of markets to return, ranked by 24-hour volume (desc).
    
        Returns
        -------
        str
            JSON array of objects with the schema:
            [
              {
                "title": "Trump to win 2024?",
                "volume": 123456.78,
                "outcomes": [
                  {"option": "Yes", "probability": 0.42},
                  {"option": "No",  "probability": 0.58}
                ]
              },
              …
            ]
            Parse with `json.loads`.
        """
    
        markets = await poly.markets_by_topic(topic_slug, limit)
        return json.dumps([m.model_dump() for m in markets])
  • Pydantic models defining the structure of market outcomes and markets returned by the tool.
    class MarketOutcome(BaseModel):
        option: str
        probability: float
    
    
    class Markets(BaseModel):
        title: str
        volume: float
        outcomes: list[MarketOutcome]
  • Helper function that scrapes Polymarket webpage to derive topic slug and queries the API for markets by topic, returning structured Markets objects.
    async def markets_by_topic(tab_name: str, limit: int = 10) -> list[Markets]:
        async with async_playwright() as p:
            browser = await p.chromium.launch(headless=True)
            page = await browser.new_page()
            await page.goto("https://polymarket.com", wait_until="domcontentloaded")
    
            tab = page.get_by_role("tab", name=tab_name)
            slug_full = await tab.get_attribute(
                "aria-controls"
            )  # e.g. radix-:r6p:-content-big-beautiful-bill
            if not slug_full:
                raise ValueError(f"Tab '{tab_name}' not found or has no slug.")
    
            tag_slug = slug_full.split("-content-")[-1]  # → 'big-beautiful-bill'
    
            # build the API URL
            base = "https://gamma-api.polymarket.com/events/pagination"
            query = dict(
                limit=limit,
                active="true",
                archived="false",
                tag_slug=tag_slug,
                closed="false",
                order="volume24hr",
                ascending="false",
                offset=0,
            )
            url = f"{base}?{urlencode(query)}"
    
            data = requests.get(url, timeout=15).json()["data"]
            res: list[Markets] = []
            for e in data:
                try:
                    outcomes = [
                        MarketOutcome(
                            option=outcome,
                            probability=float(price),
                        )
                        for outcome, price in zip(
                            json.loads(e["markets"][0]["outcomes"]),
                            json.loads(e["markets"][0]["outcomePrices"]),
                        )
                    ]
                    res.append(
                        Markets(title=e["title"], volume=e["volume"], outcomes=outcomes)
                    )
                except Exception as ex:
                    print(e["markets"][0])
                    raise ex
    
            return res
  • main.py:27-27 (registration)
    The @mcp.tool decorator registers the function as an MCP tool.
    @mcp.tool
Behavior4/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes key traits: it's a read operation (implied by 'returns'), specifies ranking criteria ('ranked by 24-hour volume (desc)'), and details the return format (JSON array with schema). However, it doesn't mention potential errors, rate limits, or authentication needs, leaving some behavioral aspects uncovered.

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 appropriately sized and front-loaded: the first sentence states the purpose and usage context, followed by a structured 'Parameters' and 'Returns' section. Every sentence earns its place by providing critical information without redundancy, making it efficient and well-organized.

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

Completeness5/5

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

Given the tool's moderate complexity (2 parameters, no annotations, no output schema), the description is complete enough. It covers purpose, usage guidelines, parameter semantics, and detailed return format (including schema and parsing instructions). The absence of an output schema is compensated by the thorough 'Returns' section, ensuring the agent can understand and use the tool effectively.

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

Parameters5/5

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

Given 0% schema description coverage, the description fully compensates by explaining both parameters: 'topic_slug' is described as an 'Identifier such as "trump-presidency"', and 'limit' as 'Number of markets to return, ranked by 24-hour volume (desc)' with a default value. This adds essential meaning beyond the bare schema, making the parameters clear and actionable.

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

Purpose5/5

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

The description clearly states the specific action ('Call after you have a Polymarket topic slug... and need the top markets under it') and distinguishes it from sibling tools by mentioning when to use it versus 'prediction_markets_trending_topics' for obtaining the slug. It specifies the verb ('need the top markets') and resource ('markets under [a topic]'), making the purpose explicit and differentiated.

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use this tool: 'Call after you have a Polymarket topic slug (from the user or `prediction_markets_trending_topics`)'. It distinguishes from the sibling 'prediction_markets_trending_topics' by indicating that tool as a source for the slug, and implicitly contrasts with 'search_prediction_markets' by focusing on top markets by topic rather than a general search.

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

Related 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/fernandezpablo85/polymarket-mcp'

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