MC-Flow - Pay-Per-Use MCP Server with x402 Micropayments
*Let AI Agents Pay for What They Use*
   
Enable AI agents to autonomously pay for premium tools using crypto micropayments on Cronos
🎯 Overview
MC-Flow revolutionizes how AI agents consume and pay for blockchain services by combining:
- Model Context Protocol (MCP): Standardized protocol for AI agent tool integration
- x402 Programmable Payments: HTTP 402 Payment Required standard with EIP-3009 authorization
- Tiered Pricing: Free, Premium, and Ultra tool tiers with automatic micropayment handling
- Cronos EVM Integration: Fast, low-cost transactions on Cronos testnet/mainnet
The Problem We Solve
- Agent Payment Friction: AI agents can't handle traditional payment systems or subscriptions
- Pay-Per-Use Gap: No infrastructure for agents to pay only for what they use
- Manual Intervention: Current systems require human approval for every transaction
- Web3 Complexity: Difficult barrier for AI agents to interact with DeFi protocols
Our Solution
MC-Flow provides a complete MCP server where:
- AI Agents discover tools with transparent pricing through MCP protocol
- Payments flow automatically via x402 when premium tools are used
- Tools execute blockchain operations (swaps, portfolio analysis, arbitrage) seamlessly
- Creators monetize their MCP tools without managing payment infrastructure
✨ Key Features
1. Tiered Tool Marketplace
Free Tier (No Payment Required):
- Get Cronos Balance (CRO & ERC20 tokens)
- Get Gas Price (current network fees)
- Get Token Price (real-time via CoinGecko)
- Check Transaction Status (by hash)
- Check x402 Status (payment system health)
Premium Tier (0.25-1.0 USDCe per use):
- Analyze Wallet Portfolio (diversification metrics, risk analysis)
- Get Historical Price Data (OHLCV charts)
- Find Arbitrage Opportunities (DEX scanner)
- Optimize Swap Route (best path across VVS, MM Finance)
Ultra Tier (5.0-7.5 USDCe per use):
- Execute Token Swap (automated DEX trading)
- Auto-Compound Rewards (DeFi yield optimization)
2. x402 Automatic Payment Flow
// How it works:
1. Agent requests premium tool
2. Server checks tool tier & price
3. x402 payment processed automatically via Crypto.com Facilitator
4. Tool executes only after payment verification
5. Transaction logged with full transparency3. Crypto.com Facilitator Integration
- EIP-3009 Support: Gasless token transfers with signature authorization
- USDCe Payments: Stablecoin micropayments on Cronos
- Payment Verification: On-chain settlement with txHash proof
- Balance Tracking: Pre/post payment balance verification
- Detailed Logging: Complete payment audit trail in x402-payments.log
4. Comprehensive Blockchain Tools
DeFi Operations:
- Real-time gas price monitoring
- Token price feeds (CoinGecko integration)
- DEX route optimization
- Arbitrage opportunity detection
Wallet Management:
- Multi-token balance checking
- Transaction status tracking
- Portfolio analysis with diversification scores
Advanced Trading:
- VVS Finance integration
- Slippage protection
- Auto-compounding for yield farms
🏗️ Architecture
┌─────────────────────────────────────────────────────────────┐
│ MCP Client (Claude/AI Agent) │
│ - Tool Discovery via MCP Protocol │
│ - Automatic x402 Payment Handling │
│ - Tool Execution with Arguments │
└─────────────────┬───────────────────────────────────────────┘
│
│ MCP stdio Transport
│
┌────────▼──────────────────────────┐
│ MC-Flow MCP Server │
│ (Node.js + TypeScript) │
│ │
│ ┌──────────────────────────┐ │
│ │ Tool Executor │ │
│ │ - Free Tools (direct) │ │
│ │ - Premium (+ payment) │ │
│ │ - Ultra (+ payment) │ │
│ └──────────────────────────┘ │
│ │
│ ┌──────────────────────────┐ │
│ │ Payment Service │ │
│ │ - Price checking │ │
│ │ - Balance verification │ │
│ │ - x402 orchestration │ │
│ └──────────────────────────┘ │
│ │
│ ┌──────────────────────────┐ │
│ │ X402 Service │ │
│ │ - Facilitator client │ │
│ │ - EIP-3009 signing │ │
│ │ - Payment settlement │ │
│ │ - Transaction logging │ │
│ └──────────────────────────┘ │
└────────┬───────────────────────────┘
│
├──────────────┬─────────────────────────────┐
│ │ │
┌────────▼──────┐ ┌───▼─────────┐ ┌─────────▼────────┐
│ Cronos EVM │ │ CoinGecko │ │ VVS Finance │
│ (Testnet) │ │ API │ │ DEX │
│ │ │ │ │ │
│ - USDCe Token │ │ - Prices │ │ - Swap Router │
│ - Gas Oracle │ │ - 24h Data │ │ - Liquidity │
│ - Txn Status │ │ │ │ │
└────────────────┘ └─────────────┘ └──────────────────┘Component Breakdown
MCP Server (/src)
- index.ts: Main server initialization with request handlers
- services/: Core business logic
- ToolExecutor.ts: Routes tool calls to implementations - PaymentService.ts: Price checking, balance verification, payment orchestration - X402Service.ts: Crypto.com Facilitator integration, EIP-3009 signing - CronosService.ts: Blockchain interactions (balances, prices, transactions)
- tools/: Tool implementations organized by tier
- free/: No-cost utilities (balance, gas, price checking) - premium/: Advanced analytics (portfolio, arbitrage, routing) - ultra/: Execution tools (swaps, auto-compound)
- config/: Configuration files
- tools.ts: Tool definitions with pricing and schemas - blockchain.ts: Network configs, contract addresses, providers
- utils/: Helper functions (error handling, price conversion)
Smart Contracts (External)
- USDCe Token: ERC-20 stablecoin for payments on Cronos
- VVS Router: DEX aggregator for token swaps
- Facilitator Contracts: x402 payment settlement infrastructure
🛠️ Tech Stack
MCP Server
- TypeScript
- @modelcontextprotocol/sdk (MCP Protocol)
- @crypto.com/facilitator-client (x402 Payments)
- ethers.js v6 (Blockchain interactions)
- axios (HTTP requests)
- dotenv (Environment management)
Blockchain
- Cronos EVM Testnet (Chain ID: 338)
- Cronos EVM Mainnet (Chain ID: 25)
- USDCe Token (ERC-20)
- EIP-3009 (TransferWithAuthorization)
External APIs
- CoinGecko API (Token prices)
- Cronos RPC (Blockchain data)
- VVS Finance (DEX operations)
🔄 How It Works
1. Free Tool Execution
// Example: Get token price (free)
1. Agent calls tool: get_token_price({ symbol: "CRO" })
2. Server checks tier: "free"
3. Directly executes CronosService.getTokenPrice()
4. Returns: { symbol: "CRO", price: 0.124, change24h: 1.2 }
5. No payment required2. Premium Tool with x402 Payment
// Example: Analyze portfolio (0.5 USDCe)
1. Agent calls: analyze_wallet_portfolio({ address: "0x..." })
2. Server checks tier: "premium", price: 0.5 USDCe
3. PaymentService verifies user USDCe balance
4. X402Service creates payment header:
- Generates EIP-3009 signature
- Sets validBefore timestamp
- Specifies recipient, amount, asset
5. Facilitator verifies signature
6. Payment settles on-chain (txHash returned)
7. Balance deduction confirmed
8. Tool executes: analyzePortfolio()
9. Returns result with payment details:
{
success: true,
tier: "premium",
paymentMethod: "x402",
paymentDetails: { txHash, amount, balanceAfter },
data: { totalValueUSD, assets, riskLevel, ... }
}3. Ultra Tool Execution
// Example: Execute swap (5.0 USDCe)
1. Agent calls: execute_token_swap({
tokenIn: "0x...",
tokenOut: "0x...",
amountIn: "10",
slippage: 0.5
})
2. Payment flow same as premium (5.0 USDCe)
3. After payment:
- Approves tokenIn to VVS Router
- Gets expected output via getAmountsOut()
- Calculates minOutput with slippage
- Executes swapExactTokensForTokens()
4. Returns: { txHash, swappedAmount, receivedMin }4. Payment Verification & Logging
Every payment is logged to x402-payments.log:
==============================================================================
🚀 [PAYMENT analyze_wallet_portfolio-1737820800000] Starting payment
==============================================================================
📊 PAYMENT DETAILS:
Payment ID: analyze_wallet_portfolio-1737820800000
From: 0xYourWallet...
To: 0xRecipient...
Tool: analyze_wallet_portfolio
Amount: 0.5 USDCe
Asset: 0xc21223249CA28397B4B6541dfFaEcC539BfF0c59
💰 BALANCE BEFORE: 10.0 USDCe
🔐 Generating payment header...
✅ Header generated (532 chars)
📝 Generating requirements...
✅ Requirements: { payTo, maxAmountRequired, ... }
🔍 Verifying payment...
✅ Payment verified!
⚡️ Settling payment on-chain...
🎉 PAYMENT SETTLED!
Transaction: 0xabcd1234...
Explorer: https://explorer.cronos.org/testnet/tx/0xabcd1234...
Block: 12345678
💰 BALANCE AFTER: 9.5 USDCe
💸 AMOUNT SPENT: 0.5 USDCe
==============================================================================
✅ PAYMENT analyze_wallet_portfolio-1737820800000 COMPLETED
==============================================================================📦 Installation
Prerequisites
- Node.js >= 18
- npm, yarn, or pnpm
- Cronos wallet with testnet CRO (for gas) and USDCe (for payments)
- Git
1. Clone Repository
git clone https://github.com/yourusername/mc-flow.git
cd mc-flow2. Install Dependencies
npm install3. Environment Setup
Create .env file in root:
# Network (testnet or mainnet)
NETWORK=testnet
# Wallet (CRITICAL: Keep private key secure!)
PRIVATE_KEY=your_private_key_here
DEFAULT_USER_ADDRESS=your_wallet_address_here
# Payment Recipient (where x402 payments go)
PAYMENT_RECIPIENT_ADDRESS=recipient_wallet_address_here
# CoinGecko API (Optional but recommended)
COINGECKO_API_KEY=your_coingecko_api_key
# Cronos RPC (Optional, uses defaults if not set)
CRONOS_TESTNET_RPC=https://evm-t3.cronos.org
CRONOS_MAINNET_RPC=https://evm.cronos.orgSecurity Notes:
- Never commit .env to git (already in .gitignore)
- Use separate wallets for dev/production
- Fund testnet wallet with USDCe from faucet
4. Get Testnet Tokens
- Testnet CRO (for gas):
- Visit Cronos Testnet Faucet - Enter your wallet address - Receive testnet CRO
- USDCe (for payments):
- Use Crypto.com Facilitator SDK faucet - Or bridge from another testnet
5. Build Project
npm run buildThis compiles TypeScript to /dist folder.
🚀 Running the Server
Development Mode (with hot reload)
npm run devUses tsx to run TypeScript directly with auto-restart on file changes.
Production Mode
npm run build
npm startRuns compiled JavaScript from /dist.
Expected Output
✅ MCP Payment Server initialized with x402
📋 Listing tools...
🚀 Cronos MCP Server with x402 Payments READY🧪 Testing with MCP Inspector
The Model Context Protocol provides an inspector tool for testing:
1. Install MCP Inspector
npx @modelcontextprotocol/inspector2. Configure Inspector
Point inspector to your built server:
{
"mcpServers": {
"mc-flow": {
"command": "node",
"args": ["dist/index.js"],
"env": {
"NETWORK": "testnet"
}
}
}
}3. Test Tool Calls
Free Tool Example:
{
"name": "get_token_price",
"arguments": {
"symbol": "CRO"
}
}Premium Tool Example (requires USDCe):
{
"name": "analyze_wallet_portfolio",
"arguments": {
"address": "0xYourWalletAddress"
}
}🏆 Hackathon Tracks
✅ Dev Tooling & Data Virtualization Track
- ✅ MCP Server with 10+ blockchain tools
- ✅ Tiered tool marketplace infrastructure
- ✅ Payment orchestration layer for developer tools
- ✅ Comprehensive logging and audit trails
- ✅ Reusable payment service architecture
✅ x402 Agentic Finance/Payment Track
- ✅ Automated settlement pipeline (verify → settle → log)
- ✅ Multi-step x402 automation (payment + execution)
- ✅ Crypto.com Facilitator SDK integration
- ✅ Balance verification and transaction logging
✅ Crypto.com X Cronos Ecosystem Integration
- ✅ Crypto.com Facilitator Client for x402 payments
- ✅ Cronos EVM testnet/mainnet support
- ✅ VVS Finance DEX integration (swap routing)
- ✅ CoinGecko price feeds for token valuation
- ✅ Native CRO and ERC-20 token operations
📊 Tool Catalog
Free Tools (Tier: 🆓)
| Tool ID | Description | Arguments |
|---|---|---|
| get_cronos_balance | Check CRO/token balance | address, token? |
| get_gas_price | Current network gas price | None |
| get_token_price | Real-time token price (CoinGecko) | symbol |
| check_transaction_status | Transaction details by hash | txHash |
| check_x402_status | Payment system health check | None |
Premium Tools (Tier: 💳)
| Tool ID | Price | Description | Arguments |
|---|---|---|---|
| analyze_wallet_portfolio | 0.5 USDCe | Portfolio analysis with risk metrics | address |
| get_historical_price_data | 0.25 USDCe | OHLCV historical charts | symbol, days |
| find_arbitrage_opportunities | 1.0 USDCe | Cross-DEX arbitrage scanner | minProfitUSD? |
| optimize_swap_route | 0.4 USDCe | Best route across VVS/MM Finance | tokenIn, tokenOut, amountIn |
Ultra Tools (Tier: 💎)
| Tool ID | Price | Description | Arguments |
|---|---|---|---|
| execute_token_swap | 5.0 USDCe | Execute DEX swap on VVS | tokenIn, tokenOut, amountIn, slippage? |
| auto_compound_rewards | 7.5 USDCe | Auto-compound DeFi yields | protocol, poolAddress |
🔐 Security Features
- Private Key Protection:
- Never logged or exposed - Stored only in .env (gitignored) - Used only for signing transactions
- Payment Verification:
- EIP-3009 signature validation - On-chain settlement confirmation - Balance verification before/after payment
- Error Handling:
- Custom ToolError class with error codes - Graceful degradation (CoinGecko API fallback) - Detailed error messages with suggestions
- ReentrancyGuard (for future smart contracts):
- Prevents reentrancy attacks - Safe withdrawal patterns
- Input Validation:
- MCP schema validation for all tools - Type safety with TypeScript - Zod schemas for runtime validation
🤝 Contributing
We welcome contributions! Please follow these steps:
- Fork the repository
- Create feature branch (
git checkout -b feature/AmazingTool) - Add your tool to
/src/tools/in appropriate tier - Update TOOLS array in
/src/config/tools.ts - Add execution logic to ToolExecutor.ts
- Write tests (coming soon)
- Commit changes (
git commit -m 'Add AmazingTool') - Push to branch (
git push origin feature/AmazingTool) - Open Pull Request
Adding a New Tool
Example: Add a premium tool for NFT floor price checking (0.3 USDCe)
- Create tool file:
/src/tools/premium/getNFTFloorPrice.ts
import axios from 'axios';
export async function getNFTFloorPrice(collectionAddress: string) {
const response = await axios.get(`https://api.nft-data.com/floor/${collectionAddress}`);
return {
collection: collectionAddress,
floorPrice: response.data.floorPrice,
currency: 'CRO'
};
}- Add to tools config:
/src/config/tools.ts
{
id: 'get_nft_floor_price',
name: 'Get NFT Floor Price',
description: 'Get current floor price for NFT collection',
tier: 'premium',
priceInCRO: 0.3,
priceInUSDC: 0.006,
inputSchema: {
type: 'object',
properties: {
collectionAddress: {
type: 'string',
description: 'NFT collection contract address'
}
},
required: ['collectionAddress']
}
}- Add executor logic:
/src/services/ToolExecutor.ts
case 'get_nft_floor_price':
return await getNFTFloorPrice(args.collectionAddress);- Test with MCP inspector
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Cronos Labs for x402 Facilitator SDK and documentation
- Crypto.com for Developer Platform and testnet infrastructure
- Anthropic for Model Context Protocol specification
- VVS Finance for DEX integration opportunities
- CoinGecko for reliable price data APIs
- OpenZeppelin for security best practices
📞 Contact & Links
- GitHub:
- Twitter: [@aaveshtwt]
- Email: saifiaavesh01@gmail.com
🐛 Known Issues & Future Fixes
- CoinGecko Rate Limits: Free tier has 50 calls/minute - implementing caching
- Gas Price Volatility: Need dynamic gas estimation for swaps
- Testnet Faucet: USDCe faucet sometimes slow - working on alternative sources
- MCP Inspector: Requires manual stdio connection - exploring HTTP transport
📚 Additional Resources
- MCP Protocol Specification
- Cronos Documentation
- x402 Facilitator SDK
- EIP-3009: Transfer With Authorization
- VVS Finance Docs
Built for the future of AI-powered payments on Cronos EVM 🚀
*MC-Flow: Where AI Agents Meet Micropayments* ⚡💰🤖
