← Back to home

Aetheros

MCP server connecting Claude to Hedera DeFi with 36 tools for analytics and transactions.

Problem Statement

OverviewAetherosis a comprehensive Model Context Protocol (MCP) server that bridges the gap between AI assistants and the Hedera DeFi ecosystem. It transforms how users interact with decentralized finance by enabling natural language conversations with AI (like Claude) to query data, analyze opportunities, and prepare transactions across multiple DeFi platforms—all without requiring deep technical knowledge or compromising security.What It Does - In Detail1.Unified Multi-Platform DeFi AccessAetheros provides a single, standardized interface to interact with5 major Hedera DeFi platforms, eliminating the need to understand each platform's unique API, smart contract interface, or data format:SaucerSwap(19 tools): Hedera's leading decentralized exchange (DEX)Access liquidity pools, farming opportunities, and single-sided stakingGet real-time token prices and historical HBAR price dataQuery V1 and V2 pool reserves, fees, and trading volumesPrepare swap transactions with optimal routingManage SAUCE staking (SAUCE → xSAUCE) and farm depositsBonzo Finance(3 tools): Lending and borrowing protocolView all lending reserves with APYs and utilization ratesCheck account positions (supplied, borrowed, collateral)Identify liquidation opportunities for profitable arbitrageStader Labs(3 tools): Liquid staking protocolGet real-time HBAR to HBARX exchange ratesPrepare HBAR staking transactionsPrepare HBARX unstaking transactionsHeliSwap(1 tool): Alternative DEXQuery trading pair information and reservesHashport(10 tools): Cross-chain bridgeList supported assets across 7+ blockchain networksGet step-by-step bridging instructionsValidate bridge parameters before executionTrack transfer history and asset reservesConvert transaction ID formatsTotal: 36 comprehensive toolscovering every aspect of Hedera DeFi operations.2.Dual-Mode Security ArchitectureAetheros solves the critical security vs. automation dilemma through an innovative two-mode system:Prepare Mode (Default - Maximum Security)Generates complete, unsigned transaction dataPrivate keys never loaded into memoryUsers can sign with hardware wallets (Ledger, D'CENT, etc.)Perfect for high-value operations and institutional useProvides full transparency: contract addresses, function calls, gas limits, payable amountsExample Output:{ "type": "prepared_transaction", "description": "Swap 10 HBAR for minimum 1,000,000 SAUCE tokens", "from": "0.0.123456", "to": "0x00000000000000000000000000000000002cc9B2", "function": "multicall(bytes[])", "gas": 400000, "value": "1000000000", "unsigned": { "contractId": "0x00000000000000000000000000000000002cc9B2", "functionName": "multicall", "functionParams": ["0xc04b8d59000000..."], "payableAmount": "1000000000" } }Execute Mode (Advanced - Full Automation)Automatically signs and submits transactions to Hedera networkIdeal for automated trading bots and strategiesReturns transaction IDs and confirmation statusRequires explicit environment variable (EXECUTE_TX=true) and private key3.Real-Time DeFi AnalyticsAsk questions in plain English and get instant, formatted data:Examples:"What's the current HBAR to HBARX exchange rate?" →1.0247 (staking rewards accumulated)"Show me the best yield farms on SaucerSwap" → Returns sorted farms by APY with TVL and reward rates"Get SAUCE/USDC pool reserves" → Returns exact token amounts and pool liquidity"Which Bonzo accounts are eligible for liquidation?" → Lists accounts with health factors below 1.04.Transaction Preparation with AI GuidanceInstead of manually constructing complex smart contract calls, simply describe what you want:User:"I want to swap 50 HBAR for SAUCE tokens"Aetheros:Fetches current SAUCE token address and pool informationCalculates optimal route (direct or multi-hop)Gets price quote with slippage protectionGenerates complete unsigned transaction with:Proper function encoding for SaucerSwap RouterHBAR wrapping (HBAR → WHBAR) if neededRecipient address conversion (Hedera ID → EVM address)Gas estimation and value amountsRefund handling for excess HBARAll ready for signing with your preferred wallet.5.Cross-Chain Bridge IntelligenceHashport integration enables seamless asset bridging:Query supported tokens on Ethereum, Polygon, Avalanche, BNB Chain, etc.Get exact bridging steps with required approvalsValidate amounts and addresses before bridgingTrack bridge transaction statusView total value locked across chainsThe Problem It SolvesPain Point #1:Fragmentation & ComplexityHedera's DeFi ecosystem spans multiple protocols, each with:Different API structures (REST vs GraphQL vs on-chain queries)Unique authentication requirementsVarying data formats and unitsComplex smart contract interfaces requiring ABI knowledgeSolution:Aetheros abstracts all complexity into simple, natural language commands. One interface, 36 tools, 5 platforms.Pain Point #2:Manual Monitoring & AnalysisDeFi traders manually:Check multiple websites for prices and APYsCalculate optimal routes across DEXsMonitor liquidation opportunitiesTrack farming rewards across platformsSolution:Ask Aetheros to monitor conditions, compare rates, or identify opportunities—all through conversation.Pain Point #3:Security Risks in AutomationExisting automation tools require:Exposing private keys to scriptsTrusting third-party servicesRunning unsafe code from unverified sourcesSolution:Prepare-only mode generates transactions without ever accessing private keys. Sign with your hardware wallet or secure environment.Pain Point #4:No AI IntegrationTraditional DeFi tools lack AI capabilities:No natural language queriesNo intelligent routing or optimizationNo conversational transaction buildingSolution:Built on MCP, enabling Claude and other AI assistants to safely interact with Hedera DeFi using your natural language.Real-World Use CasesPortfolio Management: "Show my positions across all Hedera DeFi platforms"Yield Optimization: "Find the best HBAR staking rate between Stader and SaucerSwap farms"Arbitrage Detection: "Alert me when USDC price differs by >0.5% between SaucerSwap and HeliSwap"Automated Strategies: "Stake all my farming rewards back into the highest APY pool"Bridge Operations: "How do I bridge 1000 USDC from Ethereum to Hedera?"Risk Management: "Show Bonzo accounts near liquidation with >$10k collateral"Technical InnovationFirst MCP Server for Hedera DeFi: Pioneering AI-native DeFi interactions100% Success Rate: All 36 tools tested and working (see TEST_RESULTS.md)Type-Safe: Full TypeScript with Zod schema validationProduction Ready: Published on npm asaetheroswith 1-command installationComprehensive: Covers data queries, analytics, and transaction preparationInstallation & Usage# Install globally npm install -g aetheros # Or use directly with npx npx aetherosClaude Desktop Integration(claude_desktop_config.json):{ "mcpServers": { "hedera-defi": { "command": "npx", "args": ["-y", "aetheros"] } } }Then simply chat with Claude:"Get all SaucerSwap tokens""Prepare a transaction to stake 100 HBAR""Show me the best yield opportunities on Hedera"Why It MattersAetheros democratizes DeFi by removing technical barriers. Whether you're a:Beginner: Ask questions in plain EnglishTrader: Automate strategies without codingDeveloper: Build on a unified, type-safe APIInstitution: Prepare transactions with hardware wallet securityYou can now leverage Hedera's fast, low-cost DeFi ecosystem through the power of AI assistance.

Solution

Architecture OverviewAetheros is built using amodular client-based architecturewhere each DeFi platform has its own dedicated client class, all exposed through a unified MCP server interface. This design enables independent platform updates without breaking other integrations.┌─────────────────────────────────────────────────────┐ │ MCP Server (src/index.ts) │ │ - Tool registration & schema validation │ │ - Request routing & response formatting │ └─────────────────────────────────────────────────────┘ │ ┌──────────────┼──────────────┐ │ │ │ ┌────▼───┐ ┌────▼───┐ ┌────▼───┐ │SaucerSwap│ │ Bonzo │ │ Stader │ ... │ Client │ │ Client │ │ Client │ └──────────┘ └────────┘ └────────┘ │ │ │ ┌────▼───────┐ ┌───▼──────┐ ┌────▼────────┐ │ REST APIs │ │Smart │ │ @hashgraph/ │ │ + Contracts│ │Contracts │ │ sdk │ └────────────┘ └──────────┘ └─────────────┘Core Technology Stack1.Runtime & LanguageTypeScript 5.3+(typescript@^5.3.0)Strict type checking withstrict: truein tsconfig.jsonESM modules for modern JavaScript compatibilityInterfaces for all platform responses and transaction typesNode.js 18+ESM module system ("type": "module"in package.json)Native async/await support for all API callsEnvironment variable management viadotenv@^16.3.1tsx(tsx@^4.6.0)Development hot-reloading withnpm run devDirect TypeScript execution without compilation step2.MCP Protocol Implementation@modelcontextprotocol/sdk(@modelcontextprotocol/sdk@^0.5.0)Serverclass for MCP server initializationStdioServerTransportfor stdio-based communication with Claude DesktopTool registration with JSON schemas generated from Zodimport { Server, StdioServerTransport } from "@modelcontextprotocol/sdk/server/index.js"; import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"; const server = new Server( { name: "aetheros", version: "1.0.6" }, { capabilities: { tools: {} } } ); // Register 36 tools with schemas server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ { name: "saucerswap_get_tokens", description: "Get all available tokens on SaucerSwap", inputSchema: zodToJsonSchema(GetTokensSchema) }, // ... 35 more tools ] }));3.Schema ValidationZod(zod@^3.22.0) +zod-to-json-schema(zod-to-json-schema@^3.24.6)Runtime validation of all tool inputsAutomatic JSON Schema generation for MCPType inference for TypeScript compilerimport { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; // Example: SaucerSwap swap schema const SwapHbarForTokensSchema = z.object({ accountId: z.string().describe("Hedera account ID (0.0.xxxxx)"), tokenOut: z.string().describe("Output token address"), amountIn: z.string().describe("HBAR amount in tinybars"), fee: z.number().describe("Pool fee tier (500, 3000, 10000)"), slippage: z.number().min(0).max(100).default(0.5) }); type SwapParams = z.infer<typeof SwapHbarForTokensSchema>;4.Hedera Blockchain Integration@hashgraph/sdk(@hashgraph/sdk@^2.45.0)Clientfor Hedera network connections (mainnet/testnet)AccountIdfor Hedera address handlingPrivateKeyfor transaction signing in execute modeContractExecuteTransactionfor smart contract interactionsContractCallQueryfor read-only contract queriesimport { Client, AccountId, PrivateKey, ContractExecuteTransaction, ContractFunctionParameters } from "@hashgraph/sdk"; // Initialize Hedera client const client = Client.forMainnet(); client.setOperator( AccountId.fromString(process.env.MAINNET_HEDERA_OPERATOR_ID!), PrivateKey.fromString(process.env.MAINNET_HEDERA_OPERATOR_KEY!) ); // Execute contract transaction const tx = await new ContractExecuteTransaction() .setContractId("0.0.2917554") .setGas(400000) .setFunction("stake", params) .setPayableAmount(amountInHbar) .execute(client);5.Smart Contract InteractionsEthers.js v6(ethers@^6.9.0)Interfacefor ABI encoding/decodingsolidityPackedfor parameter encodingContractclass for type-safe contract callsBigNumber handling for precise token amountsimport { ethers } from "ethers"; // Encode SaucerSwap multicall const routerInterface = new ethers.Interface([ "function multicall(bytes[] calldata data) external payable returns (bytes[] memory)", "function exactInputSingle((address,address,uint24,address,uint256,uint256,uint256)) external payable returns (uint256)" ]); const swapParams = { tokenIn: WHBAR_ADDRESS, tokenOut: tokenOutAddress, fee: feeAmount, recipient: evmAddress, deadline: BigInt(Math.floor(Date.now() / 1000) + 300), amountIn: BigInt(amountIn), amountOutMinimum: BigInt(minAmountOut) }; const encodedSwap = routerInterface.encodeFunctionData("exactInputSingle", [swapParams]);6.HTTP Client & API IntegrationAxios(axios@^1.6.0)REST API calls to SaucerSwap, Bonzo, HashportAutomatic JSON parsing and error handlingRequest/response interceptors for loggingTimeout management for rate-limited endpointsimport axios from "axios"; // SaucerSwap API with authentication const saucerswapApi = axios.create({ baseURL: "https://api.saucerswap.finance", headers: { "Authorization": `Bearer ${process.env.SAUCERSWAP_API_KEY}`, "Content-Type": "application/json" }, timeout: 30000 }); // Bonzo Finance API (public) const bonzoApi = axios.create({ baseURL: "https://mainnet-api.bonzo.finance/api/v1", timeout: 15000 });Platform-Specific Implementation DetailsSaucerSwap Client(src/clients/saucerswap.ts)Challenges:API Rate Limiting: SaucerSwap's public API has strict rate limitsSolution: Implemented graceful degradation and retry logicCache responses where appropriateV1 vs V2 Pools: Different contract interfaces for Uniswap V2 and V3 style poolsSolution: Separate tool implementations with proper ABI handlingTransaction Complexity: Swaps require multicall with WHBAR wrapping/unwrappingSolution: Built helper functions to construct multicall arraysKey Implementation:export class SaucerSwapClient { private apiKey?: string; private client?: Client; private routerAddress: string; private quoterAddress: string; // 19 methods for data queries and transaction preparation async swapHbarForTokens(params: SwapParams) { // 1. Convert Hedera account ID to EVM address const evmAddress = this.accountIdToEvmAddress(params.accountId); // 2. Encode exactInputSingle call const swapCall = this.encodeSwapCall(params, evmAddress); // 3. Encode refundETH call (for excess HBAR) const refundCall = routerInterface.encodeFunctionData("refundETH"); // 4. Construct multicall const multicallData = routerInterface.encodeFunctionData("multicall", [ [swapCall, refundCall] ]); // 5. Return unsigned transaction return { type: "prepared_transaction", contractId: this.routerAddress, functionName: "multicall", functionParams: multicallData, gas: 400000, payableAmount: params.amountIn }; } }Stader Client(src/clients/stader.ts)Challenges:Mainnet Only: Stader contracts only deployed on mainnetSolution: Network detection and graceful error messages on testnetExchange Rate Precision: HBARX rate requires high-precision decimal handlingSolution: Use BigInt for all calculations, format for displayKey Implementation:export class StaderClient { private stakePoolAddress = "0.0.2917554"; async stakeHbar(accountId: string, amount: string) { // Prepare ContractExecuteTransaction const params = new ContractFunctionParameters() .addUint256(BigInt(amount)); return { type: "prepared_transaction", description: `Stake ${amount} tinybars HBAR for HBARX`, contractId: this.stakePoolAddress, functionName: "stake", functionParams: params, gas: 300000, payableAmount: amount }; } }Bonzo Client(src/clients/bonzo.ts)Challenges:Complex Reserve Data: Multiple nested objects with protocol-specific calculationsSolution: Strong TypeScript interfaces for type safetyHealth Factor Calculation: Liquidation logic requires precise decimal mathSolution: Use reserve decimals for accurate calculationsKey Implementation:export class BonzoClient { async getReserves() { const response = await axios.get( "https://mainnet-api.bonzo.finance/api/v1/reserves" ); // Transform API response to user-friendly format return response.data.map((reserve: any) => ({ symbol: reserve.symbol, supplyAPY: (reserve.liquidityRate / 1e27 * 100).toFixed(2), borrowAPY: (reserve.variableBorrowRate / 1e27 * 100).toFixed(2), utilizationRate: (reserve.utilizationRate / 1e27 * 100).toFixed(2), totalSupplied: (BigInt(reserve.totalLiquidity) / BigInt(10 ** reserve.decimals)).toString(), availableLiquidity: (BigInt(reserve.availableLiquidity) / BigInt(10 ** reserve.decimals)).toString() })); } }Hashport Client(src/clients/hashport.ts)Challenges:Multi-Network Support: 7+ different blockchain networksSolution: Network ID mapping and validationAsset ID Formats: Different formats across chains (ERC20 addresses vs Hedera token IDs)Solution: Flexible string handling with validationKey Implementation:export class HashportClient { private baseUrl = "https://mainnet.hashport.network/api/v1"; async getSupportedAssets() { const response = await axios.get(`${this.baseUrl}/assets`); return response.data.map((asset: any) => ({ symbol: asset.symbol, name: asset.name, networks: asset.supportedNetworks.map((net: any) => ({ networkId: net.networkId, networkName: net.networkName, assetId: net.assetId, isNative: net.isNative })) })); } async getBridgeSteps(sourceNetwork: string, targetNetwork: string, assetId: string) { // Query bridge contract for step-by-step instructions // Includes: approvals, lock/burn, mint/unlock steps } }Security Implementation1. Environment-Based Mode Selectionconst EXECUTE_TX = process.env.EXECUTE_TX === "true"; const network = process.env.HEDERA_NETWORK || "mainnet"; // Only load private key if execute mode enabled let operatorKey: PrivateKey | undefined; if (EXECUTE_TX) { const keyEnvVar = network === "mainnet" ? "MAINNET_HEDERA_OPERATOR_KEY" : "TESTNET_HEDERA_OPERATOR_KEY"; operatorKey = PrivateKey.fromString(process.env[keyEnvVar]!); }2. Transaction Preparation vs Executionasync function handleTransactionTool(params: any) { const unsignedTx = await prepareTransaction(params); if (!EXECUTE_TX) { // Return unsigned transaction for external signing return { type: "prepared_transaction", ...unsignedTx, instructions: "Sign this transaction with your wallet or dApp" }; } // Execute mode: sign and submit const tx = buildTransaction(unsignedTx); const signedTx = await tx.sign(operatorKey!); const receipt = await signedTx.execute(client); return { type: "executed_transaction", transactionId: receipt.transactionId.toString(), status: receipt.status.toString() }; }Build & DistributionDevelopment Workflow{ "scripts": { "dev": "tsx src/index.ts", // Hot reload development "build": "tsc", // Compile TypeScript to dist/ "start": "node dist/index.js", // Run production build "watch": "tsx watch src/index.ts", // Watch mode "prepublishOnly": "npm run build" // Auto-build before publish } }TypeScript Configuration(tsconfig.json){ "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "node", "outDir": "./dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "declaration": true, // Generate .d.ts files "declarationMap": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] }NPM Package Configuration{ "name": "aetheros", "version": "1.0.6", "type": "module", "main": "dist/index.js", "bin": { "aetheros": "dist/index.js" // CLI command }, "files": [ "dist/**/*", // Include compiled files "README.md", "LICENSE", ".env.example" ], "engines": { "node": ">=18.0.0" // Require Node 18+ } }Particularly Hacky/Notable Implementations1. Hedera Account ID to EVM Address ConversionHedera uses account IDs (0.0.xxxxx) but smart contracts need EVM addresses (0x...). We convert by:function accountIdToEvmAddress(accountId: string): string { const parts = accountId.split('.'); const num = parseInt(parts[2]); // Hedera's EVM address: 0x0000000000000000000000000000000000{accountNum in hex} return '0x' + num.toString(16).padStart(40, '0'); }2. Multicall Transaction BuilderSaucerSwap swaps require multiple steps (swap + refund). We encode them into a single multicall:function buildMulticallSwap(params: SwapParams) { const calls: string[] = []; // 1. Wrap HBAR to WHBAR (if needed) if (params.tokenIn === HBAR) { calls.push(encodeWrapHbar(params.amountIn)); } // 2. Execute swap calls.push(encodeExactInputSingle(params)); // 3. Unwrap WHBAR back to HBAR (if output is HBAR) if (params.tokenOut === HBAR) { calls.push(encodeUnwrapWHBAR(params.amountOut)); } // 4. Refund excess HBAR calls.push(routerInterface.encodeFunctionData("refundETH")); return routerInterface.encodeFunctionData("multicall", [calls]); }3. Graceful API DegradationSaucerSwap API requires authentication, but we still work without it:async getTokens() { try { if (this.apiKey) { // Use authenticated endpoint (more reliable) return await this.authenticatedApi.get('/tokens'); } } catch (error) { console.warn("Authenticated API failed, falling back to public endpoint"); } // Fallback to public endpoint (rate limited) return await this.publicApi.get('/tokens'); }4. BigInt JSON SerializationJavaScript's JSON.stringify() doesn't support BigInt, causing errors. We patch it:// Monkey patch BigInt serialization (BigInt.prototype as any).toJSON = function() { return this.toString(); };Testing & VerificationTest Coverage: 36/36 tools tested (100% success rate)Testing Methodology:Manual testing via Claude Desktop integrationProgrammatic testing with test-mcp-tools.jsNetwork-specific testing (mainnet vs testnet)Rate limit and timeout handling verificationResults: See TEST_RESULTS.md for comprehensive results including:Response sizes and performance metricsKnown API limitations and workaroundsPlatform availability by networkWhy These Technologies?TypeScript: Type safety prevents runtime errors in financial operationsMCP: First-class AI integration, future-proof protocolZod: Runtime validation ensures user inputs are safe before blockchain submission@hashgraph/sdk: Official SDK, optimized for Hedera's unique consensusEthers.js: Industry standard for EVM contract interactionsAxios: Robust HTTP client with excellent error handlingFuture EnhancementsImmediate:Add Bonzo transaction preparation (lend/borrow/repay)Implement intelligent swap routing across multiple DEXsAdd WebSocket support for real-time price updatesAdvanced:Flash loan support for arbitrage strategiesBatch transaction builder for complex DeFi operationsPosition monitoring with customizable alertsIntegration with additional Hedera DeFi platformsLong-term:Become the standard MCP server for Hedera DeFiEnable AI-driven yield optimization strategiesSupport for other blockchain ecosystems

Hackathon

ETHOnline 2025

2025

Contributors