Skip to main content
Glama
kukapay

chainlink-feeds-mcp

getLatestPrice

Fetch real-time price data from Chainlink's decentralized on-chain feeds for any trading pair across supported blockchain networks.

Instructions

Fetches the latest price for a given pair on a specified chain

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • index.js:41-90 (handler)
    The async handler function that fetches the latest Chainlink price for a given pair on a specified chain using ethers.js, including validation, provider setup, contract call to latestRoundData, and formatted response.
    async ({ pair, chain }) => {
      try {
        // Validate inputs
        const chainKey = chain.toLowerCase();
        latestPriceSchema.parse({ pair, chain });
    
        // Find feed by pair
        const feed = feedsData[chainKey].feeds.find((f) => f.name.toLowerCase() === pair.toLowerCase());
        if (!feed) {
          throw new Error(`Pair ${pair} not found on chain ${chain}`);
        }
    
        // Initialize provider and contract
        const provider = new ethers.JsonRpcProvider(`${feedsData[chainKey].baseUrl}/${process.env.INFURA_API_KEY}`);
        const priceFeedContract = new ethers.Contract(feed.proxyAddress, priceFeedAbi, provider);
    
        // Fetch decimals and latest round data
        const [decimals, roundData] = await Promise.all([
          priceFeedContract.decimals(),
          priceFeedContract.latestRoundData()
        ]);
    
        const price = ethers.formatUnits(roundData.answer, decimals);
        const timestamp = Number(roundData.updatedAt) * 1000;
    
        return {
          content: [{
            type: 'text',
            text: JSON.stringify({
              chain,
              pair,
              price: Number(price),
              decimals: Number(decimals),
              roundId: roundData.roundId.toString(),
              timestamp: new Date(timestamp).toISOString(),
              proxyAddress: feed.proxyAddress,
              feedCategory: feed.feedCategory
            }, null, 2)
          }]
        };
      } catch (error) {
        return {
          content: [{
            type: 'text',
            text: `Error: ${error.message}`
          }],
          isError: true
        };
      }
    }
  • Zod input schema defining 'pair' and 'chain' parameters with validation for supported chains.
    const latestPriceSchema = z.object({
      pair: z.string().describe('The price feed pair, e.g., FIL/ETH or FDUSD/USD'),
      chain: z.string().refine((val) => feedsData[val.toLowerCase()], {
        message: 'Unsupported chain'
      }).describe('The blockchain network, e.g., ethereum or base')
    });
  • index.js:37-91 (registration)
    MCP server.tool registration call for 'getLatestPrice' tool, including name, description, schema reference, and inline handler.
    server.tool(
      'getLatestPrice',
      'Fetches the latest price for a given pair on a specified chain',
      latestPriceSchema,
      async ({ pair, chain }) => {
        try {
          // Validate inputs
          const chainKey = chain.toLowerCase();
          latestPriceSchema.parse({ pair, chain });
    
          // Find feed by pair
          const feed = feedsData[chainKey].feeds.find((f) => f.name.toLowerCase() === pair.toLowerCase());
          if (!feed) {
            throw new Error(`Pair ${pair} not found on chain ${chain}`);
          }
    
          // Initialize provider and contract
          const provider = new ethers.JsonRpcProvider(`${feedsData[chainKey].baseUrl}/${process.env.INFURA_API_KEY}`);
          const priceFeedContract = new ethers.Contract(feed.proxyAddress, priceFeedAbi, provider);
    
          // Fetch decimals and latest round data
          const [decimals, roundData] = await Promise.all([
            priceFeedContract.decimals(),
            priceFeedContract.latestRoundData()
          ]);
    
          const price = ethers.formatUnits(roundData.answer, decimals);
          const timestamp = Number(roundData.updatedAt) * 1000;
    
          return {
            content: [{
              type: 'text',
              text: JSON.stringify({
                chain,
                pair,
                price: Number(price),
                decimals: Number(decimals),
                roundId: roundData.roundId.toString(),
                timestamp: new Date(timestamp).toISOString(),
                proxyAddress: feed.proxyAddress,
                feedCategory: feed.feedCategory
              }, null, 2)
            }]
          };
        } catch (error) {
          return {
            content: [{
              type: 'text',
              text: `Error: ${error.message}`
            }],
            isError: true
          };
        }
      }
    );
Behavior2/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 states the tool fetches data, implying a read-only operation, but doesn't cover aspects like error handling, rate limits, authentication needs, or response format. This leaves significant gaps in understanding how the tool behaves beyond its basic function.

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 a single, efficient sentence that directly states the tool's purpose without unnecessary words. It is appropriately sized and front-loaded, making it easy to parse quickly, with no wasted information.

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?

Given the lack of annotations and output schema, the description is incomplete for a tool that likely interacts with external data sources. It doesn't explain what 'latest price' entails (e.g., timestamp, source), error cases, or how results are structured, leaving the agent with insufficient context for reliable use.

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

Parameters4/5

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

The input schema has 0 parameters with 100% coverage, so no parameters need documentation. The description mentions 'a given pair on a specified chain', which hints at expected inputs but doesn't add detailed semantics since there are no parameters to describe. This meets the baseline for tools with zero parameters.

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 ('fetches') and target ('latest price for a given pair on a specified chain'), making the purpose understandable. It doesn't explicitly differentiate from siblings like 'queryPriceByRound', but it's specific enough to convey the tool's function without being vague or tautological.

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 such as 'queryPriceByRound' or the list tools. It implies usage for fetching latest prices but lacks explicit context, exclusions, or prerequisites, leaving the agent to infer based on tool names alone.

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/kukapay/chainlink-feeds-mcp'

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