Skip to main content
Glama
clumsynonono

Aave Liquidation MCP Server

by clumsynonono

analyze_liquidation

Analyze Aave V3 positions to identify liquidation opportunities by evaluating collateral assets, debt composition, risk levels, and potential profit.

Instructions

Analyze a user position for liquidation opportunity. Returns detailed information including collateral assets, debt assets, risk level, and potential profit.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
addressYesEthereum address to analyze (must be a valid address)

Implementation Reference

  • src/index.ts:67-80 (registration)
    Registration of the 'analyze_liquidation' tool in the MCP server's listTools handler, including name, description, and input schema definition.
      name: 'analyze_liquidation',
      description:
        'Analyze a user position for liquidation opportunity. Returns detailed information including collateral assets, debt assets, risk level, and potential profit.',
      inputSchema: {
        type: 'object',
        properties: {
          address: {
            type: 'string',
            description: 'Ethereum address to analyze (must be a valid address)',
          },
        },
        required: ['address'],
      },
    },
  • MCP CallToolRequest handler case for 'analyze_liquidation': validates input address, calls AaveClient.analyzeLiquidationOpportunity, handles no-opportunity case, and returns JSON-formatted result.
    case 'analyze_liquidation': {
      const address = args?.address as string;
      if (!address || typeof address !== 'string') {
        throw new McpError(
          ErrorCode.InvalidParams,
          'address parameter is required and must be a string'
        );
      }
    
      if (!aaveClient.isValidAddress(address)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'Invalid Ethereum address format'
        );
      }
    
      const opportunity = await aaveClient.analyzeLiquidationOpportunity(address);
    
      if (!opportunity) {
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  message: 'No liquidation opportunity found. Position is healthy.',
                  address,
                },
                null,
                2
              ),
            },
          ],
        };
      }
    
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(opportunity, null, 2),
          },
        ],
      };
    }
  • Core implementation of liquidation analysis in AaveClient: fetches account data and reserves, determines risk level, calculates potential profit considering close factor and liquidation bonuses per collateral asset.
    async analyzeLiquidationOpportunity(
      userAddress: string
    ): Promise<LiquidationOpportunity | null> {
      const accountData = await this.getUserAccountData(userAddress);
    
      // Only return if liquidatable or at risk
      if (!accountData.isLiquidatable && !accountData.isAtRisk) {
        return null;
      }
    
      const { collateral, debt } = await this.getUserReserves(userAddress);
    
      // Calculate risk level
      const hf = parseFloat(accountData.healthFactorFormatted);
      let riskLevel: 'HIGH' | 'MEDIUM' | 'LOW';
      if (hf < LIQUIDATION_THRESHOLD) {
        riskLevel = 'HIGH';
      } else if (hf < 1.02) {
        riskLevel = 'MEDIUM';
      } else {
        // 1.02 <= hf < WARNING_THRESHOLD (1.05)
        riskLevel = 'LOW';
      }
    
      // Format values in USD (base is already in USD with 8 decimals from oracle)
      const totalCollateralUSD = ethers.formatUnits(accountData.totalCollateralBase, 8);
      const totalDebtUSD = ethers.formatUnits(accountData.totalDebtBase, 8);
      const availableBorrowsUSD = ethers.formatUnits(accountData.availableBorrowsBase, 8);
    
      // Calculate potential profit with actual liquidation bonus
      let potentialProfit = '0';
      if (accountData.isLiquidatable) {
        const debtValue = parseFloat(totalDebtUSD);
    
        // Close factor: can liquidate up to 50% of debt
        const maxDebtByCloseFactor = debtValue * 0.5;
    
        // Fetch prices for collateral assets to avoid overstating profit
        const priceMap = collateral.length
          ? await this.getAssetsPrices(collateral.map((c) => c.asset))
          : new Map<string, string>();
    
        let bestEstimatedProfit = 0;
    
        for (const c of collateral) {
          const priceStr = priceMap.get(c.asset);
          const price = priceStr ? parseFloat(priceStr) : 0;
          if (!price) {
            continue;
          }
    
          // Convert collateral balance to USD using token decimals and oracle price (8 decimals)
          const collateralAmount = parseFloat(ethers.formatUnits(c.currentATokenBalance, c.decimals));
          const collateralValueUSD = collateralAmount * price;
    
          // liquidationBonus is in bps, e.g. 10500 => 5% bonus
          const bonusPercentage = Math.max(0, Number(c.liquidationBonus) - 10000) / 10000;
          if (bonusPercentage <= 0) {
            continue;
          }
    
          // Debt that can be covered by this collateral considering bonus
          const maxDebtByCollateral = collateralValueUSD / (1 + bonusPercentage);
    
          // Actual liquidatable debt for this collateral
          const liquidatableDebt = Math.min(maxDebtByCloseFactor, maxDebtByCollateral, debtValue);
          const estimatedProfit = liquidatableDebt * bonusPercentage;
    
          if (estimatedProfit > bestEstimatedProfit) {
            bestEstimatedProfit = estimatedProfit;
          }
        }
    
        potentialProfit = bestEstimatedProfit.toFixed(2);
      }
    
      return {
        userAddress,
        healthFactor: accountData.healthFactorFormatted,
        totalCollateralUSD,
        totalDebtUSD,
        availableBorrowsUSD,
        liquidationThreshold: parseFloat(
          ethers.formatUnits(accountData.currentLiquidationThreshold, 4)
        ),
        collateralAssets: collateral,
        debtAssets: debt,
        potentialProfit,
        riskLevel,
        gasWarning: 'Profit calculation does not include Gas costs. Actual profit will be lower.',
      };
    }
Behavior2/5

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

With no annotations, the description carries full burden. It states the tool returns 'detailed information' but doesn't disclose behavioral traits like whether this is a read-only operation, requires authentication, has rate limits, or what happens with invalid addresses. The description is functional but lacks critical operational context for a financial analysis tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences with zero waste: first states purpose, second describes return values. Appropriately sized and front-loaded with the core function. Could be slightly more structured but earns its place efficiently.

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

Completeness3/5

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

For a single-parameter tool with no annotations and no output schema, the description provides adequate purpose and return value overview. However, it lacks completeness regarding error conditions, authentication needs, and detailed behavioral context that would be important for a liquidation analysis tool in financial systems.

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 description coverage is 100% (address parameter fully documented in schema), so baseline is 3. The description adds no additional parameter semantics beyond what's in the schema - it doesn't explain address format requirements, network context, or validation behavior.

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 tool's purpose: 'Analyze a user position for liquidation opportunity' with specific verb ('analyze') and resource ('user position'). It distinguishes from siblings like 'get_user_positions' (which likely lists positions) by focusing on liquidation analysis, but doesn't explicitly contrast with 'get_user_health' which might provide similar risk assessment.

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

Usage Guidelines3/5

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

The description implies usage when assessing liquidation risk ('for liquidation opportunity'), but provides no explicit guidance on when to use this versus alternatives like 'get_user_health' or 'get_user_positions'. No prerequisites, exclusions, or comparative context are 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/clumsynonono/aave-liquidation-mcp'

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