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
| Technology | Version | Purpose |
|---|---|---|
| ADK-TS | 0.5.7 | Agent framework and orchestration |
| OpenRouter | 1.2.8 | LLM provider integration |
| Express | 5.2.1 | HTTP server for chat API |
| node-cron | 4.2.1 | Scheduled monitoring tasks |
| ethers.js | (via ADK) | Blockchain interaction |
| Zod | 4.1.12 | Schema validation |
| Dedent | 1.7.0 | Template string formatting |
Agent Hierarchy
Project Structure
ADK-TS Integration
Why ADK-TS?
ADK-TS provides:- Conversation Orchestration: Handles session memory and context
- Tool Management: Structured tool definitions and response formatting
- TypeScript Native: Full type safety for tools and agents
- Sub-Agent Coordination: Hierarchical agent delegation
- State Management: Built-in state caching and persistence
- 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
- 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:
-
Monitoring:
- Track vault state (TVL, shares, NAV)
- Monitor strategy allocations and balances
- Fetch real-time token prices (LINK/WETH)
- Check user balances and growth
-
Risk Management:
- Calculate LTV (Loan-to-Value) ratios
- Detect liquidation risks
- Auto-deleverage when thresholds exceeded
- Pause strategies during high volatility
-
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
-
Decision Making:
- Price-based: Adjust strategy based on LINK/WETH volatility
- LTV-based: Deleverage when LTV > 70%
- Target-based: Rebalance when allocations diverge >5%
get_strategy_states- Read strategy balancesget_user_balances- Read user shares/assetsget_vault_state- Read vault statisticsget_token_prices- Fetch LINK/WETH prices from CoinGeckoget_leverage_strategy_state- Read leverage detailsget_vault_apy- Calculate vault APYcheck_liquidation_risk- Assess liquidation dangerrebalance_vault- Trigger rebalancingharvest_strategy- Collect strategy profitsvault_deposit- Deposit fundsvault_withdraw- Withdraw fundsauto_deleverage- Emergency deleveragingupdate_strategy_target_weights- Change allocationstoggle_leverage_strategy_pause- Pause/unpause leverageupdate_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
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)
- 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)
get_user_balance- Read user sharesget_user_growth- Calculate user PnLprepare_deposit_tx- Create unsigned deposit txprepare_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
- Strategy Sentinel Agent (for data fetching)
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: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
-
Private Key Management:
- Stored in environment variables
- Never logged or exposed
- Separate keys for different environments
-
Tool Access Control:
- Chat Agent: Read-only tools + unsigned tx preparation
- Strategy Sentinel: Full vault management
- Yield Generator: Limited to yield accrual
-
Input Validation:
- All tool parameters validated with Zod schemas
- Amount checks before transactions
- Address validation
-
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
Railway (Recommended)
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