Skip to main content

Overview

The MetaVault AI agent system is built using ADK-TS (Agent Development Kit) by IQAI. It implements a hierarchical multi-agent architecture where specialized agents collaborate to monitor, manage, and optimize the DeFi vault.

Technology Stack

Agent Hierarchy

Project Structure

ADK-TS Integration

Why ADK-TS?

ADK-TS provides:
  1. Conversation Orchestration: Handles session memory and context
  2. Tool Management: Structured tool definitions and response formatting
  3. TypeScript Native: Full type safety for tools and agents
  4. Sub-Agent Coordination: Hierarchical agent delegation
  5. State Management: Built-in state caching and persistence
  6. MCP Integration: Model Context Protocol for tool calling

Agent Builder Pattern

Agent Definitions

1. Root Agent

File: src/agents/agent.ts Purpose: Top-level orchestrator that delegates to specialized sub-agents. Capabilities:
  • Routes requests to appropriate sub-agents
  • Coordinates multi-step operations
  • Manages agent lifecycle
Sub-Agents:
  • Strategy Sentinel Agent
  • Yield Generator Agent

2. Strategy Sentinel Agent

File: src/agents/sub-agents/strategy-sentinel-agent/agent.ts Purpose: The primary vault management agent responsible for monitoring, risk management, and strategy optimization. Key Responsibilities:
  1. Monitoring:
    • Track vault state (TVL, shares, NAV)
    • Monitor strategy allocations and balances
    • Fetch real-time token prices (LINK/WETH)
    • Check user balances and growth
  2. Risk Management:
    • Calculate LTV (Loan-to-Value) ratios
    • Detect liquidation risks
    • Auto-deleverage when thresholds exceeded
    • Pause strategies during high volatility
  3. Portfolio Management:
    • Rebalance between strategies based on targets
    • Adjust target weights based on market conditions
    • Update leverage parameters (maxDepth, borrowFactor)
    • Harvest yields and compound profits
  4. Decision Making:
    • Price-based: Adjust strategy based on LINK/WETH volatility
    • LTV-based: Deleverage when LTV > 70%
    • Target-based: Rebalance when allocations diverge >5%
Instruction Snippet:
Tools (18 total):
  • get_strategy_states - Read strategy balances
  • get_user_balances - Read user shares/assets
  • get_vault_state - Read vault statistics
  • get_token_prices - Fetch LINK/WETH prices from CoinGecko
  • get_leverage_strategy_state - Read leverage details
  • get_vault_apy - Calculate vault APY
  • check_liquidation_risk - Assess liquidation danger
  • rebalance_vault - Trigger rebalancing
  • harvest_strategy - Collect strategy profits
  • vault_deposit - Deposit funds
  • vault_withdraw - Withdraw funds
  • auto_deleverage - Emergency deleveraging
  • update_strategy_target_weights - Change allocations
  • toggle_leverage_strategy_pause - Pause/unpause leverage
  • update_leverage_params - Adjust maxDepth/borrowFactor

3. Yield Generator Agent

File: src/agents/sub-agents/yield-generator-agent/agent.ts Purpose: Simulates yield accrual for testing and demonstration. Capabilities:
  • Accrue interest to mock Aave pool
  • Generate yield events
  • Validate profit distribution
Tools:
  • yield_generator - Accrue interest to the pool

4. Chat Agent

File: src/agents/sub-agents/chat-agent/agent.ts Purpose: Provides natural language interface for users to interact with their vault. Capabilities:
  • Answer questions about vault statistics
  • Check user balances and growth
  • Generate unsigned transactions for deposits/withdrawals
  • Enforce security boundaries (user-specific data only)
Security:
  • NEVER exposes admin functions to users
  • NEVER accesses other users’ data
  • ALWAYS validates wallet address from request
  • Only provides unsigned transactions (user signs in frontend)
Tools:
  • get_user_balance - Read user shares
  • get_user_growth - Calculate user PnL
  • prepare_deposit_tx - Create unsigned deposit tx
  • prepare_withdraw_tx - Create unsigned withdraw tx

5. Telegram Bot Agent

File: src/agents/telegram-agent/agent.ts Purpose: Sends monitoring reports to Telegram channel. Capabilities:
  • Format reports for Telegram (no markdown)
  • Send messages to configured channel
  • Handle monitoring summaries
Sub-Agents:
  • Strategy Sentinel Agent (for data fetching)
Tools (via ADK-TS MCP):
  • telegram_send_message - Send message to channel

Tool System

Tool Definition Pattern

ADK-TS uses a structured tool definition format:

Key Tools

get_token_prices

rebalance_vault

update_strategy_target_weights

Monitoring Service

File: src/crons/automation.ts Purpose: Automated health checks and maintenance tasks.

Cron Schedule

  • Monitoring Cycle: Every 1 hour (0 */1 * * *)
  • Yield Generation: Every 2 minutes (*/2 * * * *)

Monitoring Cycle Steps

Chat Server

File: src/server.ts Purpose: Express server that exposes the Chat Agent via REST API.

Endpoints

POST /chat

Request:
Response:
Response with Transaction:

GET /session/:id

Returns full conversation history for a session.

POST /session/reset/:id

Resets a session’s conversation history.

GET /health

Health check endpoint.

Session Management

Data Flow

Automated Monitoring Flow

User Chat Flow

Security

Agent Security

  1. Private Key Management:
    • Stored in environment variables
    • Never logged or exposed
    • Separate keys for different environments
  2. Tool Access Control:
    • Chat Agent: Read-only tools + unsigned tx preparation
    • Strategy Sentinel: Full vault management
    • Yield Generator: Limited to yield accrual
  3. Input Validation:
    • All tool parameters validated with Zod schemas
    • Amount checks before transactions
    • Address validation
  4. Rate Limiting:
    • Cron jobs on fixed schedule (no excessive polling)
    • API rate limits on external services

Chat Agent Boundaries

Environment Configuration

File: src/env.ts

Deployment

Docker

Monitoring & Logging

Console Logging

Telegram Reports

  • Hourly monitoring summaries
  • Error notifications
  • Action confirmations

Performance Considerations

  • Cron Frequency: Hourly checks to avoid excessive gas costs
  • Tool Caching: ADK-TS handles state caching
  • Batch Queries: Use Promise.all() for parallel reads
  • Error Recovery: Try/catch on all blockchain calls

Future Enhancements

  • Vector DB Integration: Store historical data for ML analysis
  • Multi-Chain Support: Deploy agents across chains
  • Advanced Risk Models: Machine learning for risk prediction
  • Governance Agent: DAO proposal creation and voting
  • Analytics Agent: Generate insights and reports