Skip to main content
Glama
PaulieB14

graph-polymarket-mcp

get_oi_history

Retrieve hourly open interest snapshots for a Polymarket market to chart OI trends over time.

Instructions

Get hourly open interest snapshots for a specific Polymarket market. Use this to chart OI trends over time. The conditionId can be obtained from get_market_open_interest or the main subgraph.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
conditionIdYesThe conditionId (hex string) of the market
firstNoNumber of hourly snapshots to return (default 168 = 1 week)
orderDirectionNoSort direction by timestampdesc

Implementation Reference

  • src/index.ts:658-691 (registration)
    Registration of the 'get_oi_history' tool via server.registerTool with the name 'get_oi_history'. The input schema expects a conditionId (string), first (number, default 168), and orderDirection (enum 'asc' or 'desc', default 'desc').
    server.registerTool(
      "get_oi_history",
      {
        description:
          "Get hourly open interest snapshots for a specific Polymarket market. Use this to chart OI trends over time. The conditionId can be obtained from get_market_open_interest or the main subgraph.",
        inputSchema: {
          conditionId: z.string().describe("The conditionId (hex string) of the market"),
          first: z.number().min(1).max(1000).default(168).describe("Number of hourly snapshots to return (default 168 = 1 week)"),
          orderDirection: z.enum(["asc", "desc"]).default("desc").describe("Sort direction by timestamp"),
        },
      },
      async ({ conditionId, first, orderDirection }) => {
        try {
          const query = `{
            oisnapshots(
              first: ${first},
              orderBy: timestamp,
              orderDirection: ${orderDirection},
              where: { market: "${conditionId.toLowerCase()}" }
            ) {
              id
              amount
              amountRaw
              blockNumber
              timestamp
            }
          }`;
          const data = await querySubgraph(SUBGRAPHS.open_interest.ipfsHash, query);
          return textResult(data);
        } catch (error) {
          return errorResult(error);
        }
      }
    );
  • The handler function that executes the tool logic. It queries the 'open_interest' subgraph (ipfsHash from SUBGRAPHS.open_interest) for oisnapshots filtered by market (conditionId), ordered by timestamp. Returns hourly OI snapshots with id, amount, amountRaw, blockNumber, and timestamp fields.
      async ({ conditionId, first, orderDirection }) => {
        try {
          const query = `{
            oisnapshots(
              first: ${first},
              orderBy: timestamp,
              orderDirection: ${orderDirection},
              where: { market: "${conditionId.toLowerCase()}" }
            ) {
              id
              amount
              amountRaw
              blockNumber
              timestamp
            }
          }`;
          const data = await querySubgraph(SUBGRAPHS.open_interest.ipfsHash, query);
          return textResult(data);
        } catch (error) {
          return errorResult(error);
        }
      }
    );
  • The querySubgraph helper is used by the handler to execute the GraphQL query against The Graph's decentralized network, using the open_interest subgraph's IPFS hash.
    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;
    }
  • The textResult and errorResult helpers format the tool's response as JSON content for the MCP protocol.
    function textResult(data: unknown) {
      return {
        content: [{ type: "text" as const, text: JSON.stringify(data, null, 2) }],
      };
    }
    
    function errorResult(error: unknown) {
      const message = error instanceof Error ? error.message : String(error);
      return {
        content: [{ type: "text" as const, text: `Error: ${message}` }],
        isError: true,
      };
    }
  • The input schema for the tool defines conditionId (required string), first (optional number, default 168, max 1000), and orderDirection (optional enum asc/desc, default desc).
    inputSchema: {
      conditionId: z.string().describe("The conditionId (hex string) of the market"),
      first: z.number().min(1).max(1000).default(168).describe("Number of hourly snapshots to return (default 168 = 1 week)"),
      orderDirection: z.enum(["asc", "desc"]).default("desc").describe("Sort direction by timestamp"),
    },
Behavior3/5

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

No annotations exist, so description must cover behavior. It notes hourly snapshots, default count of 168 (1 week), but does not describe return fields or pagination. Adequate but not fully transparent for a tool without output schema.

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?

Two sentences, front-loaded with action and purpose, no extraneous words. Highly concise and well-structured.

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

Completeness4/5

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

With 3 parameters, no output schema, and no annotations, the description covers core purpose and data source. Could mention response format but overall is contextually sufficient for a read-only historical 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?

Schema coverage is 100%, so baseline is 3. Description adds no parameter details beyond the schema, only referencing conditionId source. No additional semantic value.

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 action ('Get hourly open interest snapshots'), specifies the resource ('specific Polymarket market'), and implies distinction from siblings like get_market_open_interest (which likely gives current OI).

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

Usage Guidelines4/5

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

Explicitly tells when to use (chart OI trends) and where to get the conditionId (get_market_open_interest or subgraph). Lacks explicit when-not-to-use or alternative comparison, but context is sufficient.

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