Skip to main content
Glama

get_defi_health

Assess DeFi ecosystem health by analyzing total TVL, trends, top chains, protocols, health scores, revenue patterns, and concentration risks.

Instructions

Assess DeFi ecosystem health: total TVL, TVL trends, top chains and protocols, health score, revenue trends, and ecosystem concentration risk.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The handler function `getDefiHealth` retrieves DeFi market data (TVL, chains, protocols, fees), processes it into a health report, and caches the result.
    export async function getDefiHealth(cache: CacheService): Promise<DefiHealthOutput | ErrorOutput> {
      const cached = cache.get<DefiHealthOutput>(CACHE_KEY);
      if (cached) return cached.data;
    
      try {
        const [historicalTvl, chains, protocols, feesResult] = await Promise.allSettled([
          getHistoricalTvl(),
          getChains(),
          getProtocols(),
          getFees(),
        ]);
    
        // Total TVL and changes
        let totalTvl = 0;
        let tvlChange24h = 0;
        let tvlChange7d = 0;
    
        if (historicalTvl.status === 'fulfilled') {
          const data = historicalTvl.value;
          if (data.length > 0) {
            totalTvl = data[data.length - 1].tvl;
            if (data.length > 1) {
              const yesterday = data[data.length - 2].tvl;
              tvlChange24h = yesterday > 0 ? ((totalTvl - yesterday) / yesterday) * 100 : 0;
            }
            if (data.length > 7) {
              const weekAgo = data[data.length - 8].tvl;
              tvlChange7d = weekAgo > 0 ? ((totalTvl - weekAgo) / weekAgo) * 100 : 0;
            }
          }
        }
    
        // TVL trend
        const tvlTrend = classifyTvlTrend(tvlChange7d);
    
        // Top chains
        let topChains: ChainTvl[] = [];
        if (chains.status === 'fulfilled') {
          const sorted = chains.value.sort((a, b) => b.tvl - a.tvl).slice(0, 10);
          const totalChainTvl = sorted.reduce((s, c) => s + c.tvl, 0);
          topChains = sorted.map(c => ({
            name: c.name,
            tvl_usd: c.tvl,
            tvl_change_7d: 0, // Not directly available from chains endpoint
            dominance_percentage: totalChainTvl > 0 ? Math.round((c.tvl / totalChainTvl) * 10000) / 100 : 0,
          }));
        }
    
        // Top protocols
        let topProtocols: ProtocolTvl[] = [];
        if (protocols.status === 'fulfilled') {
          topProtocols = protocols.value
            .sort((a, b) => b.tvl - a.tvl)
            .slice(0, 10)
            .map(p => ({
              name: p.name,
              tvl_usd: p.tvl,
              category: p.category ?? 'Unknown',
              change_7d: p.change_7d ?? 0,
            }));
        }
    
        // Protocol revenue trend
        let revenueTrend: RevenueTrend = 'stable';
        if (feesResult.status === 'fulfilled' && feesResult.value.protocols) {
          const topFeeProtocols = feesResult.value.protocols
            .filter(p => p.total24h !== null && p.total7d !== null)
            .slice(0, 10);
    
          if (topFeeProtocols.length > 0) {
            const avgDaily = topFeeProtocols.reduce((s, p) => s + (p.total24h ?? 0), 0) / topFeeProtocols.length;
            const avgWeeklyDaily = topFeeProtocols.reduce((s, p) => s + ((p.total7d ?? 0) / 7), 0) / topFeeProtocols.length;
            if (avgWeeklyDaily > 0) {
              const ratio = avgDaily / avgWeeklyDaily;
              if (ratio > 1.2) revenueTrend = 'growing';
              else if (ratio < 0.8) revenueTrend = 'declining';
            }
          }
        }
    
        // Ecosystem concentration
        const topChainDominance = topChains.length > 0 ? topChains[0].dominance_percentage : 0;
        const concentration: EcosystemConcentration =
          topChainDominance > 70 ? 'dangerous' :
          topChainDominance > 40 ? 'concentrated' :
          'healthy';
    
        // Health score
        const healthScore = calculateHealthScore(tvlChange7d, topChainDominance, revenueTrend);
    
        const guidance = generateDefiGuidance(tvlTrend, healthScore, concentration, revenueTrend, totalTvl);
    
        const result: DefiHealthOutput = {
          total_tvl_usd: totalTvl,
          tvl_change_24h: Math.round(tvlChange24h * 100) / 100,
          tvl_change_7d: Math.round(tvlChange7d * 100) / 100,
          tvl_trend: tvlTrend,
          top_chains: topChains,
          top_protocols: topProtocols,
          defi_health_score: healthScore,
          protocol_revenue_trend: revenueTrend,
          ecosystem_concentration: concentration,
          agent_guidance: guidance,
        };
    
        cache.set(CACHE_KEY, result, getCacheTtl(BASE_TTL));
        return result;
    
      } catch (err) {
        return {
          error: true,
          error_source: 'get_defi_health',
          agent_guidance: 'DeFi health data unavailable. Without DeFi context, avoid yield farming or protocol-specific positions. Stick to spot holdings until DeFi data is restored.',
          last_known_data: cache.get<DefiHealthOutput>(CACHE_KEY)?.data ?? null,
          data_warnings: ['DeFi data source temporarily unavailable. Retry shortly.'],
        };
      }
    }
Behavior3/5

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

With no annotations provided, the description carries the full burden. It adequately describes the conceptual output (TVL trends, health scores) substituting for the missing output schema, but lacks operational details like data sources, caching behavior, or freshness of data.

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 efficient colon structure. Front-loaded purpose ('Assess DeFi ecosystem health') followed by specific metric enumeration. No redundant words.

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?

Appropriately compensates for missing output schema by enumerating expected return data (TVL, revenue trends, concentration risk). For a zero-parameter read-only tool, this provides sufficient context, though data source or latency notes would improve it.

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?

Input schema contains zero parameters. Per scoring guidelines, zero parameters warrants a baseline score of 4.

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?

Clear verb ('Assess') and resource ('DeFi ecosystem health') with specific output metrics listed (TVL, health score, concentration risk). Implicitly distinguishes from siblings like get_asset_context or get_chain_context by focusing on ecosystem-wide DeFi metrics, though lacks explicit comparison.

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?

Lists what data is returned but provides no guidance on when to use this versus alternatives like get_chain_context or get_macro_context. No prerequisites or conditions 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/0xHashy/fathom-fyi'

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