get_token_dex_price
Get DefiLlama spot prices for tokens by chain:address. Input comma-separated identifiers to receive price, decimals, symbol, timestamp, and confidence. Solves the need for reliable DEX price data without external API dependencies.
Instructions
Get DefiLlama oracle spot prices for tokens identified by chain:address.
Use when you have a token's contract address and want a price without
going through CoinGecko/DexScreener — DefiLlama aggregates DEX prices
across many sources. For human-friendly token discovery (search by
symbol/name), use dex_search (DexScreener) or CoinGecko's search.
Args:
coins: Comma-separated chain:address identifiers, e.g.
"ethereum:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48,bsc:0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c".
Chain identifiers follow DefiLlama's naming (e.g. "ethereum",
"bsc", "polygon", "arbitrum", "base", "solana"). Solana uses
"solana:".
Returns:
Object with a coins map keyed by chain:address, where each value
has decimals, price, symbol, timestamp, confidence.
Note: Each chain:address segment of coins is validated. Chain matches
^[a-z0-9-]{1,40}$ and address is EVM hex, Solana base58, or DefiLlama
token id.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| coins | Yes |
Implementation Reference
- coin_mcp/defillama.py:593-620 (handler)Main handler for get_token_dex_price tool. Decorated with @mcp.tool(). Validates the 'coins' parameter via _validate_coins helper, then calls the DefiLlama coins API endpoint to fetch current DEX prices for the specified chain:address tokens.
@mcp.tool() async def get_token_dex_price(coins: str) -> Any: """Get DefiLlama oracle spot prices for tokens identified by `chain:address`. Use when you have a token's contract address and want a price without going through CoinGecko/DexScreener — DefiLlama aggregates DEX prices across many sources. For human-friendly token discovery (search by symbol/name), use `dex_search` (DexScreener) or CoinGecko's `search`. Args: coins: Comma-separated `chain:address` identifiers, e.g. "ethereum:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48,bsc:0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c". Chain identifiers follow DefiLlama's naming (e.g. "ethereum", "bsc", "polygon", "arbitrum", "base", "solana"). Solana uses "solana:<mint-address>". Returns: Object with a `coins` map keyed by `chain:address`, where each value has `decimals`, `price`, `symbol`, `timestamp`, `confidence`. Note: Each `chain:address` segment of `coins` is validated. Chain matches `^[a-z0-9-]{1,40}$` and address is EVM hex, Solana base58, or DefiLlama token id. """ err = _validate_coins(coins) if err is not None: return err return await _http_get(f"{DEFILLAMA_COINS_BASE}/prices/current/{coins}") - coin_mcp/defillama.py:68-81 (schema)Validation helper _validate_coins that checks the 'coins' string parameter. Requires non-empty comma-separated 'chain:address' segments where chain matches ^[a-z0-9-]{1,40}$ and address is EVM hex, Solana base58, or DefiLlama token ID.
def _validate_coins(value: str) -> dict | None: """Validate `chain:address[,chain:address...]` segments for `get_token_dex_price`.""" if not isinstance(value, str) or not value: return {"error": f"invalid coins: must be non-empty string, got {value!r}"} for seg in value.split(","): if not _COINS_SEG.match(seg): return { "error": ( "invalid coins segment: each must be 'chain:address' with " f"chain matching ^[a-z0-9-]{{1,40}}$ and a valid EVM/Solana/" f"DefiLlama address, got {seg!r}" ) } return None - coin_mcp/core.py:58-180 (registration)The @mcp.tool() decorator registers get_token_dex_price with the FastMCP server. MCP instance is created here (line 58-180) and imported/used by defillama.py.
mcp = FastMCP( name="coin-mcp", instructions="""\ This MCP server provides comprehensive cryptocurrency market data from multiple complementary sources: - **CoinGecko** — aggregated market data (volume-weighted prices, market cap, OHLC, history, exchange directory, NFTs, categories, derivatives directory, public-company crypto treasuries, trending searches, search index). - **CCXT** — real-time per-exchange data via a unified API for 100+ centralized exchanges (order books, recent trades, tickers, OHLCV candles, market lists, perpetual-futures funding rates). - **DefiLlama** — protocol-level TVL, chain TVL, stablecoin caps, yield pools, DEX volumes, fees & revenue, oracle token prices. - **DexScreener** — DEX-side prices and liquidity for tokens too small or new for CoinGecko aggregation, across all major chains. - **Alternative.me** — Crypto Fear & Greed Index sentiment indicator. - **Local technical indicators** — RSI, MACD, Bollinger, EMA/SMA, ATR computed in-process from any OHLCV input. ================================================================ HOW TO PICK THE RIGHT TOOL (43 tools total) ================================================================ | Question | Tool | |----------|------| | What's BTC's price right now? | get_price | | Tell me about Solana | get_coin_details | | 30-day price/volume/market-cap chart | get_market_chart | | Daily candlesticks for ETH (aggregated) | get_aggregated_ohlc | | Which exchanges support a coin? | get_coin_tickers | | Coin name -> CoinGecko ID (also exchanges/categories/NFTs) | search | | Top 100 coins by market cap | list_top_coins | | What's hot/trending today? | get_trending | | Biggest 24h gainers and losers | get_top_gainers_losers | | Total market cap, BTC dominance | get_global_market | | DeFi TVL totals (high level, CoinGecko view) | get_global_defi | | Categories (Layer 1, DeFi, Meme...) | list_categories | | Browse all exchanges (CoinGecko directory) | list_exchanges_directory | | Single-exchange metadata (CoinGecko directory) | get_exchange_info | | Derivatives platforms | list_derivatives_exchanges | | NFT collections list | list_nfts | | Single NFT collection detail | get_nft_collection | | Public companies holding BTC/ETH | get_companies_holdings | | What exchanges can I query in real time? | list_supported_exchanges | | All trading pairs on Binance/etc. | get_exchange_markets | | Best bid/ask/last on a specific exchange | get_exchange_ticker | | Real-time order book on a specific exchange | get_orderbook | | Recent public trades on a specific exchange | get_recent_trades | | 1-minute candles on Binance for BTC/USDT | get_exchange_ohlcv | | Funding rate for a perp | get_funding_rate | | Sentiment: fearful or greedy? | get_fear_greed_index | | Compute RSI/MACD/Bollinger/ATR/etc on OHLCV | compute_indicators | | Per-protocol TVL / TVL history | get_protocol_tvl | | Browse DefiLlama protocols by TVL | list_protocols | | Chain-level TVL ranking (Ethereum, Solana, ...) | list_chains_tvl | | Historical TVL for one chain or all of DeFi | get_chain_tvl_history | | Stablecoin caps and chain breakdown | list_stablecoins | | Yield-pool APYs | list_yield_pools | | DEX 24h volume rankings | list_dex_volumes | | Per-protocol fees and revenue | list_fees_revenue | | DefiLlama oracle price for `chain:address` tokens | get_token_dex_price | | DEX price for a small/new token (any chain) | dex_search | | All DEX pairs for a given token address | get_dex_token_pairs | | Single DEX pair detail | get_dex_pair | | Newly profiled DEX tokens | list_latest_dex_tokens | | Currently boosted (paid) DEX tokens | list_top_boosted_tokens | | What's currently cached (rate-limit relief) | cache_stats | | Drop the HTTP cache | clear_cache | | Funding-rate time series for a perp | get_funding_rate_history | | Current open interest for a perp | get_open_interest | | Compare funding rates across exchanges | compare_funding_rates | | Are all data sources healthy / fast? | health_check | | Same coin's price across CG + multiple CEX + DEX | compare_prices | | Best bid/ask merged across many exchanges | get_consolidated_orderbook | ================================================================ KEY THINGS TO REMEMBER ================================================================ 1. **CoinGecko uses coin IDs**, not ticker symbols. IDs look like "bitcoin", "ethereum", "solana". Resolve unknown names via `search` first. 2. **CCXT uses unified symbols + exchange IDs.** Symbols: "BTC/USDT", "ETH/USD". Linear perps use settle suffix: "BTC/USDT:USDT". Exchange IDs are lowercase ("binance", "okx", "coinbase", "kraken", "bybit", "kucoin"). 3. **Aggregated vs per-exchange.** CoinGecko = volume-weighted across all venues. CCXT = one specific exchange. Use CoinGecko for "the market"; use CCXT for venue-specific or sub-hour granularity. 4. **DEX vs CEX prices.** For tokens listed on CoinGecko, prefer CoinGecko/ CCXT. For new/long-tail tokens, use DexScreener (`dex_search`, `get_dex_token_pairs`, `get_dex_pair`) or DefiLlama (`get_token_dex_price`). 5. **Default vs_currency is "usd"**. CCXT symbols already encode quote currency. 6. **Rate limits.** CoinGecko public allows ~30 req/min — but this server caches responses with TTLs tuned per endpoint. Repeated identical calls come from cache; check `cache_stats` if surprised by stale data, and `clear_cache` to force-refresh everything. 7. **Time ranges.** `get_market_chart` and `get_aggregated_ohlc` accept a `days` parameter. CoinGecko auto-selects granularity: minute when days<=1, hourly when days<=90, daily otherwise. 8. **Presentation.** Tools return raw numbers. Format prices/percentages/ timestamps appropriately when answering the user. ================================================================ NAMING & VALIDATION CONVENTIONS ================================================================ - Coin / exchange / NFT IDs must match `^[a-z0-9._-]+$` (lowercase slugs). - Token addresses are either EVM (`0x` followed by 40 hex chars) or Solana base58 (32-44 chars). Tools validate the shape before sending requests. - Tools never run network requests until validation passes — invalid input returns a `{"error": ...}` envelope synchronously. - Tools may return `{"error": ...}` envelopes on upstream failure. Callers should check the result with the structured-error helper before assuming success and indexing into other fields. """, ) - coin_mcp/core.py:206-217 (helper)The _http_get helper used by get_token_dex_price to make the actual HTTP GET request to DefiLlama. Delegates to the TTL cache layer.
async def _http_get( url: str, params: dict[str, Any] | None = None, headers: dict[str, str] | None = None, ) -> Any: """GET a URL and return JSON, or a structured error dict on failure. Delegates to the in-process TTL cache so repeated identical requests don't re-hit the network. See `coin_mcp.cache` for routing rules. """ from . import cache # local import to avoid circular dependency at module load return await cache.cached_http_get(url, params=params, headers=headers) - coin_mcp/core.py:32-32 (helper)DEFILLAMA_COINS_BASE constant ('https://coins.llama.fi') used to construct the API URL for the price fetch.
DEFILLAMA_COINS_BASE = "https://coins.llama.fi"