DeFAI MCP
Provides DeFi execution on BNB Chain (BSC Testnet), including market and yield scanning, yield deposits and rotation, token swaps and transfers, cross-DEX arbitrage, delta-neutral positions, portfolio tracking, and trade history.
Allows linking Telegram for alert delivery and provides a Telegram bot interface for natural-language DeFi commands and monitoring.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
DeFAI MCP — AI-Powered DeFi Agent for BNB Chain via Model Context Protocol
The first MCP server that gives AI agents real DeFi execution on BNB Chain. 19 MCP tools for yield farming, cross-DEX arbitrage, token transfers, and delta-neutral strategies — all gasless via ERC-4337 Account Abstraction.
2026 update — GCP / Vertex AI pivot. The project now ships on Cloud Run with Cloud SQL Postgres, Vertex AI Gemini 3 Pro / Flash, Vertex AI embeddings for episodic memory, and Secret Manager. The original Groq / Llama / SQLite stack still works as a one-flag fallback (
LLM_PROVIDER=groq). Seedocs/DEPLOY.mdfor the deploy runbook.
Why MCP?
AI assistants like Claude can reason about DeFi — but they can't do DeFi. There are zero MCP servers for on-chain DeFi operations on BNB Chain. DeFAI MCP changes that.
With DeFAI MCP installed, Claude can:
You: "What are the best yields on BSC?"
Claude: [calls scan_markets tool] → "Venus BNB is at 3.8% APY, highest across 60+ pools"
You: "Deposit 0.1 BNB into Venus"
Claude: [calls yield_deposit tool] → Real on-chain tx, gasless → "Done. Position tracked."
You: "Run arbitrage for 6 hours, stop if I lose $5"
Claude: [calls arb_auto_start tool] → Autonomous bot scanning every 30s
You: "How's my portfolio?"
Claude: [calls portfolio tool] → Full breakdown: positions, PnL, yield earnedThis isn't a chatbot wrapper. It's a full DeFi execution layer exposed as MCP tools.
Related MCP server: BNB Chain MCP Server
User Journey
flowchart TD
A("🔍 **DISCOVER**\nFind DeFAI MCP on GitHub / BNBChain Hackathon\nRead README — understand MCP + BNB Chain")
B("⚙️ **INSTALL**\nInstall Node.js 18+ · Clone repo\nnpm install --legacy-peer-deps\nGet API keys: Pimlico · Groq · Telegram BotFather\nConfigure .env file")
C("📝 **REGISTER**\nnpm run dev → backend starts on :3002\nOpen dashboard: localhost:5173\nPaste private key → Smart Account created on BSC Testnet\nReceive: UUID · API Key · Smart Account address")
D("💰 **FUND**\nCopy Smart Account address from dashboard\nRequest testnet BNB from BSC Faucet\nVerify balance on testnet.bscscan.com")
E("🤖 **USE MCP WITH CLAUDE**\nnpm run build → compiles to dist/\nAdd defai block to claude_desktop_config.json\nRestart Claude Desktop\nAsk Claude: scan markets · deposit · run arbitrage\nClaude calls MCP tools → real on-chain execution")
F("💬 **USE TELEGRAM**\n/connect UUID → bot linked to your account\nSend natural language: 'deposit 0.05 BNB'\nLLM agent router → tool call → execution")
G("📊 **MONITOR ON DASHBOARD**\nLog in with API Key\nView: portfolio · positions · PnL · trade history\nReceive alerts: APY drops · arb opportunities · position health")
A --> B --> C --> D --> E --> F --> G
style A fill:#1a1a1a,color:#F5C518,stroke:#F5C518,stroke-width:2px
style B fill:#1a1a1a,color:#F5C518,stroke:#F5C518,stroke-width:2px
style C fill:#1a1a1a,color:#F5C518,stroke:#F5C518,stroke-width:2px
style D fill:#1a1a1a,color:#F5C518,stroke:#F5C518,stroke-width:2px
style E fill:#1a1a1a,color:#F5C518,stroke:#F5C518,stroke-width:2px
style F fill:#1a1a1a,color:#F5C518,stroke:#F5C518,stroke-width:2px
style G fill:#1a1a1a,color:#F5C518,stroke:#F5C518,stroke-width:2px19 MCP Tools — Full DeFi Toolkit for AI Agents
Tool | What it does |
| Test connectivity to DeFAI MCP server |
| Register/resume wallet, get Smart Account address |
| Live APYs (Venus/Beefy/DefiLlama), DEX prices, funding rates, arb spreads |
| Deposit into highest-APY protocol (auto-selects best) |
| Rotate position to higher APY when rates shift |
| PancakeSwap V2 swap (BNB, USDT, any pair) |
| Transfer tokens to external address (BNB, USDT, WBNB) |
| Scan cross-DEX spreads and execute best arbitrage |
| Start autonomous arb bot (scans every 30s for N hours) |
| Stop the autonomous arb session |
| Check auto-arb P&L, trades executed, time remaining |
| Open hedged position: spot buy + virtual short |
| Close delta-neutral position, realize PnL |
| View/update risk limits (position size, slippage, exposure) |
| Enable APY drop, arb opportunity, or position health alerts |
| View alert configs and last trigger times |
| Link Telegram for alert delivery |
| Full portfolio: positions, PnL, yield earned |
| Past trades with type/limit filters |
MCP Resources: defai://protocols — lists all supported protocols with real vs simulated status.
Complete Setup Guide
Follow every step in order. Each step is required.
Step 1 — Install prerequisites
You need Node.js 18 or higher and npm 9 or higher.
# Check your versions
node --version # must be >= 18.0.0
npm --version # must be >= 9.0.0If Node.js is not installed, download it from nodejs.org (choose the LTS version).
Step 2 — Get your API keys
OR Skip Step 2 by justing visiting this doc link to just copy paste api from there (for judges)
https://docs.google.com/document/d/1ECsU_Vd0UP4Ed10Ru9_j2QfHIsIdnQiTM_1gE1yed44/edit?usp=sharing
You need four external API keys before you can run the project. Get them now, in any order.
2a. Pimlico API key (pays gas fees for users)
Go to dashboard.pimlico.io
Sign up for a free account
Create a new API key
In the API key settings, enable BSC Testnet (Chain ID 97)
Copy the key — it looks like
pim_xxxxxxxxxxxxxxxxxxxx
2b. Groq API key (LLM for Telegram natural language)
Go to console.groq.com
Sign up for a free account
Navigate to API Keys → Create API Key
Copy the key — it looks like
gsk_xxxxxxxxxxxxxxxxxxxx
2c. Telegram Bot token (bot interface)
Open Telegram and search for @BotFather
Send
/newbotChoose a name (e.g.
DeFAI MCP) and a username (e.g.defai_mcp_bot— must end inbot)BotFather sends you a token — it looks like
123456789:ABCdef...Save both the token and the @username (without the
@)
2d. Generate a private key (your agent's on-chain identity)
This is an Ethereum EOA private key used to create your Smart Account on BSC Testnet. Generate one securely:
openssl rand -hex 32
# outputs: a64f3c... (64 hex characters — this is your PRIVATE_KEY)Important: Never use a wallet that holds real mainnet funds. Generate a fresh key for this agent.
2e. Generate a JWT secret (dashboard authentication)
openssl rand -base64 32
# outputs: something like: K9mX2p...== (this is your JWT_SECRET)Step 3 — Clone the repository and install dependencies
git clone https://github.com/<your-org>/defai-mcp.git
cd defai-mcp
# Install backend dependencies
# --legacy-peer-deps is required due to a viem/permissionless peer conflict
npm install --legacy-peer-deps
# Install dashboard dependencies
cd dashboard && npm install && cd ..Step 4 — Configure your environment file
The project includes a .env.example template with detailed comments for each variable:
cp .env.example .envOpen the [.env.example](.env.example) file to see full descriptions of each variable, then fill in your .env:
Variable | Required | Get it from |
| Yes | Generate: |
| Yes | dashboard.pimlico.io (enable BSC Testnet) |
| Yes | @BotFather on Telegram ( |
| Yes | From BotFather (without the |
| Yes (Groq path) | console.groq.com/keys. Required when |
| Yes | ≥32 chars. Generate: |
| Yes | ≥32 chars. Same generation command. Process refuses to start if missing or shorter. |
| No | Leave blank for default public RPC |
| No | Leave blank (defaults to |
| No | Leave blank on first run — fill in after dashboard registration |
| No | Optional feature |
Vertex AI path (optional) | ||
| No | Set to |
| If | Your GCP project ID. |
| No | Vertex region. Default |
Cloud Run / Postgres (production) | See docs/DEPLOY.md. | |
| No |
|
| If using Cloud SQL / local Postgres | Either set the Cloud SQL connection name (with Auth Proxy sidecar) OR a |
Your completed .env should look like:
PRIVATE_KEY=a64f3c8d...your64hexchars...
PIMLICO_API_KEY=pim_xxxxxxxxxxxxxxxxxxxx
TELEGRAM_BOT_TOKEN=123456789:ABCdef...
TELEGRAM_BOT_USERNAME=defai_mcp_tele_bot
GROQ_API_KEY=gsk_xxxxxxxxxxxxxxxxxxxx
JWT_SECRET=K9mX2p...==
ENCRYPTION_KEY=
BSC_TESTNET_RPC=
MCP_TRANSPORT=
DEFAI_USER_ID=
TINYFISH_API_KEY=Tip: See .env.example for the full list of variables (including the Phase 7 Vertex AI / Cloud Run vars) with detailed comments explaining each one. Production deploy steps are in docs/DEPLOY.md.
Step 5 — Start the backend
In Terminal 1, run:
npm run devYou should see logs like:
[INFO] SQLite database initialized
[INFO] REST API server started on port 3002
[INFO] Telegram bot launched
[INFO] Yield watcher started (every 5 min)
[INFO] Arb watcher started (every 2 min)Leave this running. If you see errors, check the Troubleshooting section.
Step 6 — Start the dashboard
In Terminal 2, run:
cd dashboard && npm run devYou should see Local: http://localhost:5173. Leave this running.
Step 7 — Register on the dashboard
This is how your private key stays private. You enter it once in a secure HTTPS form. The server encrypts it with AES-256-GCM and returns a UUID you use everywhere else — Claude and Telegram never see your private key.
The Register tab should be selected by default
Paste your private key into the Private Key field (it's masked — shows dots)
Click Register
You should see a green "Registration successful!" banner with three items:
Item | What it is |
Smart Account address | Your ERC-4337 gasless wallet on BSC Testnet — click to view on BSCScan |
User ID (UUID) | Your identity token — used in Claude config and Telegram |
API Key ( | Used to log in to the dashboard |
Copy both the UUID and the API Key and save them. The page also shows ready-to-use setup instructions for Claude and Telegram — keep it open for the next steps.
Step 8 — Fund your Smart Account
Your Smart Account needs a small amount of testnet BNB to execute on-chain transactions.
Copy the Smart Account address from the registration page
Paste your Smart Account address and request testnet BNB (you'll receive 0.1 BNB)
Verify on testnet.bscscan.com — paste the address and confirm the balance
Pimlico sponsors gas via the Paymaster, but the Smart Account still needs a small BNB balance for BSC Testnet interactions.
Step 9 — Build and configure Claude Desktop
How MCP works with Claude Desktop: You do not run
npm run mcpmanually. Claude Desktop reads the config below and spawns the MCP server itself as a background child process when it opens — and kills it when it closes. You just need the compiled output to exist.
First, compile the TypeScript:
npm run build
# This creates dist/ — Claude Desktop loads dist/src/mcp/server.jsRe-run
npm run buildany time you update the code and want Claude Desktop to pick up the changes.
Open your Claude Desktop config:
OS | Location |
macOS |
|
Windows |
|
Replace (or add) the defai block with:
{
"mcpServers": {
"defai": {
"command": "/opt/homebrew/bin/node",
"args": ["dist/src/mcp/server.js"],
"cwd": "/absolute/path/to/defai-mcp",
"env": {
"DEFAI_USER_ID": "<paste your UUID here>"
}
}
}
}
eg: {
"preferences": {
"coworkScheduledTasksEnabled": true,
"sidebarMode": "chat",
"coworkWebSearchEnabled": false
},
"mcpServers": {
"defai": {
"command": "/opt/homebrew/bin/node",
"args": [
"--require",
"/Users/user/Documents/LEARNING/breaking down /defai-mcp/loadEnv.js",
"/Users/user/Documents/LEARNING/breaking down /defai-mcp/dist/src/mcp/server.js"
],
"env": {
"DEFAI_USER_ID": "<your dashboard generated user id from private key>"
}
}
}
}Replace /absolute/path/to/defai-mcp with the actual path, and paste your UUID from Step 7 into DEFAI_USER_ID.
Quit Claude Desktop completely (Cmd+Q) and reopen it.
Step 10 — Test MCP in Claude
Once Claude restarts, open a new conversation and try these in order:
ping the defai server
→ pong — DeFAI MCP is alive on BSC Testnet (Chain 97)
show my portfolio
→ Your smart account address + empty positions (no wallet_setup needed!)
scan all markets
→ Live APYs from Venus/Beefy, BNB/USDT prices, funding rates, arb opportunities
show my risk settings
→ Default limits (max position $1000, etc.)If you want to test a live deposit:
Fund your smart account first (Step 8)
Then ask Claude:
deposit 0.01 BNB to best yield
MCP with SSE transport — Connect to the hosted server (no local setup needed):
If the DeFAI server is deployed (e.g. on Railway), you can connect Claude Desktop directly to the remote MCP SSE endpoint without cloning the repo or running anything locally.
Add this to your Claude Desktop config (claude_desktop_config.json):
{
"mcpServers": {
"defai": {
"url": "https://defai-mcp-production.up.railway.app/sse",
"headers": {
"Authorization": "Bearer <your-api-key>"
}
}
}
}Replace <your-api-key> with the API key you received after registering on the dashboard (dfai_k_...).
No cloning, no
npm install, no build step. Just register on the dashboard, get your API key, and point Claude at the SSE URL.
For local SSE development:
npm run mcp:sse # Starts SSE server on port 3001Step 11 — Connect Telegram
Live bot: @defai_mcp_tele_bot — or search
@defai_mcp_tele_botin Telegram. If you're running your own instance, use the bot you created with BotFather in Step 2c.
Open t.me/defai_mcp_tele_bot (or your own bot)
Send
/start— you'll see the welcome messageSend
/connect <your-UUID>(the UUID from Step 7)The bot replies: "Linked! Your Telegram is now connected to user..."
Send
/portfolio— should show the same data as MCP
Try natural language — the bot uses a Groq LLM agent router:
/scan — market data
how much BNB can I earn in a week — conversational reply from LLM
deposit 0.05 BNB in best yield — bot asks for confirmation, then executesStep 12 — Log in to the dashboard
Go back to http://localhost:5173
Click Go to Login (or switch to the Login tab)
Paste your API Key (
dfai_k_...from Step 7)Click Login
Navigate through the sections:
Portfolio — smart account address, open positions, total value
Trades — trade history (everything done via MCP or Telegram appears here)
Markets — live APYs, prices, historical charts
Settings — alert configuration
Everything done via MCP tools or Telegram is recorded in the same SQLite DB — it all shows up here in real-time.
Step 13 — Verify everything is working
# Backend health check
curl http://localhost:3002/api/health
# Expected: {"status":"ok","service":"defai-api","chain":"BSC Testnet (97)"}
# Dashboard
open http://localhost:5173
# Telegram
# Send /portfolio to your bot — should return wallet info
# BSCScan
# https://testnet.bscscan.com/address/<your-smart-account-address>How it all fits together
Dashboard Register (private key entered once, securely)
↓
UUID + API Key
↙ ↘
Claude config Telegram /connect <uuid>
(DEFAI_USER_ID)
↓ ↓
All MCP tools All bot commands
work automatically work automatically
↘ ↙
Same DB → Same portfolio
visible on DashboardYour private key never appears in chat, config files, or environment variables passed to Claude. It lives encrypted in the server's SQLite database, decrypted only at runtime using the server-side ENCRYPTION_KEY.
All available commands
Command | What it starts | Port | When to use |
| Bot + crons + API server (all-in-one) | 3002 | Always — your main backend process |
| Compile TypeScript to | — | Before first Claude Desktop use, and after any code changes |
| MCP server — stdio transport | stdin/stdout | Manual debugging only — not needed for Claude Desktop (it auto-starts from |
| MCP server — SSE transport | 3001 | Web-based MCP clients or remote AI agents |
| REST API only | 3002 | When you want the API without the bot/crons |
| Telegram bot only | — | When you want the bot without the API |
| React dashboard (Vite dev server) | 5173 | Local dashboard development |
Normal local setup uses only two terminals:
# Terminal 1 — backend (bot + crons + API)
npm run dev
# Terminal 2 — dashboard UI
cd dashboard && npm run dev
# One-time (or after code changes) — compile for Claude Desktop
npm run buildDocker (one command, optional)
docker-compose up --build
# API + Dashboard on http://localhost:3002Troubleshooting
Error | Cause | Fix |
| EntryPoint/Factory version mismatch | Ensure both are v0.7 (check |
| permissionless/viem | Always use |
MCP server output breaks | Logger writing to stdout | pino must write to stderr (fd 2). Check |
Bot ignores commands | Handler registration order | Commands must be registered before |
Wallet init hangs | Singleton | Restart the process |
| Smart Account has no testnet BNB | Fund via BSC Testnet Faucet |
Dashboard shows 401 | JWT token expired or wrong secret | Check |
Telegram bot not responding | Wrong token or username in | Double-check |
Groq errors | Invalid API key | Verify |
Telegram 400 "can't parse entities" | Underscores in position IDs treated as Markdown italic markers | Never use |
| UUID entered before dashboard registration | Register on dashboard first (Step 7), then use the UUID shown |
MCP tools need |
| Add |
Architecture
graph TB
subgraph MCP_Layer["MCP Server (19 tools)"]
STDIO["stdio Transport<br/>(Claude Desktop)"]
SSE["SSE Transport<br/>(Web / AI Agents)"]
end
subgraph Other["Other Transports"]
TG["Telegram Bot<br/>(Agent Router — LLM tool-calling)"]
API["REST API<br/>(Express + JWT)"]
DASH["React Dashboard"]
end
subgraph Engine["Core Engine"]
ENG["engine.ts — Orchestrator"]
RM["Risk Manager"]
WM["Wallet Manager"]
end
subgraph Strategies["Strategy Layer"]
YO["Yield Optimizer"]
AS["Arb Scanner"]
DN["Delta-Neutral"]
end
subgraph Protocols["Protocol Adapters"]
VA["Venus<br/>(Real Testnet)"]
PA["PancakeSwap V2<br/>(Real Testnet)"]
TA["Thena + BiSwap<br/>(Simulated)"]
end
subgraph BSC["BSC Testnet (ERC-4337)"]
AA["Smart Account"]
PM["Pimlico Paymaster<br/>(Gasless)"]
end
STDIO & SSE --> ENG
TG --> ENG
API --> ENG
DASH --> API
ENG --> RM --> YO & AS & DN
YO --> VA
AS --> PA & TA
DN --> PA
VA & PA --> AA --> PM
ENG --> WM --> AATech Stack
Layer | Technology |
MCP Server | @modelcontextprotocol/sdk (stdio + SSE) |
Blockchain | viem + BSC Testnet (Chain 97) |
Account Abstraction | permissionless + Pimlico (ERC-4337 v0.7) |
AI / LLM | Groq SDK (Llama 3.3 70B) |
Telegram Bot | Telegraf |
REST API | Express 5 + JWT |
Dashboard | React + Vite + Tailwind CSS + React Query |
Database | better-sqlite3 (WAL mode) |
Encryption | AES-256-GCM + scrypt |
Monitoring | node-cron (5 background watchers) |
Language | TypeScript (strict mode, ES2022) |
On-Chain Contracts (BSC Testnet)
Contract | Address | Explorer |
EntryPoint v0.7 |
| |
SimpleAccountFactory v0.7 |
| |
Pimlico Paymaster |
| |
Venus vBNB |
| |
PancakeSwap V2 Router |
| |
WBNB Testnet |
| |
USDT Testnet |
|
Documentation
Document | Contents |
Problem, solution, MCP tools, business model, roadmap | |
Architecture, setup guide, demo walkthrough | |
Demo video, slides, live access links | |
On-chain contract addresses |
License
Built by DefAI MCP for the BNBChain Hackathon.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Non-custodial USDC yield vaults on Base mainnet with 9 MCP tools for AI agent treasury.
Agent MCP: 72 tools — 10 live chains, prediction & crypto trends, 17 web tools.
Agent MCP: 72 tools — 10 live chains, prediction & crypto trends, 17 web tools.
Native Solana staking for AI agents. 26 MCP tools, one-shot signing, webhooks.
Related MCP Servers
- FlicenseCqualityBmaintenanceEnables AI agents to interact with any EVM-compatible blockchain through natural language, supporting token swaps, cross-chain bridges, staking, lending, governance, gas optimization, and portfolio tracking across networks like Ethereum, BSC, Polygon, Arbitrum, and more.10041 npm44-
- AlicenseNot gradedqualityNot gradedmaintenanceA comprehensive Model Context Protocol server that enables AI agents to interact with BNB Chain, opBNB, and other EVM networks through natural language. It provides tools for DeFi trading, DEX swaps, smart contract deployment, token operations, security analysis, and market data across multiple blockchain networks.40 npm-

Bink MCP Serverofficial
AlicenseNot gradedqualityDmaintenanceEnables AI agents to perform blockchain operations like wallet management, token info, DeFi swaps, cross-chain bridging, and price checking across Ethereum, BNB Chain, and Solana.ISC- AlicenseNot gradedqualityDmaintenanceEnables AI-powered chat and DeFi operations (swap, transfer) via MCP-compliant tools, integrating with LLMs for onchain actions.8 npmMIT