Skip to main content
Glama
PaulieB14

graph-polymarket-mcp

query_subgraph

Run custom GraphQL queries on Polymarket prediction market subgraphs to access market stats, trader P&L, positions, and orderbook activity.

Instructions

Execute a custom GraphQL query against a Polymarket subgraph

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
subgraphYesSubgraph identifier: main, beefy_pnl, slimmed_pnl, activity, or orderbook
queryYesGraphQL query string
variablesNoOptional GraphQL variables as key-value pairs

Implementation Reference

  • src/index.ts:105-129 (registration)
    Registration of the 'query_subgraph' tool as an MCP tool. Defines inputSchema with subgraph enum, query string, and optional variables. The handler looks up the subgraph config by name and calls the querySubgraph helper.
    server.registerTool(
      "query_subgraph",
      {
        description: "Execute a custom GraphQL query against a Polymarket subgraph",
        inputSchema: {
          subgraph: z
            .enum(SUBGRAPH_NAMES)
            .describe("Subgraph identifier: main, beefy_pnl, slimmed_pnl, activity, or orderbook"),
          query: z.string().describe("GraphQL query string"),
          variables: z
            .record(z.unknown())
            .optional()
            .describe("Optional GraphQL variables as key-value pairs"),
        },
      },
      async ({ subgraph, query, variables }) => {
        try {
          const cfg = SUBGRAPHS[subgraph];
          const data = await querySubgraph(cfg.ipfsHash, query, variables);
          return textResult(data);
        } catch (error) {
          return errorResult(error);
        }
      }
    );
  • The handler function for the query_subgraph tool. It takes subgraph name, GraphQL query string, and optional variables, resolves the ipfsHash from SUBGRAPHS config, and delegates to querySubgraph.
      async ({ subgraph, query, variables }) => {
        try {
          const cfg = SUBGRAPHS[subgraph];
          const data = await querySubgraph(cfg.ipfsHash, query, variables);
          return textResult(data);
        } catch (error) {
          return errorResult(error);
        }
      }
    );
  • Core helper function that executes the actual GraphQL query against The Graph's decentralized network. Uses GRAPH_API_KEY env var, sends POST request to the gateway with the subgraph deployment IPFS hash, and returns the data or throws on HTTP/GraphQL errors.
    export async function querySubgraph(
      ipfsHash: string,
      query: string,
      variables?: Record<string, unknown>
    ): Promise<unknown> {
      const apiKey = process.env.GRAPH_API_KEY;
      if (!apiKey) {
        throw new GraphClientError(
          "GRAPH_API_KEY environment variable is required. " +
            "Get one at https://thegraph.com/studio/apikeys/"
        );
      }
    
      const url = `https://gateway.thegraph.com/api/${apiKey}/deployments/id/${ipfsHash}`;
    
      const body: Record<string, unknown> = { query };
      if (variables && Object.keys(variables).length > 0) {
        body.variables = variables;
      }
    
      const response = await fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
    
      if (!response.ok) {
        throw new GraphClientError(
          `Graph API returned HTTP ${response.status}: ${response.statusText}`,
          response.status
        );
      }
    
      const json = (await response.json()) as {
        data?: unknown;
        errors?: unknown[];
      };
    
      if (json.errors && json.errors.length > 0) {
        throw new GraphClientError(
          `GraphQL errors: ${JSON.stringify(json.errors)}`,
          undefined,
          json.errors
        );
      }
    
      return json.data;
    }
  • Input schema definition for the query_subgraph tool using Zod. Validates subgraph as an enum from SUBGRAPH_NAMES, query as a string, and variables as an optional record of unknown values.
    inputSchema: {
      subgraph: z
        .enum(SUBGRAPH_NAMES)
        .describe("Subgraph identifier: main, beefy_pnl, slimmed_pnl, activity, or orderbook"),
      query: z.string().describe("GraphQL query string"),
      variables: z
        .record(z.unknown())
        .optional()
        .describe("Optional GraphQL variables as key-value pairs"),
    },
  • Subgraph configuration mapping (used by the tool handler to resolve subgraph name to IPFS hash). Also exports SUBGRAPH_NAMES used in the schema enum validation.
    export const SUBGRAPHS: Record<string, SubgraphConfig> = {
      main: {
        name: "Main",
        ipfsHash: "QmdyCguLEisTtQFveEkvMhTH7UzjyhnrF9kpvhYeG4QX8a",
        description:
          "Core Polymarket subgraph with markets, conditions, and trader counts. Best for: market discovery, condition resolution status, and counting open/closed markets. NOTE: volume/fee fields in Global are zeroed out — use the orderbook subgraph for accurate volume data.",
        keyEntities: [
          "Global (numConditions, numOpenConditions, numClosedConditions, numTraders)",
          "Condition (oracle, questionId, outcomeSlotCount, resolutionTimestamp, payoutNumerators)",
          "Account",
          "MarketData",
          "Transaction",
        ],
      },
      beefy_pnl: {
        name: "Beefy Profit and Loss",
        ipfsHash: "QmbHwcGkumWdyTK2jYWXV3vX4WyinftEGbuwi7hDkhPWqG",
        description:
          "The most comprehensive Polymarket analytics subgraph. UNIQUE FEATURES not available elsewhere: (1) Hedge fund-grade account metrics — winRate, profitFactor, maxDrawdown computed on-chain per trader. (2) Per-position P&L with realizedPnl, unrealizedPnl, cost basis (valueBought/valueSold). (3) Daily time-series — query as dailyStats_collection (NOT dailyStats) for daily volume, fees, numTraders, numNewMarkets, numResolvedMarkets. (4) Market-level analytics — currentPrice, numBuyers, numSellers. Best for: trader performance analysis, portfolio analytics, P&L tracking, and historical trend data.",
        keyEntities: [
          "Account (winRate, profitFactor, maxDrawdown, numWinning/LosingPositions)",
          "MarketPosition (realizedPnl, unrealizedPnl, valueBought, valueSold)",
          "dailyStats_collection (date, volume, fees, numTraders, numNewMarkets, numResolvedMarkets) — use _collection suffix for list queries",
          "Market (currentPrice, numBuyers, numSellers)",
          "MarketProfit",
          "Transaction",
          "TokenPosition",
          "UserStats",
        ],
      },
      slimmed_pnl: {
        name: "Slimmed P&L",
        ipfsHash: "QmZAYiMeZiWC7ZjdWepek7hy1jbcW3ngimBF9ibTiTtwQU",
        description:
          "Lightweight position tracker. Stores user token holdings with amount, avgPrice, realizedPnl, and totalBought. Best for: quick position lookups when you just need current holdings without full analytics. NOTE: indexers on this subgraph can lag; if queries fail with 'too far behind' errors, use the beefy_pnl subgraph instead.",
        keyEntities: ["UserPosition (amount, avgPrice, realizedPnl, totalBought)", "NegRiskEvent", "Condition", "FPMM"],
      },
      activity: {
        name: "Activity",
        ipfsHash: "Qmf3qPUsfQ8et6E3QNBmuXXKqUJi91mo5zbsaTkQrSnMAP",
        description:
          "Event log for position management operations. Tracks splits (minting outcome tokens), merges (combining tokens back to collateral), and redemptions (claiming payouts from resolved markets). Best for: monitoring position lifecycle events, tracking when users enter/exit markets, and auditing collateral flows.",
        keyEntities: [
          "Split (stakeholder, condition, amount, timestamp)",
          "Merge (stakeholder, condition, amount, timestamp)",
          "Redemption (redeemer, condition, payout, indexSets)",
          "NegRiskConversion",
          "NegRiskEvent",
        ],
      },
      orderbook: {
        name: "Orderbook",
        ipfsHash: "QmVGA9vvNZtEquVzDpw8wnTFDxVjB6mavTRMTrKuUBhi4t",
        description:
          "Detailed orderbook trading data and authoritative platform-wide volume. Every order fill with maker/taker, price, side, fee, and asset IDs. IMPORTANT: Use ordersMatchedGlobals for accurate total volume ($72B+), trade counts, and fees — the main subgraph Global entity has zeroed volume fields. Best for: analyzing trading patterns, tracking specific maker/taker activity, order flow analysis, per-market trade statistics, and platform volume metrics.",
        keyEntities: [
          "OrderFilledEvent (maker, taker, price, side, fee, amounts)",
          "OrdersMatchedEvent",
          "Orderbook (per-token trade stats)",
          "Global (platform-wide trade counts)",
          "Account (per-trader volume and activity)",
        ],
      },
      open_interest: {
        name: "Open Interest",
        ipfsHash: "QmbT2MmS2VGbGihiTUmWk6GMc2QYqoT9ZhiupUicYMWt6H",
        description:
          "The only Polymarket subgraph dedicated to open interest. Tracks USDC currently locked in outstanding YES/NO positions per market, with hourly snapshots for time-series analysis. OI is computed from PositionSplit (increases) and PositionsMerge (decreases) events on the ConditionalTokens contract. IMPORTANT: Polymarket does NOT use on-chain PayoutRedemption — winners sell shares on the orderbook or merge positions instead. This means resolved markets will still show residual OI from losing-side tokens that will never be redeemed. High OI on a resolved market = dead money (worthless losing tokens), not unclaimed winnings. Best for: identifying markets with the most capital at risk, charting OI trends over time, and detecting capital flow shifts across markets.",
        keyEntities: [
          "MarketOpenInterest (amount in USDC, splitCount, mergeCount — cross-reference with main subgraph for resolution status)",
          "OISnapshot (hourly bucketed OI per market — amount, timestamp, blockNumber)",
          "GlobalOpenInterest (total OI across all markets, marketCount)",
        ],
      },
      resolution: {
        name: "Market Resolution",
        ipfsHash: "QmZnnrHWCB1Mb8dxxXDxfComjNdaGyRC66W8derjn3XDPg",
        description:
          "Tracks the full UMA oracle resolution lifecycle for every Polymarket question. Each MarketResolution entity captures the current status (initialized → proposed → resolved), whether it was disputed, proposed/reproposed prices, and moderator flags. Revision entities log moderator updates with timestamps. Best for: monitoring market resolution progress, detecting disputed outcomes, auditing oracle activity, and checking if a market was flagged or paused.",
        keyEntities: [
          "MarketResolution (questionId, status, proposedPrice, price, flagged, paused, wasDisputed)",
          "Revision (moderator, questionId, timestamp, update)",
          "Moderator (address, canMod)",
          "AncillaryDataHashToQuestionId (maps ancillary data to questionId)",
        ],
      },
      traders: {
        name: "Traders",
        ipfsHash: "QmfT4YQwFfAi77hrC2JH3JiPF7C4nEn27UQRGNpSpUupqn",
        description:
          "Per-trader event log indexing every CTF interaction and USDC flow. Each Trader has a derived list of CTFEvents (splits, merges, transfers, resolutions, redemptions) and USDCTransfers (inbound/outbound with amounts). Best for: building trader profiles, tracking when a wallet first appeared, reconstructing a trader's full on-chain history, and analyzing USDC deposit/withdrawal patterns.",
        keyEntities: [
          "Trader (address, firstSeenBlock, firstSeenTimestamp)",
          "CTFEvent (eventType, conditionId, amounts, timestamp) — immutable, @derivedFrom trader",
          "USDCTransfer (from, to, amount, isInbound, timestamp) — immutable, @derivedFrom trader",
        ],
      },
    };
Behavior2/5

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

No annotations exist, and the description does not disclose behavioral traits like rate limits, response structure, or side effects. The bare description adds minimal transparency beyond the obvious.

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?

Single sentence with no wasted words. Efficiently communicates the core function.

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?

Without an output schema, the description should hint at return values; it does not. The subgraph parameter description is incomplete. For a flexible query tool, more context on capabilities and constraints is needed.

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

Parameters2/5

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

Schema description coverage is 100%, but the enum description for 'subgraph' lists only 5 values while the schema includes 8, making it incomplete and potentially misleading. Other parameter descriptions are tautological ('GraphQL query string', 'Optional GraphQL variables').

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 tool executes a custom GraphQL query against a Polymarket subgraph, specifying verb and resource. It distinguishes from sibling tools that retrieve specific data points.

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?

No guidance is provided on when to use this tool vs. the many sibling get_* tools. No alternatives or exclusions are mentioned.

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/PaulieB14/graph-polymarket-mcp'

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