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
          };
        }
      }
    );

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